akash3141
Badges: 13
Rep:
?
#1
Report Thread starter 2 years ago
#1
#include <stdio.h>
int main (void)
{
int count;
for (count = 1; count <= 10; count++);
printf("%d \n", count);
return 0;
}

I was going through lecture notes and trying to revise everything but this code only outputs the number 11, instead of the numbers 1- 10.

What am I doing wrong?
0
reply
shivampaw
Badges: 12
Rep:
?
#2
Report 2 years ago
#2
I'm not sure what you're trying to do exactly, but the C code for printing the numbers 1-10 would be:

Code:
#include <stdio.h>
int main (void)
{
    int count;
    for (count = 1; count <= 10; count++) {
        printf("%d \n", count);
    }
}
Your code had a semi colon after the for statement which caused the issues
0
reply
winterscoming
Badges: 19
Rep:
?
#3
Report 2 years ago
#3
In C, a semi-colon terminates a statement -

for ( count = 1; count <= 10; count++ ) ;


Your code is equivalent to this, because your 'printf' statement is outside the for loop's body, which has been terminated by the semicolon:
Code:
int count;

for (count = 1; count <= 10; count++)
{
    ;  /* "do nothing" semi-colon */
}

printf("%d \n", count);
This causes your 'for' loop to keep repeating as long as the 'count' variable is less-than or equal-to 10. The loop increment will happen after each iteration. When the 'count' variable reaches 10, it will still iterate, and it will increment again at the end of that, meaning its value will be 11
1
reply
X

Quick Reply

Attached files
Write a reply...
Reply
new posts
Back
to top
Latest
My Feed

See more of what you like on
The Student Room

You can personalise what you see on TSR. Tell us a little about yourself to get started.

Personalise

Feeling behind at school/college? What is the best thing your teachers could to help you catch up?

Extra compulsory independent learning activities (eg, homework tasks) (13)
7.22%
Run extra compulsory lessons or workshops (29)
16.11%
Focus on making the normal lesson time with them as high quality as possible (29)
16.11%
Focus on making the normal learning resources as high quality/accessible as possible (27)
15%
Provide extra optional activities, lessons and/or workshops (49)
27.22%
Assess students, decide who needs extra support and focus on these students (33)
18.33%

Watched Threads

View All