Hey all im a beginner in c++.
Ive written this programme and ive tried to make a calculator using switch statement but its not working like it should.I would be very thankful if u point out whats wrong with it.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float x,y;
int choice;
cout<<"Enter 1,2,3,4 for +,-,x,/ respectively"<<endl;
cin>>choice;
cout<<"Enter the numbers"<<endl;
cin>>x>>y;
switch(choice)
case1 : 
cout<<x<<" + "<<y<<" = "<<x+y;
cout<<endl;
case2 : 
cout<<x<<" - "<<y<<" = "<<x-y;
cout<<endl;
case3 : 
cout<<x<<" x "<<y<<" = "<<x*y;
cout<<endl;
case4 :
if (y==0)
cout<<"division not possible"<<endl;
else
cout<<x<<" / "<<y<<" = "<<x/y;
cout<<endl;

getch();
}

Output is

Enter 1,2,3,4 for +,-,x,/ respectively
1
Enter the numbers
25
20

25 - 20 = 5
25 x 20 = 500
25 / 20 = 1.25

so the problem is that when i enter 1 it is supposed to add 20 and 25 but its not doing that.where is the problem?

Recommended Answers

All 6 Replies

* There should be a space between the keyword case and the value

case 1

* Break statement should be there in each case block

ok..thanks for the reply

when i do like what u said it gives the error "case out of switch"
what should i do now?

Then you did it wrong. But you didn't bother to show us what you did, so we can't be more specific.

And u is not an English word. Please don't use leet speek on the forums.

@op you are just having syntax issues. For your case to make a proper switch statement, you need to add the braces. Here is an example:

#include <iostream>
using namespace std;

int main()
{

  int test = 1;

  switch(test)
 {  
   case 0 : cout << "Option 0\n"; break;
   case 1: cout << "Option 1\n"; break;
 }

 return 0;
}

Notice the keyword "break". That tells the compiler that if it reaches that case, then evaluate that case and then break out of the switch statement. If you do not break out of the switch statement, then the next subsequent case statement will be evaluated.

@firstperson: thanks..my programme is working fine now.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float x,y;
int choice;
cout<<"Enter 1,2,3,4 for +,-,x,/ respectively"<<endl;
cin>>choice;
cout<<"Enter the numbers"<<endl;
cin>>x>>y;
switch(choice)
{
case 1:
cout<<x<<" + "<<y<<" = "<<x+y;
cout<<endl;
break;
case 2:
cout<<x<<" - "<<y<<" = "<<x-y;
cout<<endl;
break;
case 3:
cout<<x<<" x "<<y<<" = "<<x*y;
cout<<endl;
break;
case 4:
if (y==0)
cout<<"division not possible"<<endl;
else
cout<<x<<" / "<<y<<" = "<<x/y;
cout<<endl;
break;
}
getch();
}

my mistake was that i didn't use braces before and after i used the cases i.e. in line 4 and line 33.

thanks for the help guys.

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.