C++ For loop without braces and braces

I am following infinite skill's learning C++ and i have a following code.
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
#include <iostream>
using namespace std;

int main()
{
	int data1, data2, data3;

	cout << "Enter the first number: ";
	cin >> data1;
	cout << "Enter the second number: ";
	cin >> data2;
	cout << "Enter the third number: ";
	cin >> data3;

	for (int i = 1; i <= data1; ++i)
		cout << "*";
		cout << " " << data1 << endl;
	for (int i = 1; i <= data2; ++i)
		cout << "*";
		cout << " " << data2 << endl;
	for (int i = 1; i <= data3; ++i)
		cout << "*";
		cout << " " << data3 << endl;
}

The output of the code is
***** 5
********* 10
************** 15
But when i put braces in while block like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (int i = 1; i <= data1; ++i)
	{
		cout << "*";
		cout << " " << data1 << endl;
	}
	for (int i = 1; i <= data2; ++i)
	{
		cout << "*";
		cout << " " << data2 << endl;
	}
	for (int i = 1; i <= data3; ++i)
	{
		cout << "*";
		cout << " " << data3 << endl;
	}


The output goes to the new line every iteration of the loop and when i omit the endl i know it endl is puts a new line and forces the output buffer but my question is that i have no idea how braces effect the loop my question is why the output is changed when i put braces on while loop body.
Without the braces, a for loop just includes the first statement.

1
2
for (int i = 1; i <= data1; ++i)
		cout << "*";


Once the for loop ends, the next statement is executed one time.

cout << " " << data1 << endl;

If you want multiple statements to be executed on each iteration of the for loop, you need to put the braces around those statements.
Last edited on
Now i thoroughly understand thanks sir you save me for frustration :)
Topic archived. No new replies allowed.