I was doing my assignment and was kind of playing around with the braces around iteration loops in c. From my understanding, you can write loops without having braces around the statements in each branch.
When I used the sample question code below, it managed to exit the loop to print the value outside of the loop.
But when I include brackets for each if / if else loop (which I am more comfortable with). It seems to be stuck inside the loop without printing anything on my console.
Am I overlooking something? Or is there special meaning on the way we bracket loops in c?
Sample Code from Assignment:
while (i<=20) {
if(i%2 == 0 && i <= 10) value = i*i;
else if ( i % 2 == 0 && i > 10) value = i;
else value -= i;
i ;
}
I added braces for each if / else if loops
int i = 0 , value = 0;
while (i<=20) {
if(i%2 == 0 && i <= 10) {value = i*i;}
else if ( i % 2 == 0 && i > 10) {value = i;}
else {value -= i;
i ;}
}
printf("%d", value);
so like I said, the first one does make it to the print statement. while the second example does not? Is that supposed to happen? Am I overlooking something?
CodePudding user response:
In the first example (without parenthes) the i is performed in every cicle, so you reach 20 and you exit.
In the second example you increment i (i ) only if you enter the 'else' statement, so you get stuck (i remains zero).
If you want to understand well what happens i would suggest you to use printfs in each statement (with and without parenthesis) so you can see what happens at every iteration.
In c without using parenthesis only the first line is inside the else statement (first example: value -= i;)
Correct indentation:
while (i<=20) {
if(i%2 == 0 && i <= 10)
value = i*i;
else if (i % 2 == 0 && i > 10)
value = i;
else
value -= i;
/* not inside the else statement */
i ;
}
Correct indentation, second example:
int i = 0 , value = 0;
while (i<=20) {
if(i%2 == 0 && i <= 10) {
value = i*i;
}
else if ( i % 2 == 0 && i > 10) {
value = i;
}
else {
value -= i;
/* inside the else statement */
i ;
}
}
printf("%d", value);
CodePudding user response:
I think this is how you were supposed to include the braces, only fixed i (in the comment)
#include<stdio.h>
void main(){
int i=0,value=0;
while (i<=20){
if (i%2==0 && i<=10){ value =i*i;}
else if (i%2==0 && i>10){ value =i;}
else { value-=i;}
i ; // its outside the if statement.
}
printf("%d",value);
}