+ 4
Boolean and while loop
Hey guys, I’m wondering what is wrong with this code. It’s actually executed but still some error. Tell me please I’m stuck #include <iostream> using namespace std; int main() { int i = 0; bool condition = true; while (!(i>5)) { cout << "You got the lesson" << endl; i++; } return 0; } https://code.sololearn.com/c0WcCb10gGVQ/?ref=app
12 ответов
+ 6
Jayakrishna🇮🇳 Ipang
Thanks guys for really explaning me. It works!! Yey!!
I love you guys from far.
And thanks for you guys in this communtity for really care and help xxx
+ 4
The !( i > 5 ) expression was evaluated by using logical NOT and greater than operator which means the final result is logical, and can be treated as boolean-like data.
Not sure what you mean by "use bool with while" I think you need to elaborate further on that part ...
+ 3
First of all, sorry if my English not good. Im try to use Boolean and While loop together and its seem mess up. How can i make above code work both (boolean and while lopp) together
+ 3
You can use condition as while condition :
bool condition = true;
while( condition) {
cout << "You got the lesson" << endl;
/*
inside loop, as a stop condition, change condition value to false by if block
*/
i++;
if( i > 5 )
condition = false;
}
+ 3
Are they should be like this?
#include <iostream>
using namespace std;
int main() {
int i = 0;
bool condition = true;
while (condition = !(i>5)) {
cout << "You win girl" << endl;
i++;
}
return 0;
}
+ 2
bool condition = true; //unused variable
+ 2
Perhaps try removing the line bool condition = true
I ran your code and realised that the issue was that you didn't use this variable in the program which shot the error that the Boolean variable condition is assigned a value, but it isn't used. Try removing it and the program should run fine :)
+ 2
Simply assign the actual condition required ( !( i > 5 ) ) as value for variable <condition>
while ( condition = !( i > 5 ) )
{
// loop body code here ...
}
This way, <condition> value will be updated along with the change of value in variable <i> because we assign the evaluation result of !( i > 5 ) to variable <condition> just before loop decides (based on the evaluation result) whether to continue or to cease repetition.
+ 1
Actually, im trying to use bool with while. So how can i use it without error
+ 1
It's depend on compiler modern compiler gives warnings if you have decleared any variables and u not using anywhere in program to avoid this you can remove it or print it
+ 1
👍🏼👍🏼👍🏼
0
You have declared and incialized variable bool but you haven't used it in for loop. The loop executes anyway because variable i=0, and prints statement while i<5. So it prints statement 5 times. But if you use bool in loop than you can affect on this.