The C program finds the maximum element in an array entered by the user..
//Write a cprogram to find the maximum element in array
#include<stdio.h>
// find max value function
int maximumInArray(int arr[], int n){
int max = arr[0];
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
int main(){
int n;
printf("Enter the size of the array : ");
scanf("%d", &n);
int arr[n];
// input array from the user
for(int i = 0; i < n; i++){
scanf("%d", &arr[i]);
}
printf("%d is the maximum number", maximumInArray(arr, n));
return 0;
}
#include<stdio.h>
#include<stdio.h> is a preprocessor directive that includes the standard library input/output function. Which is used to use the printf() and scanf() function.
// function to find the maximum
int maximumInArray(int arr[], int n){
int max = arr[0];
for(int i = 0; i < n; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
The maximumInArray() function finds the maximum value in the given array from the user, parameter ‘arr’ takes the all elements which entered from the user, parameter ‘n’ is contains the size of the array. In the last returned the maximum value in the array. ‘int max = arr[0]’ initializing the max element with the frist element of the array, which is help to compare the another value of the element using follow the for loop. Inside the for loop we check every element in the array if any element is maximum of the max value then we change the max value that a particular value, afte return the max value.
int main(){
int n;
printf("Enter the size of the array : ");
scanf("%d", &n);
int arr[n];
// input array from the user
for(int i = 0; i < n; i++){
scanf("%d", &arr[i]);
}
printf("%d is the maximum number", maximumInArray(arr, n));
return 0;
}
The above main() function is the entry point of the program. ‘int n’ is store the size of the array which takes the input from the user. ‘int ar[n]’ is declared the array ‘n’ size which given by the user. Takes the input in array using the for loop and store the element in array at a particular indexed. After takes the array input from the user print the maximum value in the array. return 0; means that the program is successfully executed.
Comments
Oops!