Functions – Array Maximum
Write a program to find the maximum element in the array using functions.
Function specification:
int findMax(int n, int *a)
The first argument corresponds to the number of elements in the array.
The second argument corresponds to the pointer to an array.
Input and Output Format:
Input consists of n+1 integers where n corresponds to the number of elements in the array.
The first integer corresponds to n and the next n integers correspond to the elements in the array.
Output consists of a single integer which corresponds to the maximum element in an array.
Assume that the maximum number of elements in the array is 20.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output :
Enter the number of elements in the array
5
Enter the elements in the array
2
4
1
3
5
The maximum element in the array is 5
Function Definitions:
int findMax (int n, int *a)
Solution:
#include < stdio . h >
int findMax( int n,int*a )
{
int max,i;
max=a[1];
for(i=1; i < = n ; i + + )
{
if (a[i] > max )
{
max=a[i];
}
}
return max;
}
int main()
{
int n,a[20],i;
printf("Enter the number of elements in the array\n");
scanf("%d",&n);
printf("Enter the elements in the array\n");
for(i=1 ; i < = n ; i + + )
{
scanf("%d",&a[i]);
}
int m=findMax(n,a);
printf("The maximum element in the array is %d",m);
return 0;
}
Write a program to find the maximum element in the array using functions.
Function specification:
int findMax(int n, int *a)
The first argument corresponds to the number of elements in the array.
The second argument corresponds to the pointer to an array.
Input and Output Format:
Input consists of n+1 integers where n corresponds to the number of elements in the array.
The first integer corresponds to n and the next n integers correspond to the elements in the array.
Output consists of a single integer which corresponds to the maximum element in an array.
Assume that the maximum number of elements in the array is 20.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output :
Enter the number of elements in the array
5
Enter the elements in the array
2
4
1
3
5
The maximum element in the array is 5
Function Definitions:
int findMax (int n, int *a)
Solution:
#include < stdio . h >
int findMax( int n,int*a )
{
int max,i;
max=a[1];
for(i=1; i < = n ; i + + )
{
if (a[i] > max )
{
max=a[i];
}
}
return max;
}
int main()
{
int n,a[20],i;
printf("Enter the number of elements in the array\n");
scanf("%d",&n);
printf("Enter the elements in the array\n");
for(i=1 ; i < = n ; i + + )
{
scanf("%d",&a[i]);
}
int m=findMax(n,a);
printf("The maximum element in the array is %d",m);
return 0;
}
No comments