What's wrong with my while loop condition code? - c++

I wrote the following code, but after I compiled it, and run it, nothing happens. I can't figure out what's wrong with it.
There are two "and conditions" in the while loop. When I take out 1 condition, it works fine, but when I put both conditions in, it no longer works.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter an integer greater than 10: ";
cin >> n;
int c=1;
while ( (c*5 <= n*2) && (c*5 >= n) ) {
cout << c*5 << endl;
c = c+1;
}
return 0;
}

Your condition will never be true. You start with n > 10, let's say n == 11. Initially, c == 1.
Your condition is:
while ( (c*5 <= n*2) && (c*5 >= n) )
so that's:
while ( (1*5 <= 11*2) && (1*5 >= 11) )
or
while ( (5 <= 22) && (5 >= 11) )
5 is less than 11, so 5 >= 11 is false, and the loop never runs.

If n is greater than 10, then c*5 (ie. 5) will not be >=n so the loop condition will be false on the first evaluation.

Related

Possible infinite loop

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.

Why is this code not working for big number?

I'm doing question 4.11 in Bjarne Stroustrup Programming-Principles and Practice Using C++.
Create a program to find all prime numbers in the range from 1 to max using a vector of primes in order(prime[2,3,5,...]). Here is my solution:
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
bool check_prime(vector<int> &prime, int n) {
int count = 0;
for (int i = 0; prime[i] <= n || i <= prime.size() - 1; ++i) {
if (n % prime[i] == 0) {
count++;
break;
}
}
bool result = 0;
if (count == 0)
result = 1;
else
result = 0;
return result;
}
int main() {
vector<int> prime{2};
int max;
cout << "Please enter a max value:";
cin >> max;
for (int i = 2; i <= max; ++i) {
if (check_prime(prime, i))
prime.push_back(i);
}
for (int i = 0; i <= prime.size() - 1; ++i) {
cout << prime[i];
if (i <= prime.size() - 2)
cout << ',';
}
}
My code is working for numbers smaller than 23 but fail to work for anything bigger. If I open the program in Windows 10 the largest working number increase to 47, anything bigger than that fail to work.
This condition
prime[i]<=n||i<=prime.size()-1
makes the loop continue as long as at least one of them is true, and you're accessing prime[i] without checking the value of i.
This will cause undefined behaviour as soon as i == prime.size().
This means that anything can happen, and that you're experiencing that any specific values are working is just an unfortunate coincidence.
You need to check the boundary first, and you should only continue for as long as both conditions are true:
i <= prime.size() - 1 && prime[i] <= n
which is more idiomatically written
i < prime.size() && prime[i] <= n
(It's never too soon to get comfortable with the conventional half-open intervals.)
You check prime[i]<=n before i<=prime.size()-1. Then, if it's true (even if i>prime.size()-1, which is random behaviour), you work on it, generating wrong results.

After input my program seems to skip the first IF statement and go directly to ELSE

I have a problem with the code. It compiles with no errors, but right after taking input from the user it even with correct values it seems to skip the first conditional statement and go directly to ELSE which causes the program to terminate. I can't seem to find the cause for this behavior.
I think it might the issue with the way the conditional statement is constructed:
if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){
I need to check if the value entered is 25 <= S <= 75 and is divisible by 5, as well as the other value being 0.2 < U < 0.7
Course Assignment
//#include "stdafx.h" // Header File used VS.
#include <iostream>
//#include <iomanip> // Used to format the output.
#include <cstdlib> // Used for system().
#include <math.h> // Used for sqrt().
using namespace std;// ?
int main (){
int S; // Gram/Litre
double U; // Specific Max. Growth Rate. Per Hour.
double D; // Maximum Dilution Rate.
const int K = rand() % 7 + 2; // Saturation Constant - Randomly Gegerated Number Between 2 & 7. In Hour/Litre.
cout << "Enter value between 25 and 75, divisible by 5, for S in Gram/Litre: ";
cin >> S;
cout << "Enter value bigger than 0.2, but less than 0.7, for U per Hour: ";
cin >> U;
if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){ // Check Condition ***May Need Adjustments***
D = U * ( 1 - sqrt ( K / ( K + S) ) ); // Might have to adjust values to fit data type double. Add .00
cout.precision(3); // Prints 3 values after decimal point.
cout << "Maximum dilution rate is: " << D << endl;
if( D < 0.35 && D < 0.45 ){
cout << "Kinetic parameters are acceptable." << endl;
}
else{
cout << "Kinetic parameters are not acceptable." << endl;
}
}
else{
cout << "Invalid Input. Program will now terminate." << endl;
}
system("PAUSE"); // Pauses the program before termination.
return 0;
}
First, if you want 25 <= S <= 75, you should have
25 <= S && S <= 75, not S <= 25 && S <= 75. Same with U < 0.2 and D < 0.35 - they should be 0.2 < U and 0.35 < D.
Second, the above statement returns a boolean - thus, if S is a value between 25 and 75, the boolean will be cast to an integer value of 1, and 1 % 5 == 0 always be false. (Similarly, if S is outside this range, the boolean will be cast to an integer 0 and 0 % 5 == 0 will always be true)
A correct, complete if-statement is as follows:
if((25 <= S && S <= 75) && (S % 5 == 0) && (0.2 < U && U < 0.7)){
...
if(0.35 < D && D < 0.45){
...
}
...
}
If you read a number between 25 and 75 from the input, the if( ((S <= 25 is always false.
You must use if( ((S >= 25 && ....
The problem mainly lies in your loop conditions. For example, in this line from your code:
if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){
//...
}
The if condition S <= 25 && S <= 75 simply can be rewritten as S <= 25 because in words, your parameter states that if S is less than or equal to 25 OR if S is less than or equal to 75, and so on.
The same problem exists here: U < 0.2 && U < 0.7. Once again, the if statement simply checks whether U is less than 0.2 and U is less than 0.7, the latter always being true if the former is true.
However, in your output statement before accepting the 2 inputs, you state that S should have a range of 25 <= S <= 75, meaning that S is greater than 25; not less. The same issue for U: you are expecting input ranging between 0.2 < U < 0.7.
How you should rewrite your if-then statement is as follows:
if( (S >= 25 && S <= 75) && (S % 5 == 0) && (U > 0.2 && U < 0.7) ){
//...
}
This not only makes your if-statement's conditions easier to read and comprehend, but it also eliminates the errors. This should work now. The meaning of the code stays the same: S has to be between 25 and 75 (including these numbers), it should be divisible by 5, and U should be between 0.2 and 0.7.
BTW, the same mistake exists in this part of your code also:
if( D < 0.35 && D < 0.45 ){...
I fixed it below:
if( D > 0.35 && D < 0.45 ){...
Good luck!

My program run and returns 0, but it doesn't display the cout data ive given it

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.

Define not evaluating POD?

I was going over the C++ FAQ Lite online. I was browsing inlines again since I haven't found a use for them and wanted to know how the stopped the circular dependency as showed in this answer. I first tried to do the, "Why inlines are better than defines." example with the following code:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
inline
int safe(int i)
{
return i >= 0 ? i : -(i);
}
int f();
int main(void)
{
int x(5);
int ans;
ans = unsafe(x++);
cout << ans << endl;
ans = unsafe(++x);
cout << ans << endl;
ans = safe(x++);
cout << ans << endl;
ans = safe(++x);
cout << ans << endl;
std::cin.get();
return 0;
}
EDIT:
Great. Got the typo out of the way. Not that I'm bitter that I don't find such errors or anything.
The output is now 6, 9, 9, 11.
However, even with pre-incrementation, shouldn't the first value result in 7?
If the macro is being called twice, then doesn't it go like this:
unsafe(x) // pre-incrementation doesn't modify the value when called.
unsafe(++x) // for all intents and purposes, the incrementation happens before the second call, so the ++x. This is for the first ans = unsafe(x++) if it's being called twice.
By the time we reach the second ans = unsafe(++x), shouldn't the x have been incremented twice? Once by the double call and once when the first double call was finished?
Instead of:
#define unsafe(i) \
( (i) >= 0 = (i) : -(i) )
I think you want:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
In response to your edit:
After the first call to unsafe(x++), x is 7, even though the ans is 6. This is because you have the statement:
ans = ( (x++) >= 0 ? (x++) : -(x++) )
ans is assigned to the middle x++ after the left-most x++ is evaluated. As a result, ans == 6 but x == 7. The difference with unsafe(++x) is that ans is assigned to ++x, meaning the result is ans == x == 9.