Friday, February 2, 2018

Coding using Keywords- part 2 (if, else)

Inside this blog I will include simple if else statements, and nested if else statements.

Before starting read this blog to have a general idea about keywords http://philippebalech.blogspot.com/2018/01/keywords-in-c.html and then consider this flowchart.



Picture definition. IF the condition inside the if (condition) is true the cursor will move to the body of the if. IF not the cursor will skip the body of the if and continue whatever comes after. Let's take some examples.


Simple if



  1. #include<iostream>  
  2. using namespace std;  
  3. void main(){  
  4.     int i=-5;  
  5.     if(i<0)  
  6.         cout<<"The number is negative.";  
  7.     cout<<"This will always be executed";  
  8. }  

In this example i is less than 5. So the condition inside the if is TRUE considering that i<0 so the body of if will be executed. The second statement will alway be executed whether the condition is true or false. The output will be as following:

The number is negative. This will always be executed

In this example there is not a "\n" after cout for this reason both sentences are next to each others.

Consider that i was initialized with 5 as value (i=5 instead of i=-5); this will not meet the condition so the block of if will be skipped and the output will be:

This will always be executed


Simple if-else


  1. #include<iostream>  
  2. using namespace std;  
  3. void main(){  
  4.     int i=1;  
  5.     if(i<0)  
  6.         cout<<"The number is negative.";  
  7.     else cout<<"The number is positive.";  
  8.     cout<<"This will always be executed";  
  9. }  


Since i is 1 now, the condition inside if is FALSE. That means that the body of if will be skipped and the cursor will directly move to the body of else. That means that the output will be:

The number is positive. This will always be executed

Nested if-else


  1. #include<iostream>  
  2. using namespace std;  
  3. void main(){  
  4.     int i=-5;  
  5.     if(i<=0)  
  6.     {  
  7.         if(i==0)cout<<"The number is zero.";  
  8.         else cout<<"The number is negative.";  
  9.     }  
  10.     else {  
  11.         if(i==1) cout<<"The number is 1";  
  12.         else cout<<"The number is positive and not equal one.";  
  13.     }  
  14. }  

Output:


The number is negative.

i is equal to -5 in the example; so the cursor will enter the body of if because it's less than 0. The condition of the next if, is to check if the number is 0; that isn't our case so it will skip this if and move to else and output the sentence. Once the cursor enters the first if (i<=0) it will definitely skip else and the program will end.

Hope this was helpful, if you have any question list them in comments. 

No comments:

Post a Comment