You are here:

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

Advertisement


Question
Respected Sir,
Kindly help me correct the given code to print the pattern using While Loop;
*
**
***
Code-
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i=1,j=1;
while(i<=3,j<=i)
{
cout<<"*";
i++,j++;
}
getch();
}

Answer
Hello Moonfrost.

It is much easier to do this with nested while loops. You should try to take the earlier exercise, which printed this pattern using for loops and convert the for loops into while loops. Here is how it's done

for (initialization; condition; counter_operation)
{
   // loop body
}

becomes this:

initialization;
while(condition)
{
   // loop body
   counter_operation;
}

I don't usually like to just give answers, because it is unfair to your classmates. This time is an exception. Next time you will have to work harder.

#include<iostream>
using namespace std;

void main()
{
   int i=1,j=1;
   while(i<=3)
   {   
       j=1;
       while (j <= i)
       {
           cout<<"*";
           j++;
       }
       cout << endl;
       i++;
   }
}

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.