In: Computer Science
Write a new program named Bar that prompts the user to enter a positive integer. The program should then display a line consisting of the entered number of asterisks using a while loop. If the user enters a number that is not positive, the program should display an error message (see example below).
Example 1: Enter a positive number: 6 ******
Example 2: Enter a positive number: 11 ***********
Example 3: Enter a positive number: -4 -4 is not a positive number
Answer:
Program:
#include<iostream>
using namespace std;
int main() /* main() function starts here */
{
int n,i; /* variable declaration */
cout<<"Enter a positive number:"; /* displays a
message */
cin>>n; /* reads an integer from the keyboard
and stores in 'n' */
if(n>=0) /* if n is greater than or equal to 0
*/
{
i=1; /* the counter variable 'i'
starts at 1 */
while(i<=n) /* until 'i' is less
than or equal to 'n', the loop repeats */
{
cout<<"*";
/* prints '*' symbol once */
i++; /*
increments 'i' by 1 */
}
}
else /* if n is less than 0 */
{
cout<<n<<" is not a
positive number"; /* displays a message that 'n' is not a positive
number */
}
return 0;
} /* end of main() */
Program Screenshot:
Output: