I just started to learn C so the answer is probably incredibly obvious but when I run this code the number 0 just keeps repeating in an infinite loop. I'm trying to print x from 0 to 1 in increments of .05.
#include <stdio.h>
int main()
{
double x;
for( x = 0; x <= 1; x+.05 )
{
printf("%d\n", x );
}
}
for( x = 0; x <= 1; x += .05 )
seems like your not writing the changed x value to x..... If you know what I mean :D
x++ is the same as x+=1
x+.05 doesn't modify x's value, thus x will always be 0 and result in a infinite loop...
I think that's what you're looking for:
for( x = 0; x <= 1; x+=0.05 )
{
printf("%f\n", x );
}
You'll want to change to the += sign and change the d to an f.
d is for decimal integers
f is for floating point numbers
You want the addition and assignment compound operator, which is +=, not just +.
for( x = 0; x <= 1; x+=.05 )
Currently the result of your expression is x + 5, and its result is not used, resulting in your loop's condition never being false.
Change the line in your for loop to
for( x = 0; x <= 1; x += .05 )
Note that
x += .05
Is equivalent to typing
x = x + .05
which is what you really want since the goal is to update the value of x.
Related
int x , sum = 0;
for (x = 10; x > 0; x++) {
sum += x;
}
I am expecting the loop never end because x will never hit 0.
System.out.println(sum);
It surprises me when it outputs this value -1073741869 , where my x is incrementing instead of decrementing.
can any one help me understanding the output of this code?
#include <stdio.h>
int main()
{
int x = 1, y = 1;
for(; y; printf("%d %d \n", x, y))
{
y = x++ <= 5;
}
return 0;
}
the output is:
2 1
3 1
4 1
5 1
6 1
7 0
A for loop in the form of
for (a; b; c)
{
d;
}
is equivalent to
{
a;
while (b)
{
d;
c;
}
}
Now if we take your loop
for(; y; printf("%d %d \n", x, y))
{
y = x++ <= 5;
}
It is equivalent to
{
// Nothing
// Loop while y is non-zero
while (y)
{
// Check if x is less than or equal to 5, assign that result to y
// Then increase x by one
y = x++ <= 5;
printf("%d %d \n", x, y);
}
}
Now it should hopefully be easier to understand what's going on.
Also: Remember that for boolean results (like what you get as result from a comparison), true is equal to 1, and false is equal to 0.
The code is an obfuscated, ugly version of this:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int x = 1;
bool y = true;
while(y == true)
{
y = (x++ <= 5);
printf("%d %d \n", x, (int)y);
}
return 0;
}
y in the original code serves as a boolean. Back in the ancient days, there were no boolean type in C so it was common to use int instead. The expression y = x++ <= 5; evaluates to 0 or 1, which is equivalent to false or true.
Note:
While the C language allows all manner of crazy stuff, you should never write for loops as in the original code. De facto standard is to write for loops like this:
The first clause of a for loop shall only contain iterator initialization.
The second clause should only contain the loop condition.
The third clause should only contain a change of the loop iterator, such as for example an increment (like i++).
A for loop that doesn't follow the above industry standard rules is badly written, no excuses.
The statement y = x++ <= 5; sets y to 1 if x is less than or equal to 5, or to 0 if x is greater than 5. It then increments x. The loop stops when y is equal to 0, that is, on the iteration after x was incremented above 5. Then it runs the printf() statement on each iteration.
You wouldn’t normally see a loop switch the loop condition and the loop body that way. This seems to be a pathological example of how it’s technically legal. You shouldn’t imitate it.
y is 1 (true) as long as x <= 5 and x increases every iteration.
Rewrite your code:
for (int x = 1, y = 1; y; y = x <= 5, x++) {
printf("%d %d\n", x, y);
}
or using while
int x = 1;
int y = 1;
while (y) {
printf("%d %d\n", x, y);
x++;
y = x <= 5;
}
The first component of the for loop is empty; which means values of variables haven't changed. The condition in the for loop is y. Which means that the loop will run till the condition y is true; which means till the value of y is anything other than 0.
When the value of y becomes equal to 0; the condition will become false and the loop will stop iterating.
Then comes the block execution...
y = x++ <= 5;
Here first the condition x <= 5 is checked. Note that x++ is post increment and so the value of x will be incremented after the execution of the statement. So, if the value of x was 1 before increment; it will check 1 <= 5 and not 2 <= 5 and after the execution of the statement; the value will become 2.
After that comes the third component of for loop which is the increment part. Here,
printf("%d %d \n", x, y)
simply prints x and y.
So, what happens is; when the loop starts, both x and y are 1.
The statement
y = x++ <= 5;
is encountered, thus the condition x++ <= 5 is checked, where x is 1. Since the condition is true; the value of y will be 1 and x will be incremented to 2. The same thing continues.... when x will be equal to 5, x++ <= 5 will check 5 <= 5 and the condition will be true and x will be incremented to 6. Now when it goes in the loop the next time; the condition will be false and y will instead be equal to 0. Thus, now when the loop checks the condition y, the condition will be false and thus the control will flow out of the loop and thus you see the result.
I built and dumped this code in IDA since I understand assembly better :D
This code is a bit obfuscated so here will be the normal version of it:
#include <stdio.h>
int x = 1;
int y = 1;
while(y != 0) {
if(x++ <= 5)
{
y = 1;
} else {
y = 0;
}
printf("%d %d\n",x,y);
}
that for loop in the source:
for(; y; printf("%d %d \n", x, y))
checks if y is a non-zero value and if it is, it will print the string you want. In the body of the loop, the result of the comparison (0 or 1) will be copied to y and the check continues.
Precedence of operator <= is higher than the operator =.
So, the statement:
y = x++ <= 5;
is equivalent to:
y = (x++ <= 5)
Because of post-increment ++ operator, the value of x returned first and then x is incremented.
The initial value of both x and yis 1.
Since y is 1, the for loop condition evaluates to true and the statement in the for loop block executed. But in the for loop of your code, in place of loop iterator update statement you have printf() statement which is printing the value of x and y after executing the loop body statements. The flow goes like this:
1 <= 5 evaluate to 1 which is assigned to y and after this x is 2,
Output : 2 1
2 <= 5 evaluate to 1 which is assigned to y and after this x is 3,
Output : 3 1
3 <= 5 evaluate to 1 which is assigned to y and after this x is 4,
Output : 4 1
4 <= 5 evaluate to 1 which is assigned to y and after this x is 5,
Output : 5 1
5 <= 5 evaluate to 1 which is assigned to y and after this x is 6,
Output : 6 1
6 <= 5 evaluate to 0 which is assigned to y and after this x is 7,
Output : 7 0
Now the value y is 0 and in your code, the for loop condition is y so the loop condition evaluates as false and loop exits.
I've written some code to Integrate the function 5x^4 + 4x^3 + 3x^2 + 2x + 1.
#include<stdio.h>
#include<math.h>
float func(float x){
float a;
a = 5*pow(x,4) + 4*pow(x,3) + 3*pow(x,2) + 2*x +1;
return a;
}
int main(){
float numberOfXValues;
float a = 0; //lower limit
float b = 1; //upper limit
float numberOfStrips;
float stripSize;
float finalAnswer;
float sumFirstAndLast; //summation of first and last x value
while(1){
printf("Input number of X values:");
scanf("%f", &numberOfXValues);
numberOfStrips = numberOfXValues - 1;
stripSize = (b - a)/(numberOfStrips);
sumFirstAndLast = 0.5*func(a) + 0.5*func(b);
for (float z = stripSize; z < b; z += stripSize ){
sumFirstAndLast += func(z);
}
finalAnswer = sumFirstAndLast * stripSize;
printf("%f\n", finalAnswer);
}
return 0;
}
And it works for the majority of values, but the output for 13 and 20 is giving the wrong answer. I've looked through it a few times but can't see what could be causing this.
Input number of X values:10
5.039070
Input number of X values:11
5.031651
Input number of X values:12
5.026160
Input number of X values:13
6.271982
Input number of X values:14
5.018732
Input number of X values:15
5.016153
Input number of X values:16
5.014071
Input number of X values:17
5.012367
Input number of X values:18
5.010955
Input number of X values:19
5.009773
Input number of X values:20
5.798243
Input number of X values:21
5.007917
The problem is that in the exit condition of the inner loop, you compare two floating point numbers. After numberOfStrips iterations, it's not guaranteed that z == b because of floating point accuracy. It's entirely possible that z < b or z > b. In the z < b case, the loop it executed another time.
You should make numberOfStrips an integer and rewrite the loop like this:
float z = stripSize;
for (int i = 1; i < numberOfStrips; i++) {
sumFirstAndLast += func(z);
z += stripSize;
}
At a first glance this looks to precision and rounding issues of float.
Therefore change float to double.
For example on my machine I get 6.271982 for an input of 10 when using float while I get 5.021983 as result when using double.
Moreover you should use an epsilon in floating point comparisons.
Placing the line:
printf("%f, %d\n", z, z < b);
Inside the for loop will print the z values each iteration along with the loop condition result. The last output of this will be:
1.000000, 1
Which is pointing that we have already reached the right limit, but still performing the loop body. Literally it is thinking that 1.000 < 1.000. It can happen when working with float numbers, so in order to prevent it, consider looping on some integer number (numberOfXValues for example).
I am trying to run a while loop program that has nothing to do with input. It is merely supposed to tell me what the final value of the calculation will be. However when I run the program it does nothing. It doesn't end either. I am confused at what is happening?
int x = 90;
while (x < 100)
{
x += 5;
if (x > 95)
x -= 25;
}
System.out.println( "final value for x is " + x);
The loop never terminates because x never reaches 100. If you want to see for yourself what's happening to x, add a line to your loop so that the code looks like this:
int x = 90;
while (x < 100) {
System.out.println("x = " + x); // More useful output here...
x += 5;
if (x > 95)
x -= 25;
}
System.out.println("final value for x is " + x);
What happen is that your while loop is never stopping, so it never prints something, try changing your code inside the loop.
How can you realize about that?
Put some prints out and inside the while loop:
int x = 90;
System.out.println("Before the while");
while (x < 100) {
System.out.println("Inside the while");
x += 5;
if (x > 95)
x -= 25;
}
System.out.println("final value for x is " + x);
Iteration 1:
x = 95
Iteration 2:
x = 100
if condition is true, so x = 75
... So whenever x reaches 100 the condition will make it 75. Therefore the while never ends.
I am not understanding for loop statement and expression following it. Please do help me understand.
#include<stdio.h>
int main()
{
int x = 1;
int y = 1;
for( ; y ; printf("%d %d\n",x,y))
y = x++ <= 5;
return 0;
}
And the output I got
2 1
3 1
4 1
5 1
6 1
7 0
y = x++ <= 5; ==> y = (x++ <= 5); ==> first compare x with 5 to check whether x is small then or equals to 5 or not. Result of (x++ <= 5) is either 1, 0 assigned to y,
As x becomes > 5, (x++ <= 5) becomes 0 so y = 0 and condition false and loop break,
Basically the for syntax is:
for(StartCondition; Test; PostLoopOperation) DoWhileTestPasses;
In this case:
StartCondition == None
Test == (y != 0)
PostLoopOperation == do some printing
DoWhileTestPasses == set y to zero if x > 5 otherwise to non-zero THEN increment x.
Which is all rather bad practice because it is confusing.
Would be better written as:
int x=0;
int y=0;
for(y=0; y = (x <= 6); x++)
{
printff("%d %d\n",x,y);
}
return(0);
In y = x++ <= 5;, y stores the value that is output by the condition x++ <= 5 (here x++ is post increment). If the condition is true then y = 1 else y = 0.
for( ; y ; printf("%d %d\n",x,y))
In the for loop you are printing the values of x and y after executing the for loop body.
Initialize your variables:
int x = 1; int y = 1;
There are 3 statements for the for loop: -1. Initialize, 2. Condition, 3. Iteration:increment/decrement
In your case, you did not provide the initialize condition, however, you have the part of condition and incrementation. I do not think your for loop is used in the correct way.
You should swap the part of incrementation with your body like this:
for(; y; y = x++ <= 5;)
printf("%d %d\n", x, y)
First, you check whether the condition is true or not, y is true or not. Then, you print x and y out. Then, the part of incrementation is executed, x++ <= 5 or not. The result is assigned to y. It does so until your condition is false, y == false.
NOTE: For the good programming, you should enclose your body with a curly braces.
similar to this
int x = 1;
for( int y = 1; y!=0 ; )
{
if (x++ <= 5)
{
y = 1;
}
else
{
y = 0;
}
printf("%d %d\n",x,y);
}
Perhaps this slightly transformed (but functionally equal) code will help:
int x = 1;
int y = 1;
while (y) {
y = (x <= 5);
x = x + 1;
printf("%d %d\n", x, y)
}