Problem:
Write a program that inputs the series of 20 numbers and displays the minimum value.Solution:
Here is the code that gets input of 20 numbers and displays the minimum value using for loop.#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int min,num,count;
cout<<"Enter a value=";
cin>>num;
min=num;
for(count=1;count<=19;count++)
{
cout<<"Enter a value=";
cin>>num;
if(min>num)
min=num;
}
cout<<"The minimum number entered is="<<min<<endl;
getch();
}
Explanation:
Line 1 & 2: include header files required for this program.Line 3: initialize the main() function with its return type set to void.
Line 4: Start the body of main() function.
Line 5: clrscr() clears all the previous outputs from the screen.
Line 6: declaration of all required variables with proper names.
Line 7: Show the message to the user that he should enter a value.
Line 8: get input from the user using cin keyword. The input is taken in the "num" variable.
Line 9: set the "num" variable's value as the value of "min". (We do this so that we may compare all upcoming values of "num" with the 1st value of "num" that has been put in "min")
Line 10: introduce a new for-loop. It is based on variable "count". It's initial value is 1, every time it's value gets an increment of 1 and the loop is repeated until count stays less-than or equal to 19. (It means that the loop will repeat 19 times).
Line 11: body of for-loop starts.
Line 12: we display a message to the user that he should enter a value.
Line 13: we get the input from the user in the variable named "num" using cin keyword.
Line 14 & 15: we check if the value entered in "num" is smaller than the value of "min" then we put smaller value in the "min" variable.
Line 16: Body of for-loop ends.
Line 17: we display the minimum number out of series of 20 numbers entered by user, using cout keyword.
Line 18: getch() keeps the output still on screen until the user presses a key from keyboard.
Line 19: Body of main() function ends.

No comments:
Post a Comment