Thread: "For Loop" Help

  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,336
    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,336
    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
    Chappell Hill, Texas
    Posts
    2,332
    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?
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed