Sunday, February 14, 2016

Decision Making Control Structures

Decision making control structures check one or multiple conditions and executes a group of statements if the conditions are evaluated to true and executes another group of statements if the conditions are evaluated to false. C has following decision making control structures:
  1. 'if' statement
  2. 'if ... else' statement
  3. Nested 'if ... else' statement or 'if ... else if... else' statement
  4. 'switch' statements

'if' Statement

Simplest control structure available in C is 'if' statement. The 'if' control structure consists of'if' statement followed by an expression enclosed in parentheses. The 'if' statement evaluates the expression and if it evaluates to true, it will result in execution of immediate expression/statement following. Syntax of 'if' statement is given below.
  1. if(expression)
  2. statement
The statement 'statement' will be executed if the 'expression' is evaluated to true. If the'expression' is evaluated to false, 'statement' will not be executed.
The above syntax allows only execution of the immediately following statement. What if you want to execute more than one statement based on the evaluation of condition? In that case the set of statements that you want to execute needs to be enclosed in curly braces as given below.
  1. if(expression)
  2. {
  3. statement1
  4. statement2
  5. ..
  6. ..
  7. statementN
  8. }
It is good practice to enclose the statements you want to execute in braces even if there is only a single statement to be executed. This clears the confusion of which statements are executed if the expression of an 'if' statement is satisfied.
An important thing to remember while using 'if' statement is that every expression always return either true or false (0 is considered as false and others are considered as true), even assignment statement inside the conditional expression will not throw any compilation error. Sometimes programmers may mistakenly write if (a = 10) instead of if (a == 10). In this case, first the value '10' will be assigned to variable 'a' and then 'a' is tested to see if it's zero (false) or non-zero(true). So the 'if' statement block will always be executed no matter what the value of 'a' and to worsen things this will not generate any compilation error. To avoid this problem, it's better to use if (0 == a) instead of if(a == 0), as forgetting one '=' in the first case will produce compilation error

Example of 'if' Statement

The program given below checks if a number is positive number.
  1. #include <stdio.h>
  2. int main(void) {
  3. int i = 10;
  4. if (i > 0) {
  5. printf("%d is positive number", i);
  6. }
  7. return 0;
  8. }
  9.  
  10. Output:
  11. 10 is positive number

No comments: