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...
Related
I think my code has an infinite loop. Can someone tell me where I went wrong?
The code is supposed to find the number of valid numbers, with a valid number being a number without a digit repeating. For example, 1212 would be a non-valid number because 1 and 2 repeated.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int a; int b; int count_validNums = 1; int digit; int last_digit; bool is_valid = true;
vector <int> num_list;
cout << "Enter numbers 0 < a <= b < = 10000: ";
cin >> a >> b;
// Checks for invalid input
if (a < 0 || b < 0 || a > 10000 || b > 10000) {
cout << "Invalid input";
return 1;
}
// Checks every number from the range [a,b]
for (int i = a; i <= b; i++){
last_digit = i % 10;
num_list.push_back(last_digit);
i = i / 10;
while (i != 0){
digit = i % 10;
if (find(num_list.begin(), num_list.end(), digit) != num_list.end()){
is_valid = false;
}
num_list.push_back(digit);
i = i / 10;
}
if (is_valid) count_validNums++;
}
cout << "They are " << count_validNums << " valid numbers between" << a << " and " << b << endl;
}
The inner while loop terminates when i == 0. Then the outer for loop increments it (so i == 1), then the inner loop reduces it to zero again. Then the other loop increments it, then ...
What is happening to cause the infinite loop is that you are constantly reducing the int i back down to 0. Consider these highlights:
`for(int i = a; i <= b; i++){
//stuff
while(i != 0){ //<--this forces i down to 0
//more stuff
i = i / 10;
}
//final stuff
}`
i here is all one variable, so any changes you make to it anywhere will affect it everywhere else it exists! Instead, you can try saying something like int temp = i; and then perform your operations on temp so that i remains independent, but because your for-loop terminates when i <= b and you are constantly resetting i to 0, it will never reach b.
Also, I noticed that in your check for valid numbers you verify that 0 < a,b < 10000, but later in your for-loop you seem to make the assumption that a <= b will be true. Unfortunately, your test does not ensure this, so the for-loop will immediately terminate for inputs where b < a is true (which your program currently allows) and your program will report answers that are likely incorrect. The same is true when I enter letters as input instead of numbers. You might want to revisit that portion of code.
I was trying to solve this problem and from the comments section in the editorial, I was directed to the following solution :
#include <bits/stdc++.h>
using namespace std;
#define MAX(a,b,c) max(a,max(b,c))
int n,a,b,c,dp[4001];
int f(int x)
{
if (x == 0) return 0;
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
}
int main()
{
cin >> n >> a >> b >> c;
memset(dp,0,sizeof(dp));
cout << f(n) << endl;
}
I wanted to know:
What is the need of the if statement that returns 0xACCE97ED for the test case:
4000 1 2 3. This test case dosen't work when that specific if statement is missing.
Why specifically 0xACCE97ED is being returned? Because when I tried to return any other number (say 9999), then the output is expected output + 9999.
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // -1395746835
Well looking at the dp function, it is basically maximizing values and this specific if statement is saying:
if x < 0
the length of the ribbon you cut is negative (which should be impossible)
or if x > 0 and x < a, b, c which means you can still cut X but all available sizes would result into having a ribbon of negative length
return 0xACCE97ED; return a random negative value which happens to spell out ACCEPTED because this state is invalid
And since the third if statement will try to get the max value, 0xACCE97ED will never be selected as the max value.
0xACCE97ED means "ACCEPTED" in the 1ee7 speech. nothing else specific about this value.
What is the need of the if statement that returns 0xACCE97ED for the test case: 4000 1 2 3
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
because the function f is recursive, in the next line it calls itself:
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
with a smaller values for x so presumable it will eventually make that if statement true and will return "accepted" (0xACCE97ED).
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;
}
When I Build and run my code it instantly returns 0 saying programing was successful, however i want it to display all the numbers from 100 to 200 that are divisible by 4.
Here's my code...
#include <iostream>
using namespace std;
int main()
{
int num = 200;
int snum;
cout<<"The following numbers are all divisble by 4 and are inbetween 100 and 200\n";
while(num<99)
{
snum = (num % 4) ;
cout<<snum<<endl;
cout<<num<<endl;
if(snum = 0)
{
cout<< num << endl;
}
else
{
}
num--;
}
return 0;
}
The while condition should be while (num > 99) instead of while(num<99)(false at the beginning)
The if condition should be if (snum == 0) instead of if(snum = 0)(= is assignment, not equal operator)
The else part has nothing, you may delete it. I added some other notes in the comments below.
while (num > 99)
{
snum = num % 4 ; // no need for the parenthesizes
if (snum == 0)
{
std::cout<< num << std::endl;
}
--num; //pre-increment is preferred, although doesn't matter in this case
}
Your loop never executes because the condition
(num<99)
is already false from the start. You probably meant
(num>99)
Also, the if statement condition
(snum = 0)
sets snum to zero, always returning zero, so you probably meant
(snum == 0)
You set num to be 200:
int num = 200;
Then you only run the loop if and when the number is less than 99:
while(num<99)
What do you expect will happen?
This is not how you do an equals-test in C:
if(snum = 0)
In C, equality is checked with ==:
if(snum == 0)
In fact, what you have (if (snum = 0)) will NEVER be true, so your if-statement will NEVER be executed.
I'm trying to print all the prime numbers in series, the code I ended up with is below, instead of printing all primes it prints random numbers, Some are prime and some are not :/
Why is that so?
#include <iostream>
using namespace std;
long int x,y=3;
int a=3;
bool isprime;
int main()
{
while(a<=100)
{
for(x=2;x<=y;x++)
{
if(y%x==0 && x!=y)
{
isprime=false;
break;
}
else if(y%x!=0 && x!=y)
{
isprime = true;
}
}
if(isprime==true && y%x!=0 && x!=y)
{
cout<<a<<" is a prime number."<<"\n";
isprime=false;
}
a++;
y++;
}
}
This
if(isprime=true && a%x!=0 && a!=y)
should be this
if(isprime==true && a%x!=0 && a!=y)
That's a common mistake. But even better is to realise that you don't need to compare bools against true of false, because they are true or false. So just
if (isprime && a%x!=0 && a!=y)
The logic just looks all wrong (and way too complicated), try this
isprime = true;
for(x=2;x<a;x++)
{
if(a%x==0)
{
isprime = false;
break;
}
}
if (isprime)
{
cout<<a<<"\n";
}
No need for y.
Well what jumps into my eyes is that you never increment y.
y is 3 in the beginning, so you only try if 2 is a possible divisor of a and then go to the next a.
Anyway, I am not sure what you wanted to achieve with y.
Let x run from 2 to a/2, as there is no need to try numbers bigger than a/2.
This is simply because there never will be a divisor bigger than a/2.
Example: a = 30. It would not make sense to try to divide by 16 or bigger, as the result can never be a integer (besides a itself of course)
However, this should do what you want:
int x = 0;
int a = 0;
bool isPrime = false;
for(a=3; a < 100; a+=2)
{
isPrime = true;
for(x = 2; x <= a/2; x++) {
if(a%x == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << a << "\n";
}
}
there are of course other algorithms that can find primes, but I wanted to use your approach basically.
Cheers
Chris
EDIT:
Someone was faster :)
anyway: there is no need to run higher than a/2, this is a important optimization...!
EDIT2:
another optimization is of course skipping all even numbers, so start with a = 3 and increment by 2 for each loop iteration...
I see your code is ok now.
Nevertheless I made small changes, cleaning the code and making it a little bit faster.
#include <iostream>
using namespace std;
long int x, y = 2;
int a = 3;
bool isprime;
int main() {
while (a <= 100) {
while ((y + 1) * (y + 1) <= a) {
y++;
}
isprime = true;
for (x = 3; x <= y; x += 2) {
if (a % x == 0) {
isprime = false;
break;
}
}
if (isprime) {
cout << a << " is a prime number." << "\n";
}
a+=2;
}
}