Thread: for loop

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    4

    for loop

    Code:
     #include<stdio.h>
    int main(void )
    {
    for (int b=0;b<=5;b++)
    for (int a=0;a<=b;a++) 
    printf("*\n"); 
    }
    ^^^^
    I dont know why this code executes 21 "*" line by line
    I mean why it prints 21 particular ?



    thank you

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Because:
    Code:
    #include<stdio.h>
    
    int main(void)
    {
        for (int b = 0; b <= 5; b++)
            for (int a = 0; a <= b; a++)
                printf("b=%d, a=%d\n", b, a);
    }
    In other words, trace the flow of control, watch the variables (e.g., using a debugger), and it will soon become clear to you.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2013
    Posts
    4
    Thank you so much I got it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loop stops working when loop >45 ??
    By Zul56 in forum C Programming
    Replies: 3
    Last Post: 12-11-2012, 03:40 PM
  2. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  3. Replies: 1
    Last Post: 12-26-2011, 07:36 PM
  4. Replies: 23
    Last Post: 04-05-2011, 03:40 PM
  5. for loop ignoring scanf inside loop
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-17-2007, 01:46 AM