for loops

This is a discussion on for loops within the C Programming forums, part of the General Programming Boards category; I have this segment of a program that is supposed to print: 0 01 012 0123 01234 012345 and it ...

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    15

    for loops

    I have this segment of a program that is supposed to print:

    0
    01
    012
    0123
    01234
    012345

    and it does that, but I don't understand why. The first time through the inner for loop b isnt less than a, yet the value of b (which is 0) is printed. Why?



    Code:
    	for (a=0; a<7; a=a+1) 
    	{
    		for (b=0; b<a; b=b+1)
    		{
    			printf("%d", b);
    		}
    		printf("\n");
    	}

  2. #2
    Registered User linuxlover's Avatar
    Join Date
    Nov 2010
    Location
    INDIA
    Posts
    52

    Smile

    Quote Originally Posted by laurenlb View Post
    I have this segment of a program that is supposed to print:

    0
    01
    012
    0123
    01234
    012345

    and it does that, but I don't understand why. The first time through the inner for loop b isnt less than a, yet the value of b (which is 0) is printed. Why?



    Code:
    	for (a=0; a<7; a=a+1) 
    	{
    		for (b=0; b<a; b=b+1)
    		{
    			printf("%d", b);
    		}
    		printf("\n");
    	}
    Because when a=0 b<a is wrong so it comes out of inner loop...when a is 1 ,inner loop will print b =0 in first iteration sice 0<1 ,during second iteration of inner loop b becomes 1 and the condition 1<1 (b<a) goes wrong..So it comes out of the loop and print a new line..ie.actually when a=0 it prints nothing....when a=1 it prints 0 ....and so on..
    Last edited by linuxlover; 03-15-2011 at 11:25 PM. Reason: spelling correction

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    15
    Thank you! that makes sense now. I was just assuming the that the first thing being printed was the result of the first inner loop. I didn't think it through that the first line was just completely blank.

  4. #4
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    Read the loops, nested loops and you will understand why and how...
    I don't care if someone doesn't like me, i was not put on earth to entertain everyone.

    No King, no Queen, I am the ACE of battle.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21