Good Afternoon,

I want to convert this if-else statement to a switch statement.
The if-statement is:

int x;
cout<<"GIve me an int and I tell you whether is even of odd ";
cin>>x;
if (x%2==0)
cout<<x<<" is even."<<endl;
else
cout<<x<<" is odd."<<endl;

Dani AI

Generated

’s idea — use the number’s parity as the switch selector — is the right direction. Two practical issues explain the behavior seen in this thread: formatted input will fail if a nonnumeric character is given (leaving the stream in a failed state), and the C++ remainder operator can produce a negative result for negative dividends, so x % 2 is not always 0 or 1. Handle both to make the switch reliable.

A compact, robust pattern: read a full line, parse it to an integer with std::stoi (so malformed input is caught), compute the remainder and normalize it to a nonnegative value, then switch on that remainder.

#include <iostream>
#include <string>

std::string line;
if (std::getline(std::cin, line)) {
    try {
        int x = std::stoi(line);
        int r = x % 2;
        if (r < 0) r = -r;  // make remainder nonnegative
        switch (r) {
            case 0: std::cout << x << " is even\n"; break;
            case 1: std::cout << x << " is odd\n"; break;
        }
    } catch (const std::exception&) {
        std::cerr << "invalid integer input\n";
    }
}

Notes and references: using a character literal like 'A' in a case compares the integer code of that character (not parity). Check stream extraction failure or prefer string parsing to validate input. See the switch statement rules and the remainder behavior for details. The std::stoi helper is documented at . This addresses the input/negative-remainder pitfalls that affected ’s run.

Recommended Answers

All 4 Replies

Where I 'm having problems is dealing with x%2==0.
So far I have this:

int x;
     cout<<"Give me an int and I tell you whether is even of odd ";
     cin>>x;

     switch (x)
     {       
        case 'A':
            x = %2;
            cout<<x<<" is even."<<endl;
        break;
        default:
             cout<<x<<" is odd."<<endl;
     }

try this

switch(x%2)
{
   case 0:  // even
   default:  // odd
 }

Ancient Dragon,

I try your advise, but the program execute the default case with every number

It was because of the character,
thank you very much for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.