47.7k views
0 votes
Write a small program that asks the user how many asterisks it should print out. The user responds with a number, then the program prints that number of asterisks.

User Paolo Gdf
by
5.3k points

1 Answer

1 vote

Answer:

I am writing a C++ program. Let me know if you want the program in some other programming language.

#include <iostream> //to use input output functions

using namespace std; // to identify objects like cin cout

int main(){ //start of main() function body

int n; // number of asterisks

cout<<"how many asterisks do you want to print? "; //asks user how many asterisks it should print

cin>>n; // reads the value of number of asterisks that user want to print

for( int i=0; i< n; i++) { //loop to display the number of asterisks in output

printf("*"); } } // print * asterisks

Step-by-step explanation:

I will explain how the for loop works.

Suppose the user entered 3 as number of asterisks that user wants to print.

So n=3

Now for loop has a variable i that is initialized to 0. For loop checks if the value of i is less than that of n. It is true because i=0 and n=3 and 0<3. So the body of the loop executes. This prints the first asterisk *

Then the value of i is incremented to 1 and becomes i=1

At next iteration loop again checks if value of i is less than n. It is true because i=1 and n=3 and 1<3. So the body of the loop executes. This prints the second asterisk **

Then the value of i is incremented to 1 and becomes i=2

At next iteration loop again checks if value of i is less than n. It is true because i=2 and n=3 and 2<3. So the body of the loop executes. This prints the third asterisk ***

Then the value of i is incremented to 1 and becomes i=3

At next iteration loop again checks if value of i is less than n. This time it evaluates to false because i=3 and n=3 so 3=3. So the loop ends and the output is

***

The output screenshot is attached.

Write a small program that asks the user how many asterisks it should print out. The-example-1
User Niklas Peter
by
6.1k points