70.9k views
0 votes
Given an int variable n that has already been declared and initialized to a positive value, and another int variable j that has already been declared, use a for loop to print a single line consisting of n asterisks. Thus if n contains 5, five asterisks will be printed. Use no variables other than n and j

1 Answer

7 votes

Answer:

#include<iostream>

using namespace std;

//main function

int main(){

//initialize the variables

int n = 5;

int j=1;

// for loop

for(;j<=n;j++){

cout<<"*"; //print the '*'

}

}

Step-by-step explanation:

Create the main function and declare the variable n with the value 5 and initialize the variable j with zero.

take a for loop for executing the statement again and again until a condition is not false.

Syntax for loop:

for(initialize; condition; increment/decrement)

{

statement;

}

we can initialize the variable outside as well but the semicolon always present in the loop otherwise compiler gives the error.

for example:

int i=0;

for(; i<4; i++){

statement;

}

The condition put in the original code is j <= n and n has the value 5. so, the loop executes 5 times and inside the loop, write the print statement for print the character '*'.

User Lidia
by
8.6k points