#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0

    Nested for loop unexpected behavior


    Hi i'm a C# coder and new to C but the code below has been giving me some weird behavior.

    Code:
    #include<stdio.h>
    
    int i;
    int j;
    
    main()
    {
    	for(i=0;i<20;i++)
    
    	{
    
    	for(j=0;j<20;j++)
    
    	printf("i=%d j=%d \n",i,j);
    
    	}
    	getchar(); 
    }
    The output i'm receiving from the console window reads.

    i=5 j=1
    i=5 j=2
    i=5 j=3

    etc.. but (i) starts at 5 for some reason so i decided to debug the code to see what the problem was. As i started to step through the code i got a different output.

    i=0 j=0
    i=0 j=1
    i=0 j=2

    Now since i'm stepping through my code it's giving me a different output? What am i missing here?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,183
    Rep Power
    2222
    Are you sure it's not just scrolling off the screen? Why don't you put another getchar right after the j-loop so that you can see each iteration of i?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0
    Originally Posted by dwise1_aol
    Are you sure it's not just scrolling off the screen? Why don't you put another getchar right after the j-loop so that you can see each iteration of i?
    Lol you were right wow i'm a noob for sure thanks.

IMN logo majestic logo threadwatch logo seochat tools logo