-
"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;
}
-
And what do you think i++ does?
-
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 !
-
Well, it would be fine, I suppose; but that's where your i+=3 belongs, really.
-
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?