Saturday, February 3, 2018

Coding using keywords- part 3 (switch, break, default)

I will include a C program about the switch, default, break keywords then the explanation below it.


  1. #include<iostream>  
  2. using namespace std;  
  3. int main(){  
  4.     cout<<"In this program you have to enter three numbers";  
  5.     while(1)  
  6.     {  
  7.         cout<<"\nPress 1 to enter them"  
  8.             <<"\nPress 2 to find the maximum "  
  9.             <<"\nPress 3 to find the minimum"  
  10.             <<"\nPress 4 to find the product of them"  
  11.             <<"\nPress 5 to exit";  
  12.         int choice,n1,n2,n3,product;  
  13.         cout<<"\nEnter your choice :";cin>>choice;  
  14.         switch(choice)  
  15.         {  
  16.             case 1: cout<<"\nEnter the first number :";cin>>n1;  
  17.                     cout<<"\nEnter the second number :";cin>>n2;  
  18.                     cout<<"\nEnter the third number :";cin>>n3;  
  19.                     break;  
  20.             case 2: int max;  
  21.                     if(n2>=n1 && n2>=n3)max=n2;  
  22.                     if(n3>=n1 && n3>=n2)max=n3;  
  23.                     if(n1>=n2 && n1>=n3)max=n1;  
  24.                     cout<<"\nThe maximum number is :"<<max;  
  25.                     break;  
  26.             case 3: int min;  
  27.                     if(n2<=n1 && n2<=n3)min=n2;  
  28.                     if(n1<=n2 && n1<=n3)min=n1;  
  29.                     if(n3<=n2 && n3<=n1)min=n3;  
  30.                     cout<<"\nThe minimum is :"<<min;  
  31.                     break;  
  32.             case 4: int product;product=n1*n2*n3;  
  33.                     cout<<"\nThe product result is :"<<product;  
  34.                     break;  
  35.             case 5:exit(1);break;  
  36.             default: cout<<"You didn't choose any correct number";break;  
  37.         }  
  38.     }  
  39.     return 0;  
  40. }  

Explanation


switch is a keyword used to enter one if the case one time. For this example, when you press 1 the user enters 3 numbers and break the switch the the options will show. If the user press 2 the compiler will find the maximum between the three numbers and the switch will break. If he presses 3 the compiler will find the minimum and break the switch, if 4 find the product of three numbers and 5 to exit the while(1) this means the program.

default: this will be executed when the user don't press any number matching the case.

Note: You can check all the keywords anytime you like :
https://philippebalech.blogspot.com/2018/01/keywords-in-c.html 

No comments:

Post a Comment