user2756669
user2756669

Reputation: 123

Conditions in a FOR loop

This is my code.

#include <iostream>
using namespace std;
void numberChecker();
bool numberCalc(int num, bool guess);
int main(){
    numberChecker();
    return 0;
}

void numberChecker(){
    int num;
    int guess = false;
    cout << "Hello, welcome to my program!\nGuess: ";
    for ( ; numberCalc(num, guess==false); ){
        cin >> num;
    }
}

bool numberCalc(int num, bool guess){
    return guess = 1;
}

If I have a for loop, and the condition is looking at a method such as numberCalc(num, guess), how can I, in the for loop, check the guess argument and ignore num?

And also, let's say I want to compare for example num == 0 and guess == true, how do I lay that out?

for ( ; numberCalc(num == 1, guess==false) ;

Upvotes: 0

Views: 139

Answers (3)

phuclv
phuclv

Reputation: 41804

In your function

bool numberCalc(int num, bool guess){
return guess = 1;
}

the last return guess = 1; line assigns 1 to guess, and return the result of that assignment, so it always returns 1. You should change it to

return guess == 1;

Upvotes: 0

deeiip
deeiip

Reputation: 3379

If you are interested only about guess you can always write:

bool numberCalc(int num, bool guess){
return guess == someValue; // value with you want to campair
}

If you write the function like :

bool numberCalc(int num, bool guess){
    return guess = someValue; // value with you want to campair
    }

It'll return the result of the assignment operation ( which is likely to be true always) If you want to check both condition you can write like:

bool numberCalc(int num, bool guess){
return guess==someValue1 || num==someValue2 ;
}

Upvotes: 0

Saksham
Saksham

Reputation: 9380

If you want to terminate yor loop when num=0 and guess=false, you may define numbercalc as:

bool numberCalc(int num, bool guess){
return guess || num ;
}

Or better use a while loop

while(guess||num) { }

Upvotes: 1

Related Questions