Saturday, February 14, 2026

C++ Tricky Predict Output Questions (Logical Errors)

C++ Decision-making Statements

Tricky Predict Output Questions (Logical Errors)

(ifif-elsenested ifelse if ladderswitch, etc.)

Answers are given at the bottom of this page.

Q1 - Assignment Instead of Comparison
#include <iostream>
using namespace std;

int main() {
    int x = 5;
    if (x = 0)
        cout << "True";
    else
        cout << "False";
    return 0;
}

Q2 - Missing Braces
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    if (x > 5)
        cout << "A";
        cout << "B";
    return 0;
}

Q3 - Dangling Else Problem
#include <iostream>
using namespace std;

int main() {
    int x = 5;
    if (x > 2)
        if (x < 4)
            cout << "A";
        else
            cout << "B";
    return 0;
}

Q4 - Switch Without Break
#include <iostream>
using namespace std;

int main() {
    int x = 2;
    switch(x) {
        case 1: cout << "One";
        case 2: cout << "Two";
        case 3: cout << "Three";
        default: cout << "Default";
    }
    return 0;
}

Q5 - Logical AND Mistake
#include <iostream>
using namespace std;

int main() {
    int x = 5;
    if (x > 2 && x < 5)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Q6 - Semicolon After If
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    if (x > 5);
        cout << "Hello";
    return 0;
}

Q7 - Character Comparison
#include <iostream>
using namespace std;

int main() {
    char ch = 'A';
    if (ch == 65)
        cout << "Match";
    else
        cout << "No Match";
    return 0;
}

Q8 - Multiple If Instead of Else If
#include <iostream>
using namespace std;

int main() {
    int marks = 85;

    if (marks > 50)
        cout << "Pass ";
    if (marks > 75)
        cout << "Distinction";

    return 0;
}

Q9 - Not Equal Confusion
#include <iostream>
using namespace std;

int main() {
    int x = 5;
    if (!x == 5)
        cout << "True";
    else
        cout << "False";
    return 0;
}

Q10 - Boolean Value Check
#include <iostream>
using namespace std;

int main() {
    bool flag = 2;
    if (flag)
        cout << "ON";
    else
        cout << "OFF";
    return 0;
}

* * * * *

Answer Key (Tricky Outputs)

Que.| Output    | Explanation
Q1   False      x = 0 assigns 0 → condition false
Q2   AB         Only first cout inside if; second always executes
Q3   B          else belongs to inner if
Q4   TwoThreeDefault        No break, so fall-through occurs
Q5   No         x < 5 is false (5 is not less than 5)
Q6   Hello      Semicolon ends if; cout always executes
Q7   Match      ASCII value of 'A' is 65
Q8   Pass Distinction   Both if conditions are true
Q9   False      !x → !5 → false (0); 0 == 5 false
Q10  ON         Any non-zero value converts to true


Back to C++ Home Page >

* * * * *

No comments:

Post a Comment