Reputation: 4238
I'm stuck at Question 7 of Project Euler. I have this piece of code.
#include <stdio.h>
int main (void)
{
int contador = 0, i, n, variavel = 0;
for (i = 0; contador == 1000; i++)
{
for(n = 0; n == i; n++)
{
if (i % n == 0)
{
variavel = i;
contador++;
}
}
}
printf("%d\n", variavel);
}
It always prints 0. Why is that?
PS: I wrote 1000 but the answer must be the 10001st prime number.
Upvotes: 0
Views: 142
Reputation: 20244
A for
loop consist of 3 parts
for( init ; cond ; step )
When the execution reaches the loop,
init
is executed.cond
is evaluated.
step
(in many cases, this is increment/decrement)So, in your code, when the execution reaches
for (i = 0; contador == 1000; i++)
i
is set to 0. Then the condition contador == 1000
is checked. It is false as contador
is initialized to 0. So, the loop breaks and the execution reaches the printf
which prints the value of variavel
which is 0 and then
return 0;
executes. This ends the execution of your program.
Your inner for
loop has a somewhat similar issue. If the condition of the outer for
loop is corrected, then the inner for
loop executes. n
is set to zero and then, the condition n==i
is checked. It will be true only when i=0
,i.e, it will be true only in the first iteration of the outer for
loop.
You need to correct these mistakes.
Upvotes: 4
Reputation: 16351
The reason it is always zero is that the inner loop condition is satisfied in the first iteration:
for(n=0; n==i; n++)
Additionally, your outer loop will never run. It is written to say that it should only loop when contador == 1000
, which can never happen as written.
Upvotes: 1