Reputation: 191
I'm going through the Big Nerd Ranch book on Objective-C, which takes you through some early C stuff. I've played with C before, and am pretty experienced in PHP.
Anyhow, I'm doing the challenges and this one is not working the way I think it should. It's pretty simple - start at 99, loop through and subtract three until you get to zero, and every time you get a number that is divisible by 5 print "Found one." Pretty straightforward. However, subtracting by three in the for loop is not working
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
It creates and endless loop at 99, and I'm not sure why.
Upvotes: 0
Views: 4373
Reputation:
You are just subtracting 3
from i
, but you are not assigning it to i
.
Use i = i - 3
instead of just i - 3
.
Change your for statement like this:
for(i = 99; i > 0; i = i - 3) {
// Write your code here.
}
Upvotes: 1
Reputation: 13
The Last Term in the For loop is the increment of decrement operation. While i-3
is none. If you want the Value of i to get reduced by 3, then you should store that value in i
itself.
To do that Following code should be written: i = i-3
or shorthand i-=3
.
Upvotes: 0
Reputation: 59617
Your loop statement doesn't modify the value of i
. Just doing i - 3
doesn't change i
, it just returns the value of i - 3
.
Use: for(i = 99; i > 0; i = i - 3)
Upvotes: 1
Reputation: 10110
It should be i-=3
instead of i-3
.
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-=3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
i-3
does not change the value of i
.
i-=3
does.
Upvotes: 3
Reputation: 34625
i-3
doesn't modify the variable i
. Do something like -
for( i=99; i>0; )
{
// ....
i -= 3;
}
Upvotes: 4