This was an exercise question from a C++ programming book. There's a flaw in this loop code. I am sure a lot of people would the answer straightaway. I am guessing is with the prefix increment operator.
int x = 0;
while (x)
{
++x;
cout << x << endl;
}
no, its x=0;
you need to assign x to a positive number like x=1 to get the loop running because x=0 evaluates to false, so loop will not run.
If x=0 the while loop will evaluate to false, and the body of the while loop will never be executed, since x will not be changed and always remain 0.
Nothing will be output, and the program will exit with a return code of 0, giving no clue to the lack of output.
The while loop will not execute at all since 0 is treated as false
while(false){
//will not execute; since (x=0 == false)
}
//skips above code and execute this directly.
if you want to run code inside loop you can just give a true value like x=1;
while(true){
//will execute (since x=1 === true)
}
while(1) is equivalent to while(x == 0), while(0) is equivalent to while(x)
The "semantic" is "while" running while .. and the variable "x" contains 0 so if it is added directly to the condition, as it is 0 = false
x == 0, return true if x == 0.
..
return (x == 0);
ref: https://www.tutorialcup.com/cplusplus/while-loop.htm
while(x) is evaluated as while(x!=0) so nothing will be output to the console. i.e. it is the same as:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
while (x != 0)
{
++x;
cout << x << endl;
}
return 0;
}
Related
I am new to coding and i am trying to print fabonacci sequence and i cannot understand why i am unable to get the output correct without subtracting 7 from my while loop condition . And can anyone tell me how to fix this problem.
#include<iostream>
#include<cmath>
using namespace std;
int main (){
double y;
double z;
int x;
cout <<"Enter the number you want to find the sequence of :";
cin>>x;
int zero = 1;
cout<<"Sequence equal to or less than "<<x<<" is :"<<"0";
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
cout<<","<<y;
} while(y<=x-7);
}
You "need" to subtract 7 because you want the last value printed to be smaller than x, but you check the condition after printing. Putting the -7 makes the last value printed smaller than x sometimes, but not always. Try x = 123 to get output 0,1,1,2,3,5,8,13,21,34,55,89,144 or x = 3 to get 0,1 while it should be 0,1,1,2,3.
To fix your code first check the condition and only then print it:
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
if (y <= x) {
cout<<","<<y;
} else {
break;
}
} while(true);
The issue is there's too much happening in this loop:
int zero = 1;
do {
z = (pow(1.618,zero)-pow(-0.618,zero))/2.236;
zero++;
y=ceil(z);
cout<<","<<y;
} while(y<=x-7);
You are combining the iteration of zero, with the computation of y, with the check against x. Spelling out every step is error-prone, and if the loop is more than a few lines it becomes hard to tell what's going on. If your loop is not doing what you want, a good approach is to abstract out the details of the loop by wrapping that in a function.
For example, simply by refactoring the computation of y, like this:
auto fib = [](int zero) {
return ceil((std::pow(1.618,zero) - std::pow(-0.618,zero)) / 2.236);
};
You can use a much more natural loop construct for the problem:
for(int zero = 1; (y = fib(zero)) <= x; ++zero)
std::cout<<","<<y;
Here's a demo.
This is still more complexity than necessary. From c++20, you could declare all the fibonacci numbers:
auto fib_nums = std::views::iota(1) | std::views::transform(fib);
This has the nice advantage that it can be used for different purposes, and keeps generating fibonacci numbers forever.
Now your loop can just do the needed comparison:
for(int y : fib_nums | std::views::take_while([x](int y) { return y <= x; }))
std::cout << "," << y;
Here's a demo.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I just came upon one problem. I wanted to compare whether my Eratostenes's Sieve contains prime numbers or not. In the code i have this line
if (sieve[2] == is_prime(2)) // returns false
printf ("true");
Now, sieve[2] is a boolean and it's value is true (I even checked in the array, so there's no doubt about it). is_prime(2) is a boolean aswell (I also checked).
Now my problem. The line presented above returns false. Yes - it returns false even though it's statement is:
if ( true == true ) // which normally returns true
printf ("true");
However, after removing one equation sign:
if ( sieve[2] = is_prime(2) ) // returns true
printf ("true");
This statement returns true.
Can someone briefly explain how does one equation mark work in this case in comparison to ==?
Thanks in advance
EDIT
is_prime:
bool is_prime(int x) {
unsigned int i,j,k;
if (x < 2) return false;
else {
for (i=2; i!=x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
}
}
sieve:
const int n = 10000;
bool sieve[n+1];
.
.
unsigned long int i;
sieve[0] = sieve[1] = false;
for (i=2; i<=n; i++) sieve[i] = true;
for (i=2; i*i<=n; i++) {
if (sieve[i]) {
unsigned tmp = 2*i;
while (tmp <= n) {
sieve[tmp] = false;
tmp += i;
}
}
}
[EDIT2]
The problem was with "is_prime(x)" Changed loop condition from "i!=x" to "i<=x"
Sorry for the trouble and thanks for the answers
UPDATE
bool is_prime(int x) {
unsigned int i,j,k;
if (x < 2) return false;
else {
for (i=2; i!=x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
}
}
Your is_prime() (above) is broken, with undefined behaviour, as when x is 2 (or indeed any actually prime number) it reaches the end of the function without having a return statement - the i!=x test means the x == i inside the loop can never be true.
is_prime(2) it's likely to return effectively random results (based on left over stack or register content / in your documented output it's seeming "returning" x itself, presumably because your ABI uses the same CPU register or stack address to pass in the argument and pass back the function's return value).
Specifically for 2, flow enters the first else clause, then with i=2 the first i!=x test fails and the for loop immediately exits... there's no return after the for's scope. Minimally corrected code (faster implementations are possible, but keeping the simplicity and intended logic):
bool is_prime(int x)
{
if (x < 2) return false;
for (int i = 2; i < x; ++i)
if (x % i == 0)
return false;
return true;
}
Equivality / ==
With sieve[2] == is_prime(2) it's checking they have the same value - possibly after converting one of the values to enable the comparison, but you say they're both booleans so that's not necessary. This would yield a "true" value for the if when they're both true or both false.
Now my problem. The line presented above returns false. Yes - it returns false even though...
That doesn't make any sense... I suggest you add the following before the if statement to check the variables' values:
std::cout << "sieve[2] " << sieve[2] << " (bool)" << (bool)sieve[2]
<< ", is_prime(2) " << is_prime(2) << std::endl;
I even checked in the array, so there's no doubt about it
Be wary of mistakes like seeing the array content displayed ala { true false true false } and thinking [2] is the second value... it's actually the third. as array indexing starts at 0.
Assignment / =
With sieve[2] = is_prime(2) you're assigning the value of is_prime(2) into sieve[2], and the if statement is deemed "true" if that value is deemed true in a boolean context (i.e. it's a boolean with value true, or a non-0 number or pointer etc.). For most data types, the execution flow of if (sieve[2] = is_prime(2)) ... is the same as simply if (is_prime(2)) ..., but of course it also modifies sieve[2].
It assigns the right hand operand to left, and returns the left operand.Since you are assigning true to your variable, it evaluates to true. If you set your variable to false, you don't get the output, e.g:
bool x;
if(x = false)
printf("this won't be printed");
Here the equal affect the left operator with the value of the right operator then test the value. So the result must be the value of the right operator.
Your loop in is_prime will never run for the check x == i will be true, because it runs as long as x != i. Those two conditions are mutually exclusive.
That means the function will end without a return statement, which leads to undefined behavior.
This
if ( sieve[2] = is_prime(2) )
contains an assignment, not a comparison.
As the value of an assignment is the value assigned, it is true whenever is_prime(2) is.
However, let's look at your is_prime and see what happens if we pass it a 2...
bool is_prime(int x) {
unsigned int i,j,k;
So far, so good, but j and k are never used, so they shouldn't really be here.
if (x < 2) return false;
2 isn't less than 2, so we'll continue...
else {
for (i=2; i!=x; i++) {
OK, set i = 2, and compare it to x which is 2, and... oops, i is equal to x, so we'll abandon the loop immediately...
if (x == i) return true;
else if (x % i == 0) return false;
}
}
... and fall through here, where we're not returning a value like we promised, and causing undefined behaviour.
}
So, your program is undefined (you really should switch on compiler warnings, or start listening to them).
And this happens on every number that is prime.
You can rewrite the loop like this:
for (i=2; i <= x; i++) {
if (x == i) return true;
else if (x % i == 0) return false;
}
or
for (i=2; i < x; i++) {
if (x % i == 0) return false;
}
return true;
Why does if (is_prime(2)) appear to work?
(Since this code is undefined, the following is largely speculation and should only be taken with suitable measures of salt.)
Often, when a function is supposed to return something but doesn't, the calling function will just grab whatever is stored in the place where the return value should have been and use that.
This value is in this case very likely not the same as the bit pattern that represents true, so will compare unequal to true, in if (is_prime(2) == true).
It will however, also very likely, not be the bit pattern that represents false either, so will be considered true in a conditional, if(is_prime(2)).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a trouble understanding what does this code do :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (x++ && y++)
y += 2;
cout << x + y << endl;
return 0;
}
The output is 1 by C++. But I think it should be 2?
Why? Because in the () of if statement, I think there should only check if it's true/false, so it doesn't increment/decrement any of the integers. And since that's true by default, it increases y for 2? And output should be 0+2 = 2, but it outputs only 1?
if (x++ && y++) will not do y++ because the condition to the left of the logical and operator (&&) is false since x++ will return 0 and increment x by 1.
Since false && expression will yield false for any expression, there is no need to evaluate the rest of it.
Hence, you end up with x = 1 and y = 0.
This is called Short-circuit Evaluation.
The post ++ operator has high priority and && operator is allowed to short circuit evaluation.
What happens in if (x++ && y++) is that first it evaluates x++. The result is 0 and increments x. Since 0 is false && will short circuit the evaluation of y++ (will not be executed). Also the if will evaluate to false and will not execute the y+=2.
So now you have x=1 and y=0.
So the result is 1.
it will first execute x++ and the compiler knows that because of that the expression x++ && y++ will be false and will ignore y++
as a result after that x = 1 and y = 0;
it is the same as writing if(false && do_something()) , in this case do_something() will never be called.
I advice you to take a look at the operator precedence chart : http://en.cppreference.com/w/cpp/language/operator_precedence
//in a statement, x++ will evaluate x then increment it by 1.
//in a statement, ++x will increment x by 1 then evaluate it.
If you have hard time to understand it then try the below code to better understand :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (++x && ++y) // in your case, with the previous code, it gives (0 && 0)
// instead of if statement you can try the following : cout << x++; then cout << ++x;
// and notice the difference
y += 2;
cout << x + y << endl;
return 0;
}
Alright, beginner, take it easy. Thanks.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int x = 0;
bool while1 = true;
while (while1)
{
cout << x << "\n";
sleep(200);
if (x < 10)
{
while1 = true;
}
else if (x >= 10)
{
while1 = false;
}
x = x+1;
}
cin.get();
}
Alright, so I don't understand why the program even gets x to 10 if I'm have the if statements check if x < 10 before I have 1 added to x... please explain.
Order of operations is:
1) stop the loop if 3) found x was >= 10 (if while1 is false)
2) print out x
3) check if x >= 10 here and set while1 to false if it is
4) increment x
When x is 9 we proceed as follows:
Don't stop the loop (while1 is true)
Print out 9
x is not >= 10 yet, set while1 to true
x is incremented to 10
Don't stop the loop (while1 is true)
Print out 10
x is now >= 10, set while1 to false
x is incremented to 11
We stop the loop as while1 was set to false
So, x gets printed out when it's 10. The problem is that, the way you check and act on the check, you do one loop too many before stopping.
One way to fix this is
while (x < 10)
{
cout << x << "\n";
Sleep(200);
x = x+1;
}
Now the loop will not execute on the same pass through that x is 10, not the pass immediately afterwards.
Even better is this:
for (int x = 0; x < 10; ++x)
{
cout << x << "\n";
Sleep(200);
}
Which is clearer about its intent over looping over incrementing values of x.
The program gets x to 10 because the x = x + 1 happens outside of the if.
So during one execution of the loop, it will check, then if x is less than 10 it will make while1 true. Otherwise it makes while1 false. After that it increases x no matter what.
Then it repeats this process if while is true.
else if (x >= 10)
{
while1 = false;
}
x = x+1;
I understand the question as: Why is x getting to 10? Is this correct?
Your while loop does not immediately exit when setting while1 to false. So of course x will equal to 10 after exiting the loop as x is increase after checking that, so x will in fact be 11 after this code segment.
If you don't want x to be printed after x >= 10, do the checking after you increment x.
#include <iostream>
#include <windows.h>
using namespace std;
int main(
{
int x = 0;
bool while1 = true;
while (while1)
{
cout << x << "\n"
x++;
Sleep(200);
if (x < 10)
{
while1 = true;
}
else if (x >= 10)
{
while1 = false;
}
}
cin.get();
}
if x>=10 in the loop than obviously the loop will iterate one more time when it reaches to 10 in the while loop
What you are doing is:
asking the program to print the value of x
check to see if x is less than 10
if it is, set while1 to true. Else set while1 to false
increase the value of x by 1 (regardless of whether while1 is true or false)
...
At the start of the 10th loop, x = 9.
Prints out 9
Since x is still less than 10, while1 remains true
At the end of the 10th loop, x = 10 and while1 = true
Your program start another loop since while1 = true
At the start of the 11th loop, x = 10.
Prints out 10
Since x is now equal to 10, while1 is set to false
At the end of the 11th loop, x = 11 and while1 = false
Best thing to do is to just
int x = 0;
while(x < 10)
{
cout << x << endl; //this way your program will only print 0 to 9
sleep(200);
x++; //this is the same as x = x+1
}
If you insist on using your own code, I guess you can replace your while1 = false with break;
else if (x >= 10)
{
break;
}
break; will let you break out of the while loop if x >= 10 without increasing x or going through the loop again...
Should be safe unless you are going to do more things in that while loop...
I want to apply a while loop and have written that while (a!=-1); it should exit but it's printing "0" always and I don't know why. Can you explain?
#include <stdio.h>
int main()
{
long num;
int a,i,j;
int arr[10000];
float x;
while( a != -1)
{
scanf("%d",&a);
int sum=0;
for(i=0;i<a;i++)
{
scanf("%d",&arr[i]);
sum = sum + arr[i];
}
x = sum%a;
if (x == 0)
{
int z = sum/a;
int y=0;
for(j=0;j<a;j++)
{
if (arr[j]>z)
{
y = (arr[j] - z) + y ;
}
}
printf("%d",y);
}
else
printf("-1");
}
}
I think it is printing y; how to avoid so that it only exits?
First of all, you failed to initialize a before running the while loop, so the behavior of your program will be undefined and it could just terminate right away.
Second, you said "while(a!=0)" in your question but your code says "while(a != -1)". Which one is correct: 0 or -1? Maybe if you just changed the -1 to a 0 the program would behave as expected.
You want to write while( a != 0) but you actually have written while( a != -1).
Fix that. Then the loop will exit when you enter 0.
I got my answer actually i have to take my scanf("%d",&a); outside while loop ;