Reputation: 1
I get an unusual output for the loop below. When it is run in my compiler, the output is 233445
. Why do I get this output for the loop below? 7
would be the only reasonable output for this loop, why don’t I get 7
when the printf
statement is inside the loop?
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int j;
for (i = 1; i < 4; i++)
for (j = 1; j < 3; j++)
printf("%d", i + j);
}
Upvotes: 0
Views: 37
Reputation: 1425
#include <stdio.h>
#include <stdlib.h>
int main () {
int i ;
int j ;
for( i=1; i<4;i++)
for(j=1;j<3;j++)
printf("%d",i+j);
}
The code runs an outer loop three times beginning with i = 1
. It goes to the inner loop and runs twice beginning with j = 1
. Then it prints 2,3
for the first loop, 3,4
for the second loop, and 4,5
for the third loop.
I added the commas for clarity and to show the inner loop does indeed run twice, but the actual output is 233445
because you're not adding any separators or newlines.
If you want 7
as the output using loops, try:
#include <stdio.h>
#include <stdlib.h>
int main () {
int i ;
int j ;
for( i=4; i<5;i++) { // this brace means it contains the inner loop.
for(j=3;j<4;j++) { // this inner brace means it contains control of the statement.
printf("%d",i+j); // and always remember to indent for your readers
} // close the inner brace!
} // close the outer brace!
} // close main brace
Alternatively, you can try incrementing the numbers using loops, and then print it outside of the loops, as others have mentioned:
#include <stdio.h>
#include <stdlib.h>
int main () {
int i ;
int j ;
for( i=1; i<4;i++) { // this brace means it contains the inner loop.
for(j=1;j<3;j++) { // this inner brace means it contains control of the statement.
} // close the inner brace!
} // close the outer brace!
printf("%d",i+j); // 7
} // close main brace
Upvotes: 1
Reputation: 75062
Why do I get this output for the loop below?
Make a chart and you will see.
i | j | i+j
--+---+----------------------------
1 | 1 | 2
1 | 2 | 3
1 | 3 | (get out of the inner loop)
2 | 1 | 3
2 | 2 | 4
2 | 3 | (get out of the inner loop)
3 | 1 | 4
3 | 2 | 5
3 | 3 | (get out of the inner loop)
4 | - | (get out of the outer loop)
why don't I get
7
when theprintf
statement is inside the loop?
Because i<4
and j<3
, so i+j < 4+3
and it means i+j<7
, so i+j
won't be 7
inside the loop.
Upvotes: 6
Reputation: 590
Yes, the printf
statement is inside the loop. To get 7
, you take it out of the loop by placing {}
after the loop.
Upvotes: 0