Let’s identify variables needed for this program.
In this program, we need several variables to store and compare the values to find the largest and the smallest out of them. Its not recommended to take number of variables declared of the same data type with different names and remembering it. It becomes worst when the variable numbers goes on increasing to large number. Hence we have a savior called ARRAY.
Array is a nothing different than any variable but the only difference is that it allows us to use more than one variables with a single name to it. The size of array is decided by us. We can take 2 to n numbers according to our requirement. It has to be accessed with the help of index number ranging from 0 to n-1. (e.g. num,num,num,num)
First variable will be the one which will save the values entered by the user and it will be NUM. Here we are taking ten different values hence taking number 10. Second variable will be I which will be for FOR Loop. other variables will be holding largest and smallest numbers and it will be LARGE and SMALL so in all Four variables.
The identified variables are NUM,I,LARGE,SMALL.
Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.
In this program there is a requirement of accessing the array NUM,NUM….NUM. Here we have the index values ranging from zero to the given number minus one (i.e. n-1) . Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to 9. We will need two FOR loops, First one for scanning required array values and Second one for comparing all the other numbers to find largest and smallest out of them.
The variable for largest and smallest are already taken. But the problem is both are having no values inside it to compare so the logic is assign the first value to both LARGE and SMALL. So that we have the first value to compare and replace it with the other larger or smaller value with LARGE and SMALL respectively. Comparison is done with the help of IF condition below. FOR Loop the value of loop will start with 1 to 9. We will need this because First value is already assigned now we need to compare all the other numbers except the first to find largest and smallest out of them.
if(LARGE<NUM[I]) LARGE=NUM[I]; if(SMALL>NUM[I]) SMALL=NUM[I];
Finally print the Numbers as Largest and Smallest at the end of the program.
C program code :
- void main()
- int NUM,I,LARGE,SMALL;
- printf("ENTER TEN NUMBERS TO COMPARE\n");
- printf("\nENTER NUMBER : ");
- printf("\nTHE LARGER NUMBER IS %d", LARGE);
- printf("\nThe SMALLER NUMBER IS %d", SMALL);