Thread: My code works... but I don't understand why. Can someone explain?

  1. #1
    Registered User
    Join Date
    Sep 2016
    Posts
    10

    My code works... but I don't understand why. Can someone explain?

    Hi all. I'm new to C programming and I am having A LOT of trouble understanding nested for loops. Here is a program I wrote.
    Code:
    #include <stdio.h>
    
    int main(void){
        int userNum = 0;
        int i, j;
    
        printf("Enter an integer: ");   scanf("%d", &userNum);
        printf("\n");
    
        for(i = 0; i <= userNum; ++i){
            for(j = 1; j <= i; ++j){
                printf(" ");
            }
            printf("%d", i);
            printf("\n");
        }
        return(0);
    }
    The desired output is:
    0
    _1
    __2
    ___3...... and so on, up to the number that was entered. (the underscores should be spaces instead)

    I understand why it works for the first couple of iterations. But starting on the third line, why does the inside loop iterate twice, producing 2 spaces? Shouldn't 'j' increment and become equal to 'i', therefore only iterating once and printing one space?

    I'm just trying to get a better understanding of all this. Any kind of explanation would be greatly appreciated.
    Attached Files Attached Files
    • File Type: c test.c (270 Bytes, 137 views)
    Last edited by agamemn0n; 09-14-2016 at 09:58 AM.

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Please post your code in the respective code tags.
    Code:
    int get_random_number(void)
    {
       return 4; //chosen by fair dice roll.
                 //guaranteed to be random
    }

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    That happens because "++j" happens after everything else inside that loop. I don't know how to say it, so I'll show it:

    The following pieces of code are equivalent.
    Code:
    int i;
    
    for (i = 0; i < 10; i++) {
        // Code goes here
    }
    Code:
    int i;
    
    i = 0;
    while (i < 10) {
        // Code goes here
    
        i++;
    }
    Last edited by GReaper; 09-14-2016 at 09:54 AM.
    Devoted my life to programming...

  4. #4
    Registered User
    Join Date
    Sep 2016
    Posts
    10
    Ok, I think I understand.
    So you're saying that '++j' happens AFTER '++i'? I was thinking that everything in the inner loop happened before moving back to the outer loop.

  5. #5
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    That the behavor of for-loops.
    Code:
    for ( initialization ; evaluation ; action )
    {
        loop-code;
    }
    initialization will be executed at the start of the loop.
    evaluation will be checked every time befor the loop-code runs.
    action will be executed every time the loop-code is finish.

    You can rebuild your for-loop with while():

    Code:
    …
        j = 1;           // initialization
        while (j <= i)   // evaluation
        {
            printf(" "); // loop-code (one or more lines)
            ++j;         // action (last line)
        }
    …
    Other have classes, we are class

  6. #6
    Registered User
    Join Date
    Sep 2016
    Posts
    10
    I understand how for loops work on their own. It's when there is a for loop nested inside another for loop that I have an issue.

    In my code above, 'i' starts at zero and 'j' starts at one. During the first iteration the inner loop is ignored because the loop condition is false. During the second iteration (after 'i' has been incremented) the inner loop will also run, printing a space, then incrementing 'j' to 2, then printing the number 1, then incrementing 'i' to 2 also. After this, since 'i' and 'j' are now equal, why would the inner loop run twice, printing 2 spaces? I know that this is super confusing but I'm hoping there's someone that can get what I'm asking and explain it.

  7. #7
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by agamemn0n View Post
    After this, since 'i' and 'j' are now equal, why would the inner loop run twice, printing 2 spaces?
    In every iteration of the outer loop, the inner loop will start new! This means, the initialization will be executed.
    So, the inner loop starts again and initialize j with 1!
    Other have classes, we are class

  8. #8
    Registered User
    Join Date
    Sep 2016
    Posts
    10
    Ahhh yes! It all makes sense now. Thank you so much friend.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 02-27-2014, 08:09 AM
  2. Can someone explain how Python code parser works?
    By 33volx in forum C Programming
    Replies: 5
    Last Post: 02-27-2014, 08:09 AM
  3. Replies: 2
    Last Post: 06-13-2012, 06:49 PM
  4. Pls explain how this program works...
    By Unregistered in forum C Programming
    Replies: 9
    Last Post: 01-05-2002, 09:53 AM
  5. Can someone explain how this function works?
    By Drew in forum C++ Programming
    Replies: 1
    Last Post: 12-26-2001, 01:09 PM

Tags for this Thread