Introduction:
The switch statement allows a program to perform different arithmetic operations based on the user's choice. It provides an easy and organized way to execute one operation from multiple available options.
Definition:
An Arithmetic Operation Program accepts two numbers and a choice from the user. Depending on the selected option, the program performs addition, subtraction, multiplication, or division using the switch statement.
Syntax:
switch(choice)
{
case 1:
// Addition
break;
case 2:
// Subtraction
break;
case 3:
// Multiplication
break;
case 4:
// Division
break;
default:
// Invalid Choice
}
Explanation:
switch statement executes the selected operation.default case displays an error message.
Explanation: This program accepts two numbers and performs addition, subtraction, multiplication, or division according to the user's choice using the switch statement.
#include <stdio.h> #include <conio.h> main() { int a,b,c; clrscr(); printf("Enter the value of a : "); scanf("%d",&a); printf("\nEnter the value of b : "); scanf("%d",&b); printf("\nEnter your choice"); printf("\n1. Addition"); printf("\n2. Subtraction"); printf("\n3. Multiplication"); printf("\n4. Division"); printf("\n\nEnter Your Choice : "); scanf("%d",&c); switch(c) { case 1: c = a + b; printf("\nAnswer is %d",c); break; case 2: c = a - b; printf("\nAnswer is %d",c); break; case 3: c = a * b; printf("\nAnswer is %d",c); break; case 4: if(b!=0) { c = a / b; printf("\nAnswer is %d",c); } else { printf("\nDivision by zero is not possible."); } break; default: printf("\nInvalid Choice"); } getch(); }
Output:
switch statement to calculate the area of different shapes based on the user's choice.switch statement to perform different calculations depending on the option selected by the user.#include <stdio.h> #include <conio.h> main() { int choice; float side,length,width,radius,area; clrscr(); printf("1. Area of Square"); printf("\n2. Area of Rectangle"); printf("\n3. Area of Circle"); printf("\n\nEnter Your Choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter Side : "); scanf("%f",&side); area = side * side; printf("\nArea = %.2f",area); break; case 2: printf("\nEnter Length : "); scanf("%f",&length); printf("Enter Width : "); scanf("%f",&width); area = length * width; printf("\nArea = %.2f",area); break; case 3: printf("\nEnter Radius : "); scanf("%f",&radius); area = 3.14 * radius * radius; printf("\nArea = %.2f",area); break; default: printf("\nInvalid Choice"); } getch(); }
switch statement performs the corresponding area calculation. If an invalid option is entered, the program displays "Invalid Choice".