C Decision Making - Branching

Sample Program (switch-case)

#include ' stdio.h ' //include stdio.h header file to your program 
main ( ) //start of the main function 
{ 
int num1, num2, result; //Declaration of variables 
char operator; 
printf (“Enter two numbers”); //Message to the user to enter 2 numbers 
scanf (“%dy.d”, & num1, &num2); //read and store the numbers. 
printf (“Enter an operator”); //message to the user to enter an //operator 
Scanf (“%c”, & operator); //read and store the operator 
Switch (operator) //start of the switch construct 
{ 
case ‘+’ :
result = num1 + num2; //If the operator entered is ‘t’ 
break; //add the 2 numbers & store it in result 
case ‘-‘: 
result = num1 – num2; //If the operator entered is ‘-‘ 
break;// subtract the numbers & store 
case ‘*’: 
result = num1 * num2;// it i n the result 
break; //If the operator enter is (*) 
case ‘/’:
if (num2! = 0)// multiply the 2 numbers & show it in //result 
result = num1 / num2; // if the operator is ‘/’ then 
else // check for division by zero if the second number is zero 
{
printf (“warning : division by zero \ n”); 
result = 0: 
} 
break; 
default:
printf (“\n unknown operator”) //If the operator entered 
result = 0// is none of the 4 operators print message 
break;// set the result value to zero. 
Printf (“%d”, result); //print the result. 
}

Make Comments..!!


Oops!! No posts from user.

Download Android App