Write a C program to find the largest element in an array
Description: Take 5 numbers in an array and print the largest one.
Hint:
- Assume the first element is the largest. Then compare the others, and update the value if a bigger one is found.
C program to find the largest element in an array
#include <stdio.h>
int main(void) {
int a[5], max;
printf("Enter 5 numbers: ");
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
max = a[0];
for (int i = 1; i < 5; i++) {
if (a[i] > max) {
max = a[i];
}
}
printf("Largest = %d\n", max);
return 0;
}
Output:
Output of the above program is
Enter 5 numbers: 23
91
45
67
12
Largest = 91
How it works
maxstarts as 23. When 91 is found, it is bigger, somaxbecomes 91. No later value is bigger.- For the smallest element, change
>to<.
Learn more about the similar topics:
| Tutorials |
|---|
| C Arrays |
| C Two Dimensional Arrays |
| C Passing Arrays to Functions |
| C Strings |
| C String Input and Output |
| C String Functions |
| C strlen() Function |
| Interview Questions & Answers |
|---|
| What is an array in C? |
| How is a string stored in C? |
| How to reverse a string in C? |
| What is the difference between memcpy() and strcpy() in C? |