C++ while statement not equal checks - c++

I started coding in C++ (VS 2015).
Wrote a little program which using a while statement.
#include <iostream>
using namespace std;
int main() {
int x = 1;
int y = 2;
int z = 0;
while (x != y || z != y) {
cout << "x: " << x << "\n" << "z: " << z << "\n";
x++;
z++;
}
cin.get();
}
If i get this correctly it should work in that way (but since its going to an infinite loop i guess my logic is not as correct as i think).
So in my mind the while statement should work in that way.
While X not equal to y OR z not equal to y.
add +1 to X and +1 to Z.
Do this until the statment became true (or atleast the left side of the expression).

There's no iteration where both of your conditions become evaluated to false at a certain point, hence the loop doesn't stop.
You can easily investigate that behavior by stepping through your code using a debugger, and watch how the variable values change.

Loop iterations
x=1, y=2, z=0, condition: true
x=2, y=2, z=1, condition: true
x=3, y=2, z=2, condition: true
. . . and so on
The condition never evaluates to false, and leads to infinite loop. Consider changing to and operator to make the loop finite, or maybe change some values.
while (x != y && z != y) {
Output
x: 1
z: 0

The 1st expression of while condition is becoming false after first iteration.
the 2nd expression is becoming false after a couple of iteration, but after first execution the first expression is becoming true again, and your program runs forever because infinite loop.

the loop will keep iterates because whenever the x and y value is increased, it will never become 0, which is equals to the value that is assigned to y. (simple logic)
Change this statement-> while(x!=y||z!=y) into this-> while(x!=y && z!=y)
you should get the output:
x:1
z:0

Related

what does if(!(x%3)) mean?

I am attempting to solve a hw problem in which I need to write down what the program will output. I am stuck however, on the syntax "if ( !(i%3)). What does that really mean? Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
int main () {
for (int i=0; i<10; (i<3?i++;i+=2)) {
if (!(i%3)) {
continue;
}
else if (i%7 ==0) {
break;
}
cout << i<< endl;
}
Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
Correct. The longer version of that check would be
if (i % 3 == 0)
continue;
The most common use case for such branching is probably FizzBuzz.
İt means if i is not(!) divisible by 3 continue.
For example if i is 3,6,9 it won't continue otherwise it will continue.
if (x) where x is int implicitly compared with zero. I.e. if (x) equals to if (x != 0). ! is negation. So if (!x) equals to if (x == 0). And the last step is if (!(i%3)) equals to if ((i%3) == 0) what is the same with check, that i deivisible by 3
The if() statement is false only if the result inside the parentheses is 0 (false). Take a look at your program:
i%3 may return 0 (false), 1 (true), or 2 (true)
The negation operator ! changes the result of the operation (i%3). So, if the i is divisible with 3 the statement will return 0 (false). Being negate, ! it will result in True. Otherwise the result of (i%3) will be true and with the operator ! the result of the hole statement will be false. Basically this code is checking if the value of i is divisible with 3.
Other options will be:
if (0==i%3)
{
/*code*/
}
Your code can be simplified as below
int main() {
for (int i=0; i<10;)
{
if (i % 3 == 0) {
continue;
}
else if (i % 7 == 0) {
break;
}
cout << i << endl;
i = i<3 ? i+1 : i+2;
}
}
When you write a integer variable like i as a condition, what happens is that if i==0 then the result of the condition is false, otherwise it would be true.
Let's check it out in your program, if(!(x%3)), let's name condition= !(x%3), when this condition is true? when x%3 == 0, note that the negation operator ! is behind x%3, so in this case the condition would be equal to true, more formally the condition is equal to :
if(x%3==0)
these kinds of conditions are common, check this example out :
int t = 10;
while(t--){
cout<<t<<endl;
}
The above condition i.e if(!(i%3)) will true when " i is not disvisable by 3"
Hope this helps.
In java and other languages there is a special type to represent booleans and evaluate expressions; in c and its variants there is no such thing, instead an expression is considered "true" if -taken as a integer number- is equal to 0; false for every other value. (Fun fact: this is why you usually end the code by return 0)
So if(x%3) in c is equivalent to if(x%3==0) in other languages. That said, if(x%3) execute the if body when the remainder of x/3 is 0, that is when x is a multiple of 3.
In your code you have the ! before, that -as you may know- "inverts" the expression. That means that if(!(x%3)) can be read as "If the remainder of the integer division of x by 3 is not 0", or alternatively: "If x is not a multiple of 3".
So, basically, you saw it right.
Hope I helped!

How can I print the square roots of the first 25 off integers by using a while loop with i=i+1 instead of i=i+2

When I try to solve this problem I write the following code:
int x = 1;
while(x%2 != 0 && x <= 50) { //x%2 != 0 defines odd integers and x<=50 gives the first 25
cout << pow(x,0.5) << endl;
x = x + 1;
}
This code only prints out the value of the square root of 1. So I edit the code like so:
int x = 1;
while(x%2 != 0 && x <= 50) {
cout << pow(x,0.5) << endl;
x = x + 2;
}
Now it prints out all the 25 odd integer square roots.
So the problem with the first code is clearly that the while loop is stopping once the square root cannot be executed (i.e. when the integer is even). It is executing the square root of 1, moving on to the integer 2, not executing the square root, and instead of then moving onto the integer 3 it is stopping. This is why the second code works: because I am adding 2 it is only ever meeting an odd integer, so always works and thus continues until x<=50.
How can I stop it from stopping and why is it doing this? I would have thought that it would register each and every integer that satisfies the condition but it is not doing this.
while executes while the condition is true. On the second iteration x == 2, so the condition x%2 != 0 becomes false, consequently x%2 != 0 && x <= 50 becomes false and while loop terminates.
You already solved How can I stop it from stopping part by incrementing x by 2, so it's unclear what you are asking here.

Inifinite loop makes variable come out as 0

I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.

need understanding of while loop condition (see comment)

while (x >= 1000)
{
cout << "M";
x -= 1000;
}
Can someone explain to me how this while loop works? I understand the condition is for x is greater or equal to 1000, it will print out 'M'.
The part after that is what I actually don't understand, is it saying that it will keep subtracting a thousand from X and keep printing until the condition is false?
Yes, that is exactly what it will do.
This translates roughly into:
While x is greater than or equal to 1000, do what is in the code block (over and over until the condition fails)
The code block then prints M and sets x equal to itself minus 1000. (x -= 1000 is the same as x = x - 1000
Hypothetical:
x = 3000
x is greater than 1000
print M
x is set to 2000
loop resets and checks x...passes test
print M
x is set to 1000
loop resets and checks x...passes test because of = portion
print M
x is set to 0
loop resets and checks x...fails
moves to the code after the while code block
while (x >= 1000) //x is greater than or equal to 1000
{ //executes loop if condition true, else the statement after the loop block
cout << "M"; // print M
x -= 1000; // x = x-1000
} //goes back to condition checking
You are right!
x-=1000;
is actually
x=x-1000;
Yes.
it saying that it will keep subtracting a thousand from X and keep printing until the condition is false
The program appears to be an inefficient way of writing
x %= 1000;
which is x = x%1000, where % is the modulus operator.
Your code reaches the same result by subsequent substraction, and stops when x<1000.

C++ reading a sequence of integers

gooday programers. I have to design a C++ program that reads a sequence of positive integer values that ends with zero and find the length of the longest increasing subsequence in the given sequence. For example, for the following
sequence of integer numbers:
1 2 3 4 5 2 3 4 1 2 5 6 8 9 1 2 3 0
the program should return 6
i have written my code which seems correct but for some reason is always returning zero, could someone please help me with this problem.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int x = 1; // note x is initialised as one so it can enter the while loop
int y = 0;
int n = 0;
while (x != 0) // users can enter a zero at end of input to say they have entered all their numbers
{
cout << "Enter sequence of numbers(0 to end): ";
cin >> x;
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
n = n + 1;
y = x;
}
else
{
n = 0;
}
}
cout << "longest sequence is: " << n << endl;
return 0;
}
In your program, you have made some assumptions, you need to validate them first.
That the subsequence always starts at 1
That the subsequence always increments by 1
If those are correct assumptions, then here are some tweaks
Move the cout outside of the loop
The canonical way in C++ of testing whether an input operation from a stream has worked, is simply test the stream in operation, i.e. if (cin >> x) {...}
Given the above, you can re-write your while loop to read in x and test that x != 0
If both above conditions hold, enter the loop
Now given the above assumptions, your first check is correct, however in the event the check fails, remember that the new subsequence starts at the current input number (value x), so there is no sense is setting n to 0.
Either way, y must always be current value of x.
If you make the above logic changes to your code, it should work.
In the last loop, your n=0 is execute before x != 0 is check, so it'll always return n = 0. This should work.
if(x == 0) {
break;
} else if (x > y ) {
...
} else {
...
}
You also need to reset your y variable when you come to the end of a sequence.
If you just want a list of increasing numbers, then your "if" condition is only testing that x is equal to one more than y. Change the condition to:
if (x > y) {
and you should have more luck.
You always return 0, because the last number that you read and process is 0 and, of course, never make x == (y + 1) comes true, so the last statement that its always executed before exiting the loop its n=0
Hope helps!
this is wrong logically:
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
Should be
if(x >= (y+1))
{
I think that there are more than one problem, the first and most important that you might have not understood the problem correctly. By the common definition of longest increasing subsequence, the result to that input would not be 6 but rather 8.
The problem is much more complex than the simple loop you are trying to implement and it is usually tackled with Dynamic Programming techniques.
On your particular code, you are trying to count in the if the length of the sequence for which each element is exactly the successor of the last read element. But if the next element is not in the sequence you reset the length to 0 (else { n = 0; }), which is what is giving your result. You should be keeping a max value that never gets reset back to 0, something like adding in the if block: max = std::max( max, n ); (or in pure C: max = (n > max? n : max );. Then the result will be that max value.