Why does it writte me "statement with no effect use" in the line where there is the "for".
r=7;
for (r=7;r<=n1;r+10)
printf("%d\n",r);
Because r+7 is no assignment.For assignment to take place,you have to write
something like
r = r+7 or r += 7
r+10 does not modify r so if n1 happens to be greater than on equal to 7 at the start of the loop, the loop will be infinite, which is probably not what you were trying to achieve. Did you mean r += 10, or in other words, increment r by 10?
Related
I have a problem with predicting result of code linked below.
Why program is printing 2 0 6 0 10 0 16 0 20 0 ? I guess it is all about operators precedence, but after thinking a while I can't realize what's wrong with my interpretation. Can you explain it a little bit?
#include <stdio.h>
int main(void)
{
int tab[10] = {2,4,6,8,10,14,16,18,20};
int *pi, i;
for(pi = tab; ++pi < tab+9;)
{
*pi++ = 0;
*pi *= 2;
}
for(int i=0; i<10; i++)
printf("%d ", tab[i]);
return 0;
}
The first thing that the for loop does is point pi at tab, i.e. pi=&tab[0]
So pi is pointing at the number 2. The next piece of code to be executed is the for loop's "condition" statement ++pi < tab+9. This first increments pi (so it's now pointing at the number 4 in tab[1]) and checks whether it's still pointing at a member of tab earlier than the final 20.
In the body of the for loop, the line *pi++ = 0; first stores a 0 at the address pointed to by pi (which means that tab[1] is now 0 rather than 4) and then (post-) increments pi to point at tab[2], which is 6. Then the line *pi *= 2; doubles the value pointed to by pi, so tab[2] becomes 12.
The next thing that happens is a re-evaluation of the for loop's conditional statement (since its iteration statement is empty): pi is incremented and checked.
The rest of the iterations are fairly uneventful. The final state of tab is that the first member is unchanged, members with an odd index are zero, and other members are doubled from their initial value.
General advice regarding operators and precedence: one of two situations is almost always the case. The first is that you and the compiler don't agree on the order in which the operators in your code will be applied—in other words your code doesn't do what you expect. The second is that you understand perfectly what the compiler is going to do, but the programmer reading your code does not—in other words your code doesn't do what they expect. Fortunately, both situations can be mitigated by adding parentheses to remove any doubt.
The actual output is 2 0 12 0 20 0 32 0 40 0 (as shown in Blastfurnace comment https://ideone.com/UUy8QO)
pi is indeed initially on the first cell, but your stop condition increment the pointer. Therefore, inside the loop, for the first instruction, pi is in tab[1]. It first put this cell to 0, then increment with ++. On the second line, it double the value, therefore it double tab[2]. Then, the stop condition again increment the pointer, and so on.
Below is the recursive function for sum of natural numbers up to n.
int calculateSum(int n) {
if (n == 0){
return 0;
}else{
return n + calculateSum(--n); //Replacing --n with n-1 works
}
}
Input: 5
If I use --n then the output is 10, but when I replace --n with n - 1 then the correct result is returned (15). Why the difference?
As surprising as it might be, the behaviour of the expression
n + calculateSum(--n);
is undefined, because --n not only evaluates to the value of n after being decremented by 1, it also changes n to the new value. The change (a side effect), however, is unsequenced in relation to the other evaluation of n (a value computation) on the left. And according to C11 Appendix J.2., the behaviour is undefined, when
A side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object (6.5).
More of the same class of errors in this question.
You can consider yourself lucky when you got a wrong value, because your compiler could have also generated code that would return the "correct value"... given the phase of the moon, and the optimization settings, or the number of lines in the calling function...
--n also modifies the local variable n; the expression n-1 just returns the decremented value to pass it on to the recursive call, but does not modify your input-parameter.
In detail for the first iteration with input 5:
Correct is return 5 + calculateSum(5-1);
With --n you would also decrement from n and end up with 4 + calculateSum(4)
#user3386109 & #Yunnosch worded it this way:
With --n you calculate the sum 0...(5-1) instead of 0...5.
See #Antti answer, it explains that it's actually undefined behaviour.
The following code snippet (a Function), you can call it in the main function which will return the sum of n natural numbers recursively
int NNumbers(int n)
{
if(n != 0)
return n + NNumbers(n-1);
else
return n;
}
In your code you are decrementing the value of n and then you are calculating the sum (i,e. Pre-Decrement), since the input is 5, it decrements 1 at each iteration and and then it will go for addition of natural numbers. so you are getting the result 10 instead of 15
Hope this helps for you :)
Thank you
I just started programming in C, and while practicing with for loops, I came up with the following piece of code:
#include <stdio.h>
int main()
{
int x;
for (x=0;x=10;x=x+1)
printf("%d\n",x);
return 0;
}
When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?
Thanks in advance!
The condition part of your for loop is wrong. What you are doing is :
for (x = 0; x = 10; x = x +1) {
// Operations
}
The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :
for (x = 0; true; x = x + 1) {
// Operations
}
This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.
EDIT : As Virgile mentioned in comments, for the second for loop, x will go from 0 to INT_MAX, then the behavior is undefined. So, your code is more likely to look like :
for (x = 0; true; x = 10) {
// Operations
}
When entering a for loop, the initialization part is performed first. So after the loop initialization x is 0.
Before entering the body of the loop, even the first time, the condition is checked. The "condition" in this case does not compare x to 10 but sets it to 10 since you are using = instead of ==.
Since an assignment as an expression has the value of the variable after assignment, the conditional expression has a value of 10 since that is what was assigned to x. Because this value is non-zero, it evaluates to true, and always will.
The problem here is, Take a close look on the condition part(2), in this what x=10, means is it is just assigning the value 10 to x, and it returns "True" always, so no problem what you have incrementing, it comes to 10 always, Thus infinite loop.
What you are trying to do is, you are implicitly converting int to bool in this line:
for (x=0;x=10;x=x+1)
^^^^
here, x=10; results true
So, it prints 10 everytime as you are using the = assignment operator.
for(int x=0;true;x=x+1)
What you could do to maintain the loop?
Use relational operators:
for (x=0;x!=10;x=x+1)
for (x=0;x==10;x=x+1)
for (x=0;x<10;x=x+1)
Just a fast question:
I'm trying to test if a variable is not greater than or equal to another variable.
I have it coded as such:
if (f!>=i){
print ("True");}
but my c compiler won't recognize it. I can't find it online, is it possible?
Just change it to (f < i) which is !(f >= i).
Note: this is not the case if either f or i is NaN. This is because f >= i will evaluate to false if either is NaN leading to !(f >= i) evaluating to true where f < i evaluates to false.
You want to do: if (!(f>=0))...
Specific to what you're doing, using < makes more sense. My suggestion here is just for a generic means of reversing polarity on any if statement.
Not greater than or equal to is equivalent to less than.
Use the aliter i.e instead of !> think in reverse and use f<i
and you cant use ! for more than one operator i.e !+= is not valid
You can write it like so:
if(!(anyvariablename<0))
I need to convert this loop to a for loop.
Input:A number k ≥ 0
Output: Output ??
x←0
y←0
while x≤k do
x←x+1
y←y+3
return y
Also can you describe me the output of this?
Thank you.
You didn't describe what language you were thinking of, and I didn't recognize the syntax of your while example. But this C code should be a for-loop equivalent of that code.
for(x=0, y=0; x <= k; x++) y += 3;
Of course, if you only care about the result, this could be replaced by
y = 3*(k+1);
Edit: Ok, so as pseudo-code, this could be something like
y←0
for each x from 0 to k inclusive do
y←y+3
end do
return y
But I find the proper C code much clearer, myself.