"For Loop" Help

This is a discussion on "For Loop" Help within the C Programming forums, part of the General Programming Boards category; Hello, I am trying to get the following "for loop" to take the variable "Y' set it to zero , ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    22

    "For Loop" Help

    Hello, I am trying to get the following "for loop" to take the variable "Y' set it to zero , and then increment it in the "for loop" by 3 until Y is > X. So something like X= 12 , y= 3
    I would have 0, 3, 6, 9, 12, 15 ....then exit the loop. I am getting it to add the 3 each tiem but it's also adding one before. Any suggestions ? I have read a ton on for loops tonight , and I still do not see my error ? Thank you !

    Code:
    #include <stdio.h>
    
    
    
    int foo ( int x, int y)
    {
        int i = y;
        
       for( i = 0; i <= x; i++)
       { 
          i += 3;
          printf(" %d \n", i); 
           
       }
    }
     
    
    
    int main()
    {
        int x;
        int y;
        
        
        printf("Please Enter A Integer...\n");
        scanf("%i", &x);
        
        printf("Please Enter A Second Intger...\n");
        scanf("%i", &y);
        
        foo (x,y);
        
        
        getch();
        return 0;
        
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    And what do you think i++ does?

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    22
    ok, so sorry !! I need not to do these programs so late at night !! one question , if I omit i++ , is that considered bad programming layout ? Thanks again for the help !

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Well, it would be fine, I suppose; but that's where your i+=3 belongs, really.

  5. #5
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Since you are using the variable i to control your FOR loop, and you are initializing it to zero as the loop initializer, when you declare i, you don't need to set it to the value of y.

    What happens to your code when someone enters a negative number?
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

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