Problem
Let the user enter four series of integers in the console, find out a number which is smallest and largest in a series
Solution
To calculate the small and large number, we use if conditions. The logic we use to find the largest and smallest number is −
if(minno>q) //checking 1st and 2nd number minno=q; else if(maxno&l;q) maxno=q; if(minno>r) //checking 1st and 3rd number minno=r;
Program 1
#include<stdio.h> int main(){ int minno,maxno,p,q,r,s; printf("enter any four numbers:"); scanf("%d%d%d%d",&p,&q,&r,&s); minno=p; maxno=p; if(minno>q) //checking 1st and 2nd number minno=q; else if(maxno<q) maxno=q; if(minno>r) //checking 1st and 3rd number minno=r; else if(maxno<r) maxno=r; if(minno>s) //checking 1st and 4th number minno=s; else if(maxno<s) maxno=s; printf("Largest number from the given 4 numbers is:%d\n",maxno); printf("Smallest numbers from the given 4 numbers is:%d",minno); return 0; }
Output
enter any four numbers:34 78 23 12 Largest number from the given 4 numbers is:78 Smallest numbers from the given 4 numbers is:12
Program 2
The below program finds the smallest and largest element in an array −
#include<stdio.h> int main(){ int a[50],i,num,large,small; printf("Enter the number of elements :"); scanf("%d",&num); printf("Input the array elements :\n"); for(i=0;i<num;++i) scanf("%d",&a[i]); large=small=a[0]; for(i=1;i<num;++i){ if(a[i]>large) large=a[i]; if(a[i]<small) small=a[i]; } printf("small= %d\n",small); printf("large= %d\n",large); return 0; }
Output
Enter the number of elements :8 Input the array elements : 1 2 6 4 8 9 3 9 small= 1 large= 9