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.
A for loop consist of 3 parts
for( init ; cond ; step )
When the execution reaches the loop,
init is executed.
cond is evaluated.
If false, break the loop
If true, proceed to the next step
Execute the body of the loop.
Do step(in many cases, this is increment/decrement)
Goto step 2
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.
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.
Related
How do I calculate the frequency count of each statement (i.e. the number of time each statement gets read/executed) in the following C code.
The frequency count of each statement must be written in terms of 'n'.
int dividable(int n){
for(int i=3 ;i< = n ; i+=3)
if(n%i = 0){
cout << (“dividable\n”);
return 0;
}
return 1;
}
Suppose the code is corrected, changing < = to <=, n%i = 0 to n%i == 0, and cout to printf:
int dividable(int n)
{
for (int i = 3; i <= n; i += 3)
if (n%i == 0)
{
printf("dividable\n");
return 0;
}
return 1;
}
If n is less than 3, the for is executed once but immediately completes without executing any iterations of the body of the loop.
Otherwise, in the first iteration of the loop, i is 3. Then if n is a multiple of 3, n%i is 0, the if test is satisfied, and the routine prints “dividable” and returns 1.
If n is not a multiple of 3, then n%i is never 0, because i is always a multiple of 3. Then the test is never satisfied, all loop iterations are executed, and the routine returns 0.
Thus we have:
If n is less than 3, the for is executed once, the return 1; is executed once, and the other statements are executed zero times.
Otherwise, if n is a multiple of 3, the for is executed once (partially), the statements starting with if, {, printf, and return 0; are executed once each, and the return 1; is executed zero times.
Otherwise, the for is executed once, the if is executed floor(n/3) times, the statements inside the if are executed zero times, and the return 1; is executed once.
I'm currently learning C and I'm facing a problem that I can't solve.
It's really simple, I want the numbers from 1 to 20 printed but only if they're even (meaning the output would be 2, 4, 6,...). I know how to do this but the problem is that I want to do it in a way that I put two conditions in a for loop:
int main() {
for (int i = 1; i<=20 && i%2 == 0 ; i++) {
printf("%d\n", i);
}
return 0;
}
It seems that the second condition isn't evaluated, moreover it causes the program not to print anything. How can I do it ?
The second condition is evaluated. It is because it is evaluated the loop does not iterate.
The initial value of i is equal to 1. So the sub-expression i%2 == 0 evaluates to false.
You could use an if statement within the loop like
for (int i = 1; i<=20; i++) {
if ( i % 2 == 0 ) printf("%d\n", i);
}
If you want to place the expression i % 2 == 0 in the condition of the loop then the loop can look for example the following way as it is shown in the demonstrative program
#include <stdio.h>
int main(void)
{
for ( int i = 1; ( i % 2 == 0 ? i : ++i ) <= 20; i++) {
printf("%d\n", i);
}
return 0;
}
The program output is
2
4
6
8
10
12
14
16
18
20
Both conditions are evaluated - that's why the loop never gets going, in fact. When for starts, it sets i to 1, and immediately does the loop termination check: 1<=20 && 1%2==0. This reduces to true && false and finally to false. So the for loop won't do anything else: the very first check fails.
Remember: a failure of the condition check in the for loop terminates the loop!
Instead, you need to write what you meant - it'll be more readable and will work, too! You said:
I want the numbers from 1 to 20 printed but only if they're even
That translates directly to C (the return is unnecessary):
#include <stdio.h>
int main() {
// for all numbers from 1 to 20
for (int i = 1; i<=20; i++) {
// print out only those that are even
if ((i%2) == 0) printf("%d\n", i);
}
}
You can try this out online!.
The loop stops as soon as the condition fails. Since i%2 == 0 fails for i = 1, the loop stops immediately.
You need to put the even check inside the loop, not in the for condition.
int main() {
for (int i = 1; i<=20; i++) {
if (i % 2 == 0) {
printf("%d\n", i);
}
}
return 0;
}
I've used Code::Blocks to find the result, and it gives me 2 at the end, where i + j = 1 + 1.
#include <stdio.h>
int main(void) {
int i = -1, j = 1;
for(i++; i++; i++)
j++;
printf("%d",i + j);
return 0;
}
How does i get to be 1, and why was j not incremented?
You start with i == -1, j == 1.
Then you run the first i++, which will make i == 0. The result (which is the original value of i) is unused.
Then you test for the first time in i++. Since i is already 0, the test is false, so the for loop will quit. Now the post-increment runs, which makes it i == 1, and the loop exits.
Note how j++; was never reached!
To see it more clearly, you can think about the for loop in the following equivalent way:
i++; // init statement
while (i++) { // condition
j++; // body of the for loop
i++; // iteration expression
}
Here's the order in which it executes:
i is -1 and j is 1
i is incremented (after which i == 0)
The loop checks if i != 0. Since i is 0 at this point, the contents of the loop are skipped.
i is incremented again (after which i == 1)
The code prints i + j, which is 2 because j is unchanged and i is 1.
Here's a program with a while loop that does the same thing as the program in your question:
int main(void) {
int i = -1, j = 1;
i++;
while(i++)
{
j++;
i++;
}
printf("%d",i + j);
return 0;
}
To directly answer your question:
i is 1 afterwards because it is incremented twice from an original value of -1.
j is not incremented because the contents of the loop are skipped.
Let me first explain how for loop execution happens:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
Increment operator: value of i increments after execution if it is i++
Explanation of your code:
for(i++; i++; i++)
At init step i++ been executed but i will be still 0 until it get to condition step of for loop.
i becomes zero it means condition is false but at same time one more i++ already executed.
As condition is false for loop statement will never be executed and value of i will be 1 and value of j remains 1.
This code should count the number of prime numbers based on user input. If user input is 10, then I should get 4. However, I only get 0. Why does the second loop not run?
#include<stdio.h>
#include<math.h>
int main()
{
int N;
scanf("%d", &N);
int numprime;
numprime = 0;
int P=1;
for (P; P<N; P++)
{
if (P%2==0)
continue;
int e = sqrt(P);
for (int j=3;j<=e;j+=2)
{
if (P%j!=0)
{
numprime = numprime + 1;
}
else
{
continue;
}
}
}
printf("%d", numprime);
}
Why does the second loop not run?
It does run, once, when e is equal to 3 (that means that this happens when P is equal to 9), in the case that input is 10.
Change this:
for (P; P<N; P++)
to this:
for (; P <= N; P++)
since the first part had no effect, and more importantly, you want to check all N numbers, so the stop condition had to be modified.
Then, you need to change this:
for (int j=3;j<=e;j+=2)
to this:
for(int j = 2; j <= e; j+=2)
in order to check for prime numbers, are suggested here.
Furthermore, you need to change this:
if (P % j != 0)
to this:
if (P % j == 0)
since P is actually a prime number when the condition is met.
Moreover, you need to get rid of this:
if(P % 2 == 0) continue;
since for example 2 is a prime number, but it meets this condition, and will not be taken into account!
From your code, it looks like P starts out as 1, so e is sqrt(1), which is again 1, and j is 3. Therefore, j is not less than or equal to 1, and the test at the top of the inner loop fails, so the loop doesn't execute the first time through. This pattern continues for each iteration of the outer loop until P becomes large enough that sqrt(P) is greater than 3, at which point the inner loop does run.
#include< stdio.h>
int main()
{
int n,a=0,i=1,b=11;
while(i<=2)
{
while(i>0)
{
a=a+b;
i--;
}
printf("%d",a);
i++;
}
}
but if i make a little change i will get the output..
what is the difference between both the code??
#include< stdio.h>
int main()
{
int n,a=0,i=1,b=11;
while(i<=2)
{
n=i;
while(n>0)
{
a=a+b;
n--;
}
printf("%d\n",a);
i++;
}
}
output-
11
33
while (i <= 2)
{
while (i > 0)
{
a = a + b;
i--; <- out the inner while loop when i = 0
}
printf("%d", a);
i++; <- at here, the i==0 each time, so infinity loop
}
Because your nested loop always restores the value of i to 0,
And 0 <= 2 is always true, thus it keeps on going.
Initially the value of i is 1, the first loop starts by checking i<=2 , which is true for i=1, then the second loop checks i>0, which is also true, then the second loop decreases the value of i to 0 by i--;
This time the test condition for the nested loop fails and the inner loop exits, back in the first loop, the condition is satisfied as i=0 is<= 2 thus i is incremented, now i = 1.
This keeps on going forever.
In the second code, you're copying the current value of i to n, thus, initially i = 1;
Condition for first loop satisfied, then you set n = i,
And check n >0 which is true as n = i = 1
In this loop you are decrementing n and n becomes 0, thus the loop quits, and the outer loop increments i, i now being 2 allows the outer loop to run and then again n = i = 2,
The inner loop runs twice and then exits and i is incremented to 3 failing the outer loop condition and hence quitting the loop. And you get the result.
In the first code your
While(i<=2) never ends because you add 1 to i with i++ and then you subtract 1 from i with i-- and you never get i=3 to end the while loop.