Create Half-Triangle Using Nested Loops

This is what i've made so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	int b=1;

	for (int i=1; i<=5; i++)
	{
		for (int k=1; k<=i; k++)
		{
		 cout<<b;
		 b++;
		}
		cout<<endl;
    }

	getch();
	return 0;
}


And this is the output:

1
23
456
78910
1112131415

The correct output should be:

1
12
123
12
1

Any help would be greatly appreciated.
Here's a hint:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    const int i_max  = 256;
    double    i_step = 2.0;

    for (int i = 1; i >= 1; i = i * i_step)
    {
        std::cout << i << ' ';

        if (i == i_max) i_step = 0.5;
    }

    std::cin.get();
}
One problem is that you're printing the same variable all the time. The output is restarting from 1 on each line. Notice that you do have a variable which starts from 1 for every line - k.
Now, about the shape, the most simple solution would be to first print
1
12
123
and then in another set of loops
12
1
to print a backwards triangle, simply change the outer loop to one that does -- instead of ++.
Last edited on
Thanks, finally i've made the program to display the correct output, this is how it looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	int b=1, d=1;


	for (int j=1; j<=3; j++)
	{
		for (int k=1; k<=j; k++)
		{
			cout<<b;
			b++;
		}
		cout<<endl;
		b=1;
	}

	for (int c=2; c>=0; c--)
	{
		for (int a=1; a<=c; a++)
		{
			cout<<d;
			d++;
		}
		cout<<endl;
		d=1;
	}

	getch();
	return 0;
	
}

Topic archived. No new replies allowed.