I don't understand why I don't need brackets in this case
for (int i = 0; i < 10; i++)
if (num[i] < min)
min = num[i];
And why I need brackets in this case
int num[10], min;
for (int i = 0; i < 10; i++) {
cout << "enter 10 numbers" << endl;
cin >> num[i];
}
Create a for- loop to repeatedly execute statements a fixed number of times. Create a while- loop to execute commands as long as a certain condition is met. Use if-else constructions to change the order of execution.
Yes it is not necessary to use curly braces after conditions and loops (functions always need them) IF and only if there is just one statement following. In this case it automatically uses the next statement.
In C, C++ and Java, if you add another statement to the then clause of an if-then: if (condition) statement1();
Both the for
and the if
have to be followed by a "statement". A "statement" can be a simple statement, like min = num[i];
, a more complicated one like if (num[i] < min) min = num[i];
or it can be a compound statement (i.e., zero or more simple statements enclosed in curly braces), like { std::cout << "enter 10 numbers\n"; std::cin >> num[i]; }
Some people think that cluttering simple statements with syntactically redundant curly braces is good style. Others don't.
Because you don't.
They are optional. That is just how it is.
If you don't use braces to group multiple statements into one, then only the first statement following the for
or if
preamble is considered part of that construct. (But this rule is transitive, so your assignment is part of your if
is part of your for
!)
It is important to note that indentation has no effect.
Many people believe[citation needed] that you should always use braces, for clarity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With