0

If +1 to Variable

Given the following code: int number = 50; Which code will display "yes" and add one to the number variable if the value stored in the number variable is greater than or equal to 50? 1. if ( number > 50) { cout << "yes" << endl; number = number + 1; } 2. if ( number >= 50) cout << "yes" << endl; number = number + 1; 3. if ( number >= 50) { cout << "yes" << endl; number = number + 1; } 4. if ( number <= 50) { cout << "yes" << endl; number = number + 1; } Please give me the correct option when explaining. 2, 3, and 4 all give me a yes and a 51.

20th Aug 2017, 8:31 PM
gorgamin
gorgamin - avatar
2 Respostas
+ 7
3 is correct. 1 checks greater than only and 4 checks less than or equal. So both are incorrect. Although 2 checks greater than and equal, since the increment statement is outside the if statement it'll always increment the number even if the condition is false.
20th Aug 2017, 8:42 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 2
#3
20th Aug 2017, 8:38 PM
Sébastien Auriault
Sébastien Auriault - avatar