C105(2): Conditional

In part 1 we saw that if statement controls the execution of the program. It is used to control whether to execute a statement or not to execute. We tell the compiler what to do if the condition is correct, but we did not tell what to do if the condition is false. By default if the condition is false it simply skips the statement and continue at the next line after the if statement.

to provide action to take id the condition is false, we use else keyword

if(condition){
  //code block 1
}else{
  //code block 2
}

this is known as if...else statement

if(6 < 3){
  printf("6 is more than 3");
}else{
  printf("6 is less than 3 is false");
}

now when the program run, the condition is evaluated to FALSE. so it outputs

6 is less than 3 is false

Following is another type of if statement, if else if statement. This statement can have more than 1 condition checks and its own action.

if(condition_1){
  //code block 1
}else if(condition_2){
  //code block 2
}else{
  //code block 3
}
//next statement

if condition one true it executes code block 1, after execute the code block it skips the rest of the statement and goes to next statement. if condition 1 is false code block 1 is skipped and condition_2 is checked. if the condition 2 is true than it executes the block 2 and skips else part of the statement. id the condition is false than code block 3 will be executed.

if(a > 7){
  printf("value a is more than 7");
}else if(a > 4){
  printf("value a is more than 4");
}else{
  printf("value a is less than 4");
}

assuming the value a is in the range of 8 or more the output will be:

value a is more than 7

and if the value of a is between 5 to 7

value a is more than 4

finally any other value less or equal to 4, the else portion of the id statement is entered.
value a is less than 4

we can add as many else if in this statement, but it must end with an else.

another common selection statement is switch.

switch(variable){
  case value1:
    //codes
    break;
  case value2:
    //codes
    break:
  default:
    //codes
}


for example

switch(varA){
  case 1:
    printf("the value of var A is 1");
    break;
  case 2:
    printf("the value of var A is 2");
    break;
  case 1:
    printf("var A is undefined");
}

Assuming varA is 1 the output is

the value of var A is 1

Assuming varA is 2 the output is

the value of var A is 2

Assuming varA is other than 1 or 2 the output is

var A is undefined

Assuming varA is 1 and the break keywords are missing in the switch statement. The output will be:

the value of var A is 1
the value of var A is 2
var A is undefined

the break keyword causes program execution exits the switch statement immediately after it has executed all the statements for that particular case.

Loop is one of the conditional statement and we will discuss in part 3.

Click here to go back to part 1.




Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net