need understanding of while loop condition (see comment) - c++

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.

Related

C++ while statement not equal checks

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

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.

Having trouble understanding a portion of code (bit operation)

I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.

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.