You are here:

C++/C++ Code to print the following pattern

Advertisement


Question
Respected Sir,
Kindly help me complete the given incomplete code to print the pattern-
****
***
**
*

The code:-
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,j;
for(i=4;i<= ;i--)
{
for(j= ;j =i;j  )
{
cout<<"*";
}
cout<<endl;
}
cout<<"over";
getch();
}

Answer
Hello Moonfrost.

Nice to hear from you again. In this program you have 2 nested loops. The outer loop controls the number of lines to be printed, and the inner loop controls the number of characters to be printed. The outer loop goes from 4 down to, and including, 1 so that 4 lines are printed.

The outer loop uses the i variable as a counter. The inner loop uses i in its condition.

Notice that on the first pattern line, i is 4, and 4 stars are printed. On the second line, i should be 3 because it is decremented in the outer loop (with i--) and notice that 3 stars are printed. The inner loop uses the variable j and it is used to count the stars. It should be clear that j goes from 1 up to, and including, the value of i so the condition on the inner loop looks like j<=i.

I think you have enough clues now to finish the assignment.

Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.