Create a program that will ask for a two numbers and use the selected operators.

How can i create this program without using switch statement? need some help..

Recommended Answers

All 2 Replies

You can use a series of if/else branches, or you can create a set of functions for each operator and create a 2d array or 2d vector of operators and the associated function. In the latter method, you look up the operator, and call the associated function with the provided numbers. Using a 2d array will work for both C and C++ as will branching (if/else statements).

Input for character can be taken using

char oper;
cin >> oper; // operation to perform

Comparing operator to char entered

if (oper == '+')
  <add numbers>
else if (oper == '-')
  <subtract numbers>
 .
 .
 .
end if

Basically

switch(ch)
{
  case 1 : <action1>
  case 2 : <action2>
     .
     .
}

becomes

if (ch == 1)
  <action1>
else if (ch == 2)
  <action2>
  .
  .
end if

in if-else

For more info, you can check using if-else in c++

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.