What is the output of the following snippet? #include <iostream> using namespace std; int main(){ int i = 2; if (i--==1) cout << i; else cout << i + 1; return 0; } i + 1 2 3 1
Question
What is the output of the following snippet?
#include <iostream> using namespace std; int main(){ int i = 2; if (i--==1) cout << i; else cout << i + 1; return 0; }
i + 1
2
3
1
🧐 Not the exact question you are looking for?Go ask a question
Solution
The output of the given C++ code snippet will be 1.
Here's the step by step explanation:
- The variable
iis initialized with the value 2. - The
ifstatement checks ifi--is equal to 1. Thei--operation decreases the value ofiby 1 after the comparison. So, at the time of comparison,iis still 2, hence the conditioni-- == 1is false. - Since the condition in the
ifstatement is false, the program goes to theelsestatement and executescout << i + 1;. At this point,iis 1 (because of thei--operation in theifstatement), soi + 1equals 2. - Therefore, the output of the program is 2.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following PHP code?
1/4
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.