Question: Write a simple program that will prompt a user to enter an integer between 1 and 20. Then the program will print on screen the numbers starting from 1 and ending at the number that the user has entered. Example: If a user enters 6 then the program should print "1 2 3 4 5 6". If a user enters a value outside the specified range, it should give a message: "Incorrect input. Enter number between 1 and 20". (Note: Use WHILE loop);
Solution:
Code description:
int a; int a is a variable declaration for an ending point.
cin>>a; this line inputs user data for an ending point e.g. 6 to output 1 2 3 4 5 6
(a<1 || a>20) Is a conditional statement that checks if a user has entered a value outside the specified range, if this statement is true then the line cout<<"Incorrect input. Enter number between 1 and 20\n"; will be executed otherwise the else block is to be executed.
while(i<=a){
cout<<i<<" ";
i++;
}
The while loop loops from 1 to an ending point input by a user, it will display 1 at the start as the initial point of i has been set int i = 1; above and will increment(i++) by one for every iteration, and will stop the iteration when it reaches the number entered by a user...
No comments:
Post a Comment