Knowee
Questions
Features
Study Tools

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:

  1. The variable i is initialized with the value 2.
  2. The if statement checks if i-- is equal to 1. The i-- operation decreases the value of i by 1 after the comparison. So, at the time of comparison, i is still 2, hence the condition i-- == 1 is false.
  3. Since the condition in the if statement is false, the program goes to the else statement and executes cout << i + 1;. At this point, i is 1 (because of the i-- operation in the if statement), so i + 1 equals 2.
  4. Therefore, the output of the program is 2.

This problem has been solved

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.