Place Your Query
-
C Programming
-
- Control flow-based C Programs
- Enjoy Conditional Programming in C using If...else and switch statement.
- Good, Now write a C program to display "Hello World" on the screen.
- Write a C program to display Your Name, Address and City in different lines.
- C program to find sum of n numbers
- Write a C program For Addition of two numbers using Function.
- Write a Program to Find Simple Interest and Compound Interest.
- Write a Program to Convert Celsius To Fahrenheit and Vice Versa.
- Write a Program to Find Area and Perimeter of Circle, Triangle, Rectangle and Square.
- Write a Program to Swap Two Numbers Using Temporary Variables and Without Using Temporary Variables
- Write a C Program to Design a Simple Menu Driven Calculator
- Simple Expression Based C Programs
-
- 7. Components of C language
- 1. Introduction to C Programming Language
- 10. Operator Precedence and Associativity
- 11. Comments in C Programming
- 14. Fundamental Control Structure Statements in C [Part-1]
- 15. Fundamental Control Structure Statements in C [Part-2]
- 16. Looping Statements [Fundamental Control Structure Statements in C. #Part-3]
- 17. Keyword break, continue, return and exit [Fundamental Control Structure Statements in C. #Part-4]
- 2. Computer Languages
- 3. Interpreters vs Compilers vs Assemblers in programming languages
- 4. C Program Structure
- 5. Compile and Execute C Program
- 6. Errors in C Program
- 8. C Datatypes
- 9. Operators in C
- Control flow-based C Programs
- Demystifying Bit Masking: Unlocking the Power of Bitwise Operators in C-Language with best Examples.
- 18. Fundamentals of C Functions
- Show Remaining Articles (3)Collapse Articles
-
-
Java
-
AI ML
-
FAQs
- A Program to find Tokens in C code?
- What are the Common Coding Mistakes.
- Easy Learning, Python QAs for Beginner’s to Pro Part-1
- Easy Learning, Python QAs for Beginner’s to Pro Part-2
- Easy Learning, Python Strings QAs for Beginner’s to Pro Part-1
- Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2
- Easy Learning, Python String Functions QAs for Beginner to Pro Part-3
-
Python Interview Questions
- Easy Learning, Python QAs for Beginner’s to Pro Part-1
- Easy Learning, Python QAs for Beginner’s to Pro Part-2
- Easy Learning, Python Strings QAs for Beginner’s to Pro Part-1
- Easy Learning, Python Strings QAs for Beginner’s to Pro Part-2
- Easy Learning, Python String Functions QAs for Beginner to Pro Part-3
Write a C Program to Design a Simple Menu Driven Calculator
Aim
To write a C-program to design a simple menu-driven calculator. A simple menu-driven calculator in C can perform basic arithmetic operations like addition, subtraction, multiplication, and division based on the user’s choice.
This program starts by asking the user to input an operator and two numbers. Then, it uses aswitch
statement to perform the operation based on the chosen operator. If the division is selected, it checks for division by zero to avoid runtime errors. The result is then printed to the console.
Remember to compile the program using a C compiler before running it to ensure it works as expected.
Procedure / Algorithm
Step-1: Start the program execution.
Step-2: Declare 2 variables a and b, ch, c.
Step-3: Get the choice as ‘+’ for addition, ‘-‘ for subtraction, ‘*’ for Multiplication, ‘/’ for Division and ‘%’ for Modulo.
Step-4: If ch=+, perform addition and print the results.
Step-5: If ch=-, perform subtraction and print the results.
Step-6: If ch=*, perform multiplication and print the results.
Step-7: If ch=/, perform division and print the results.
Step-8: If ch=%, perform modulo and print the results.
Step-9: If choice is not in them print “Enter correct choice”.
Step-10: Stop the program execution.
Program
// Program to Design a Simple Menu Driven Calculator
// author milind bhatt
#include<stdio.h>
int main()
{
int a,b,c;
char ch;
printf("\nEnter two values:\n");
scanf("%d%d",&a,&b);
printf("\nEnter the choice:\n1.Addition\n2.Subtraction");
printf("\n3.Multiplication\n4.Division\n5.Modulo\nchoice: ");
scanf("%c",&ch);
switch(ch)
{
case '+': printf("\nAddition of %d+%d is %d",a,b,a+b);
break;
case '-': printf("\nsubtraction of %d-%d is %d",a,b,a-b);
break;
case '*': printf("\nMultiplication of %d*%d is %d",a,b,a*b);
break;
case '/': if(b==0)
printf("\nDivision is not possible");
else
printf("\nDivision of %d/%d is %f", a,b,(float)a/b);
break;
case '%': printf("\n Moduls of %d%%d is %d",a,b,a%b);
break;
default: printf("\n Enter correct choice:");
break; // break with default is always optional
} // end switch
return 0;
}// end main
Output
Enter two values:
10
30
Enter the choice:
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulo
choice: 3
Multiplication of 10*30 is 300
--------------------------------
Process exited after 16.97 seconds with return value 0
Press any key to continue . . .
Result
Thus, the C-program had been written, executed successfully to design the menu driven calculator.
Conclusion
C program for the menu-driven calculator was written and executed without any issues. This means the program was able to compile correctly, and when run, it presented a menu to the user, accepted inputs, and performed the desired calculations based on the user’s choices.
If you’re looking to enhance the program further, consider adding more features like:
- Error handling for invalid inputs.
- A loop to allow multiple calculations without restarting the program.
- Functions to organize the code and make it more modular.
Recommended Reading
FAQs
< All Topics
- Main
- C Programming
- C Tutorial
- 15. Fundamental Control Structure Statements in C [Part-2]
15. Fundamental Control Structure Statements in C [Part-2]
Updated14 March 2024
ByMilind Bhatt
What we discussed in previous post?
We actually try to understand Control Structures in C Programming: Selection, Iteration, and Jump Statements and then we have explored the fundamental control structures as if() statement and if()…else statement. In support we have also shared some simple examples to have a proper feel of the concept.
Now in this post we will go deeper into these and will discuss about nested if()… else, if…else if ladder and switch statements
Table of Contents
- What we discussed in previous post?
- Example: Greatest Among Three Given Numbers
- Example: Check the grade of the student
- Example: Create calculator using SWITCH statement
- Example: Write a switch-based menu driven program in C with the following options-
3) Nested if-else statementas a control structure
A user can use if…else statements in-side any specific if or else condition in the program.
Syntax:The syntax of a nested if( )…else statement in C programming language is:
if( condition_1)
{ // statements for true part of condition
if(condition_2)
{ /* Statement(s) when cond_1 and cond_2 both are true. */}
else
{ /* statements for condition 1 as true and false for condition2 */}
}
else
{
if(condition_3)
{ /* Statement(s) when cond_1 and cond_2 both are true. */}
else
{ /* statements for condition 1 as true and false for condition2 */}
C supportsmaximum seven levels of nestedif conditions only. Means,six nested inner if()sand there corresponding else can be part ofouter if()condition and in a same waysix nested inner if()sand there corresponding else can be part ofouter elsecondition.
Example: Greatest Among Three Given Numbers
//WAP in C to find the greatest number among three numbers using nested if else.
#include
void main()
{
int a,b,c;
printf("\n Enter the numbers :-----> ");
scanf("%d%d%d", &a, &b, &c);
if (a>=b)
{
if(b>=c)
printf("\n %d is greatest in all",a);
else
if(a>=c)
printf("\n %d is greatest in all",a);
else
printf("\n %d is greatest in all",c);
}
else
if(b>=c)
printf("\n %d is greatest in all",b);
else
printf("\n %d is greatest in all",c);
}// end main
Output
4) if…else if…else statementas a control structure
Think a situation when we have to work with multiple if…else conditions and we apply multiple if…else blocks then each if…else block is treated as separate condition and each of these if…else block will be being checked by the compiler, also this raises a problem that we get both desired and undesired outputs.
To overcome this problem, C has introduced a construct calledif…else if…elseblock of statement where we have oneIf ()block, one or moreelse if() blocks and at last anelse blockof code.
i.e. multiple else if () conditions are stuffed between the if() and else block of statement.
Flowchart
Working: From the above flowchart, when condition1 if true, it will just move to the very next statement after the if…else if…else construct. When condition1 is false then it moves to check condition2 and so on. At last, when all the conditions are false control moves to else block of the construct.
Rules for multiple if … else condition sets.
- While using if…else if… else statements, there are few points to keep in mind −
- An if can have zero tomany else if’sand they mustcome before the else.
- Once an else if succeeds, none of the remaining else if’s or else’s will be tested.
- An if can have zero or oneelse’sand it must comeafter any else if’s.
Syntax:
if(Condition_ 1)
{
// Set of statements for condition 1 as true
}
else if(Condition_ 2)
{
// Set of statements for condition 2 as true
}
else if( Condition_3)
{
// Set of statements for condition as true
}
else
{
// Set of statements when all above conditions are false
}
Example: Check the grade of the student
// ckeck the grade of the student
// marks <=100 -----> approved limit
// marks >=85 A++
// marks >=75 A+
// marks >=65 B+
// marks >=55 B
// marks >=45 C
// marks <45 Fail.
#include
void main()
{
int marks;
printf("\n Enter your marks out of 100 : ");
scanf("%d", &marks);
if (marks>100)
printf("\n Marks are out of approved limit");
else if(marks>=85)
printf("\n your marks= %d and grade is A++", marks);
else if(marks>=75)
printf("\n your marks= %d and grade is A+", marks);
else if(marks>=65)
printf("\n your marks= %d and grade is B+", marks);
else if(marks>=55)
printf("\n your marks= %d and grade is B", marks);
else if(marks>=45)
printf("\n your marks= %d and grade is C", marks);
else
printf("\n Better Luck Next Time! marks=%d, grade FAIL", marks);
}
Output
5) switch statementas a control structure
The switch statement in C is an alternate to if-else-if ladder statement. we can define various statements in the multiple cases for the different values of a single variable.
Flowchart
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
} // end switch statement.
Rules for using switch statement:
- Theswitch expressionmustbe of aninteger or charactertype.
- Thecase valuemust be aninteger or character constant.
- Thecase valuecan beusedonly inside the switch statement.
- Thebreak statementin switch case isnot must.It is optional.
If there is nobreakstatement found in thecase, all the cases present just after the matchedcasewill be executed . This is known asfall throughstate of C switch statement.
Let’s try to understand the valid and invalid cases by the examples. We are assuming that there are following variables.
int x,y,z;
char a,b;
float f;
Valid Switch | Invalid Switch | Valid Case | Invalid Case |
---|---|---|---|
switch(x) | switch(f) | case 3; | case 2.5; |
switch(x>y) | switch(x+2.5) | case ‘a’; | case x; |
switch(a+b-2) | case 1+2; | case x+2; | |
switch(func(x,y)) | case ‘x’>’y’; | case 1,2,3; |
Example:Create calculator using SWITCH statement
// program to create calculator using SWITCH statement
#include
void main()
{int a,b;
char ch;
printf("\n Enter two numbers \n");
scanf("%d",&a);
scanf("%d",&b);
printf("\n Press:\n + for addition\n - for substraction\n * for multiplication\n / for divide operation");
scanf("%c",&ch);
switch(ch)
{ case '+':
printf("\n addition of %d and %d = %d",a,b, a+b);
break;
case '-':
printf("\n substraction of %d and %d = %d",a,b,a-b);
break;
case '*':
printf("\n multiplication of %d and %d = %d",a,b, a*b);
break;
case '/':
printf("\n divide of %d and %d = %d",a,b, a/b);
break;
default:
printf("\n wrong operator");
}// end switch
}// end main
Example:Write a switch-based menu driven program in C with the following options-
A. Find greater between two numbers.
B. Check, number is even or odd.
C. Calculate area of Circle.
D. Exit
/*
Write a menu driven program in C with the following options-
A. Find greater between two numbers.
B. Check, number is even or odd.
C. Calulate area of Circle.
D. Exit
*/
#include<stdio.h>
void main()
{
char ch;
int n1, n2, max;
int num, res;
float r, area;
printf("\n Mention your choice\n Press A for greater between two numbers");
printf("\n Press B to Check, number is even or odd");
printf("\n Press C to Calulate area of Circle.");
printf("\n Press D to take Exit : \t -> ");
scanf("%c",&ch);
switch(ch)
{
case 'A':
case 'a':
// Find greater between two numbers.
printf("\n Enter Two Numbers : "); scanf("%d%d", &<em>n1em>,&<em>n2em>);
max = n1>=n2? n1 : n2;
printf("\n greater number is %d", max);
break;
case 'B':
case 'b':
// Check, number is even or odd.
printf("\n Enter The Number : "); scanf("%d", &<em>numem>);
res = ((num%2) == 0 )? printf("\n num =%d is EVEN", num): printf("\n num =%d is ODD", num);
break;
case 'C':
case 'c':
//Calulate area of Circle.
printf("\n Enter The radius : "); scanf("%f", &<em>rem>);
area= 3.14*r*r;
printf("\n area covered by radius %f is %f", r, area);
break;
case 'D':
case 'd':
// take Exit
printf("\n Bye !!");
break;
default:
printf("\n INVALID INPUT");
}// end switch
}// end main
Recommended Readings
gnu.org Official Documents on Conditional Syntax
The ANSI C Programming Language by Brian W. Kernighan, Dennis M. Ritchie
C Programming A Modern Approach 2nd Edition (C 89, C 99) King By King, K. N.