An array is used to store multiple values of the same data type. In this program, the user enters 5 numbers into an array. The first element is assumed to be both the greatest and the smallest. A for loop then compares each array element with these values. If a smaller value is found, it becomes the new smallest value. If a larger value is found, it becomes the new greatest value. Finally, the program displays the greatest and smallest numbers.
How It Works?
r[5] and the variables s, g, and k.for loop to accept 5 numbers from the user and store them in the array.s and g with the first array element r[0].for loop to compare each element with s and g.s, update s.g, update g.#include <stdio.h> #include <conio.h> main() { int r[5], s = 0, g = 0; int k; clrscr(); for(k = 0; k <= 4; k++) { printf("Enter the Number : "); scanf("%d", &r[k]); } s = g = r[0]; for(k = 0; k <= 4; k++) { printf("\n %d", r[k]); if(s > r[k]) { s = r[k]; } if(g < r[k]) { g = r[k]; } } printf("\n Greatest %d", g); printf("\n Smallest %d", s); getch(); }
for loop.greatest and smallest variables with the first element of the array. Use a for loop to compare each element and update the values whenever a larger or smaller element is found.#include <stdio.h> #include <conio.h> main() { int r[6], s = 0, g = 0; int k; clrscr(); for(k = 0; k <= 5; k++) { printf("Enter the Number : "); scanf("%d", &r[k]); } s = g = r[0]; for(k = 0; k <= 5; k++) { if(s > r[k]) { s = r[k]; } if(g < r[k]) { g = r[k]; } } printf("\nGreatest = %d", g); printf("\nSmallest = %d", s); getch(); }
greatest and smallest variables with the first array element. A for loop compares each element with these variables. If a larger value is found, it updates the greatest value. If a smaller value is found, it updates the smallest value. Finally, the program displays the greatest and smallest numbers in the array.