0

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..

3
Contributors
2
Replies
17
Views
2 Years
Discussion Span
Last Post by mridul.ahuja
1

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).

Edited by rubberman

1

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++

Edited by mridul.ahuja

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.