0

C program to find maximum number in an array.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,max,a[5];
clrscr();
printf(“Enter elements of array:”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
max=a[0];
for(i=0;i<5;i++)
{
if(max<a[i])
{
max=a[i];
}

else max = max;
}
printf(“Maximum number in the given array is:%d”,max);
getch();
}

 

Here is the explaination of the code:-

first of all we are declaring an array of size 5 you can take the size by user too. After entering elements by the user lets say we have elements [8,7,2,5,11]. so the statement max = a[0] assign the first element to the variable max. Then the loop executes In which every element of array is compared with max that is it greater then it or not. if true then max is assigned the value of current array element. Else max is same. The last value of max is the maximum element.

for example let’s see by our assumed array. value of max = 8 initially Now it is checked by all other elements

  1. By 7 it is smaller than max so value of max is unchanged.
  2. by 2 it is smaller than max so value of max is unchanged.
  3. by 5 it is smaller than max so value of max is unchanged.
  4. by 11 it is greater than max so max is assigned 11.



ks007

Leave a Reply

Your email address will not be published. Required fields are marked *