How to know which is greatest number?

May 7, 2016 at 6:15pm
#include<stdio.h>
#include<conio.h>
void main()
{int i,max=0,imax,b;
int a[5];
clrscr();
for (i=1;i<=5;i++)
{
printf("\nEnter number %d:",i);
scanf("%d",&a[i]);
}
for (i=1;i<=5;i++)
{
if (a[i]>max)
{max=a[i];
}
}
printf("\nGreatest number is %d",max);


getch();
}


I created this program to know greatest number, but how to know that which number is highest.
For example i entered 5 numbers 1,2,30,4,5
How to print that 3rd number 30 is largest?
May 7, 2016 at 6:43pm
You are already keeping track of the highest value so keeping track of the index where the highest value is stored you can do in a very similar way. In fact, you don't even need the max variable anymore if you instead keep track of the index.

Note that array indices start at zero so valid indices for an array of size 5 is 0, 1, 2, 3 and 4. You need to fix this in your code because you are accessing a[5] which is out of bounds.
Last edited on May 7, 2016 at 6:46pm
Topic archived. No new replies allowed.