Thursday, 22 August 2013

Calculator using switch and fuctions in C

Calculator using switch and fuctions in C

This is our exercise today and our first time coding call functions in
class. These are the instructions given to us:
I have to make a C Program calculator with choices: 0 - exit, 1 - add, 2 -
subtract, 3 - multiply and 4 - divide.
Once the user inputs their choice, I ask for two numbers from them.
I need to use functions for each arithmetic operation.
When I'm done with calculating, it should go back to the menu.
The program only ends when the user chooses 0.
I'm not so sure if I've coded the functions properly and I'm wondering if
I'm right about exit();. But this is my program: Edit: I've edited it
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
int main(){
int num1, num2, choice;
printf("[0] Exit\v[1] Add\v[2] Subtract\v[3] Multiply\v[4] Divide");
scanf("%d", &choice);
switch(choice){
case 0:
exit();
break;
case 1:
printf("Enter 1st number:\n");
scanf("%d", &num1);
printf("Enter 2nd number:\n");
scanf("%d", &num2);
printf("%d", add(num1,num2));
break;
case 2:
printf("Enter 1st number:\n");
scanf("%d", &num1);
printf("Enter 2nd number:\n");
scanf("%d", &num2);
printf("%d ", sub(num1,num2));
break;
case 3:
printf("Enter 1st number:\n");
scanf("%d", &num1);
printf("Enter 2nd number:\n");
scanf("%d", &num2);
printf("%d", mul(num1,num2));
break;
case 4:
printf("Enter 1st number:\n");
scanf("%d", &num1);
printf("Enter 2nd number:\n");
scanf("%d", &num2);
printf("%d", div(num1,num2));
break;
default:
printf("That is not a valid choice.");
break;
}
//Addition
int add(int x,int y){
int z;
z = x + y;
return add;
}
//Subtraction
int sub(int a,int b){
int c;
c = a - b;
return sub;
}
//Multiplication
int mul(int d,int e){
int f;
f = d * e;
return mul;
}
//Division
int div(int g,int h){
int i;
i = g / h;
return div;
}
}
Is my whole code wrong? What should I do to improve it?

No comments:

Post a Comment