Create a right-angled triangle with "Do while" Loop

Hello guys !
Im trying to solve this problem with do while loop which is kinda new for me.
I solved it with for loop but not finding a solution for do while loop.
Well i know where my mistake is but i dont know how to fix it , i dont know where to declare "j".
I tried it like: "" while (i<=rows && j<=i) "" but it seems that the second declaration into while loop doesnt count.
Desired shape is:
*
**
***
****
***** ....... number of rows I put
This is the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{  
    int i=0,j=0,rows;
    cout<<"Put the number of rows you want: ";
    cin>>rows;
 do{
    cout<<"*";
    cout<<"\n";
     i++;
    j++;
    }
 while (i<=rows && j<=i);
 return 0;
}
Last edited on
you need to store a value inside a while loop that will record amount of printed asterisks in previous line. (you can use 'j' variable for this task)

then you need to put rows parameter into the while loop (or use 'i' if rows is used for input), and increase it's value by
+1 each time you print 1 asterisks more than it is recorded in last row (the amount stored in j variable)

each time you increment rows variable you also print new line character!

you current program doesn't work because you print new line for each loop iteration.
Last edited on
You will need a for loop in your do loop. but this works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
	int i = 0, j = 0, rows;
	cout << "Put the number of rows you want: ";
	cin >> rows;
	do {
		for (j = 0; j < i; j++) {
			cout << "*";
		}
		cout << "\n";
		i++ ;
	} while (i <= rows);

	cin.ignore();
	cin.get();
	return 0;
}
Last edited on
since complete solution is already posted...

same thing but without for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main()
{  
    int i = 0, j = 1, rows;
    cout<<"Put the number of rows you want: ";
    cin>>rows;
    
 do{
    cout<<"*";
    if(++i == j)
    {
        cout << '\n';
        i = 0;
        ++j;
    }
 }
 while (j <= rows);
 
 return 0;
}
Thank you very much !
I solved it like this :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
int main()
{   
    int i=1,j=1,rows;
    cout<<"Put the number of rows you want: ";
    cin>>rows;
   
 do  
 {
	int i=1;
    do
	{
	 cout<<"*";
	 i++;

    }
	   while (i<=j); 
       cout<<"\n";
       j++;
 } while (j<=rows);
 cout<<endl;
 return 0;
Last edited on
Topic archived. No new replies allowed.