2

I am trying to learn the C programming language on my own and have to depend on the internet for some help. I am playing around with one variable and a for loop; incrementing the variable by 1, each iteration of the loop. In this example, I am confused by the fact that the variable is not 1 in the first iteration of the loop. It's like the arguement was skipped on the first pass. I don't understand.

// This is a test of for loops

#include <stdio.h>

main () {

    int a;

    for (a = 0; a < 10; a++) {

        printf("%d\n", a);

    }

    return 0;
}
4
  • 1
    Hi @AndyS, and welcome to Stack Overflow. I think if you Google "c for loop" you'll find explanations of the syntax that clarify the behavior here. Specifically, the last argument of the for loop—the incrementer—only executes after the logic within the loop has been executed, whereas you're assuming it will happen before. Commented Feb 27, 2020 at 21:21
  • I guess my confusion is: if it's getting tested to see if it's less than 10, doesn't the flow dictate that the next thing in the argument be to increment it by 1? Commented Feb 27, 2020 at 21:48
  • One could imagine a for loop operating that way, but that's not the way for loops in c work—nor how they work in any other popular programming language for that matter. The syntax is a bit confusing since the three conditions are placed right next to one another; it can give the impression of a sequence. That's probably just an artifact of there not being a more elegant way of expressing the syntax. If you're reading it like a sequence, it might be easier to think of it as having an implicit extra parameter: for (a = 0; a < 10; execute logic; a++). Commented Feb 27, 2020 at 23:05
  • To be clear, though, the way you should think of this: "Is a less than 10? If so, execute code. Then, increment a. Repeat until the initial condition is false." Commented Feb 27, 2020 at 23:07

4 Answers 4

3

Maybe it's easiest to understand as follows. In C, a loop written like this:

for (a = 0; a < 10; a++) {
   printf("%d\n", a);
}

is equivalent to this:

a=0;
while (a<10) {
   printf("%d\n", a);
   a++;
}

The for-loop notation is meant to collect up all of the loop control information at the top of the loop as written, but the parenthesized part after the keyword "for" is not executed as a group of statements before the body, it's treated as if it were written as shown in the while loop.

You can also write an infinite loop like this in C:

for (;;) {
   printf("Hello forever\n");
}

which is equivalent to:

while (1) {
   printf("Hello forever\n");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Now that makes sense to me! Thank you Thomas Kammeyer!
No problem. When you feel your question's fully answered, remember to accept an answer. It doesn't need to be mine, and you can wait a little longer to see if a better answer than any currently available is posted, but please don't leave an adequately answered question without accepting one of the answers. People new to the site often seem to leave questions that way after they've gotten their answers.
Note the equivalence breaks when the loop contains a continue;, which will skip an a++ inside the body but will not skip the a++ in the controlling for statement.
Thanks for making that point, Eric Postpischii. Really annotating the extent of the equivalence well requires a bit more care -- like restating the for-loop continue as a goto inside the body of the while. My main concern was laying down the equivalence simply and clearly for this example.
2

You're initializing a to 0 when your loop is created( see a = 0 on line 9 of your code snippet). The first iteration will be just that, 0.

#include <stdio.h>

int main(int argc, char* argv[]) {

    int a;

    /**
     * RIGHT HERE! 
     * "a" is being assigned the value of 0 for the first iteration, and is incremented each loop
     * until a is no longer less than 10.
     */
    for (a = 0; a < 10; a++) {

        printf("%d\n", a);

    }

    return 0;
}

You could start a at 1 if you really wanted to, but ask yourself "why?" first, as starting from 0 is what you'll find yourself doing most of the time.

(Also, please consider making your main signature compliant with the C standard by specifying the return type and accepting the appropriate arguments e.g. int main(void) or int main(int argc, char* argv[]))

Comments

0
#include <stdio.h>

int main (int argc, char **argv)
{
    int c = 0;
    while (c < 10) 
    {
        printf("count: %d\n", c);
        c++;
    }
    return 0;
}

also try initialize c with 1 int c = 1;

and try while (c <= 10)

and you can also use c += 1;, but c++; is usually faster and just for tickles you can try out c = c + 1;, my personal favourite, but that might be the slowest way of incrementing, and your compiler might complain about that one, you'll see!

but whenever one is working with C, one shall use c++; that's just a little joke! ;)

Comments

0

For loop has 4 parts:

for(initialise;condition;updation)
{
  //Body
}

This is how it works:

Step 1: Execute Initialise (Which is zero for you, so a=0)
Step 2: Evaluate Condition: If false,end the loop. If true go to next step. (It's True in your case. The value of a is still 0)
Step 3: Execute Body (value of a is still zero)
Step 4: Execute updation and go back to Step2 (This is where 'a' becomes 1 for your)

This is why for the first time Body is executed, you get the value of a to be zero.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.