Tuesday, September 24, 2013

DECISION MAKING BRANCHING AND LOOPING

DECISION  MAKING  BRANCHING  AND LOOPING

Decision making are needed when, the program encounters the situation to choose a particular statement among many statements.

In C, decision making can be performed with following  statements.

if...else statement
switch statement

if statement

syntax

if (test expression){
       statement/s to be executed if test expression is true;
}

If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed.
But, if the test expression is false, the execution of the statements for the body of if statements are skipped.


Example of if statement

Write a C program to print the number entered by user only if the number entered is positive .

#include <stdio.h>
      int main(){
      int num;
      printf("Enter a number to check.\n");
      scanf("%d",&num);
      if(num<0)       /* checking whether number is greater than 0 or not. */
            printf("Number=%d\n",num);  
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
return 0;
}

Output
Enter a number to check.
2
Number=2


if...else statement

The if...else statement is used, if the programmer wants to execute some code,
If the expression  is true  or false one statement is going  to be executed.

Syntax

if (test expression)
     statements to be executed if test expression is true;
else
     statements to be executed if test expression is false;


Example

Write a C program to check whether a number entered by user is even or odd
#include <stdio.h>
int main(){
      int num;
      printf("Enter a number you want to check.\n");
      scanf("%d",&num);
      if((num%2)==0)          //checking whether remainder is 0 or not.
           printf("%d is even.",num);
      else
           printf("%d is odd.",num);
      return 0;
}

Output 1
Enter a number you want to check.
25
25 is odd.

Output 2
Enter a number you want to check.
2
2 is even.

Nested if...else statement (if...elseif....else Statement)

The if...else statement can be used in nested form when a serious decision are involved.

Syntax

if (test expression)
     statements to be executed if test expression is true;
else
     if(test expression 1)
          statements to be executed if test expressions 1 is true;
       else
          if (test expression 2)
           .
           .
           .
            else
              statements to be executed if all test expressions are false;

How nested if...else works?
If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed.
The ANSI standard specifies that 15 levels of nesting may be continued.

Example

Write a C program to relate two integers entered by user using = or > or < sign.

#include <stdio.h>
int main(){
     int number1, number2;
     printf("Enter two integers to check".\n);
     scanf("%d %d",&number1,&number2);
     if(number1==number2) //checking whether two integers are equal.
          printf("Result: %d=%d",number1,number2);
     else
        if(number1>number2) //checking whether number 1is greater than number 2.
          printf("Result: %d>%d",number1,number2);
        else
          printf("Result: %d>%d",number 2,number1);
return 0;
}

Output 1
Enter two integers to check.
5
3
Result: 5>3

Output 2
Enter two integers to check.
-4
-4
Result: -4=-4


Loops in C

Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied,
 i.e.,loops are used in performing repetitive work in programming.

Suppose you want to execute some code/s 1000 times. You can perform it by writing that code/s only one time and repeat the execution 1000 times using loop.

There are 3 types of loops in C

for loop
while loop
do...while loop

for Loop

Syntax

for(initial expression; test expression; increment/decrement expression)
{
       code/s to be executed;
}

Working  of loops in c

The initial expression is initialized only once at the beginning of the for loop.

Then, the test expression is checked by the program. If the test expression is false, for loop is terminated. But, if test expression is true then, the codes are executed and update expression is updated. Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same process repeats until test expression is false.

example

Write a program to find the sum of first n natural numbers .

#include <stdio.h>
int main(){
    int n, count, sum=0;
    printf("Enter the value of n.\n");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  //for loop terminates if count>n
    {
        sum+=count;    /* this statement is equivalent to sum=sum+count */
    }
    printf("Sum=%d",sum);
    return 0;
}

Output
Enter the value of n.
19
Sum=190

In this program, the user is asked to enter the value of n. Suppose you entered 19 then,  count is inatialized to 1 at first. Then, the
 test expression in the for loop,i.e.,  (count<= n) becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the expression ++count is executed and again the test expression is checked, which becomes true. Again, the body of for loop is executed which makes sum to 3 and this process continues. When count is 20, the test condition becomes false and the for loop is terminated.

while and do...while Loop


while loop


Syntax of while loop

while (test expression)
{
     statements to be executed.
}

In the beginning of while loop, test expression is checked. If it is true, codes inside the body of while loop,i.e, code/s inside parentheses are executed and again the test expression is checked and process continues until the test expression becomes false.

Example
Write a C program to find the factorial of a number.

#include <stdio.h>
     int main(){
     int number,factorial;
     printf("Enter a number.\n");
     scanf("%d",&number);
     factorial=1;
     while (number>0){      /* while loop continues util test condition number>0 is true */
           factorial=factorial*number;
           --number;
}
printf("Factorial=%d",factorial);
return 0;
}

Output
Enter a number.
5
Factorial=120


do...while loop

In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.

Syntax

do {
   some code/s;
}
while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside body of do are executed again and the process continues until test expression becomes false(zero).

Notice, there is semicolon in the end of while (); in do...while loop.


Example

Write a C program to add all the numbers entered by a user until user enters 10.

/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
   int sum=0,num;
   do             /* Codes inside the body of do...while loops are at least executed once. */
   {                                  
        printf("Enter a number\n");
        scanf("%d",&num);
        sum+=num;    
   }
   while(num!=10);
   printf("sum=%d",sum);
return 0;
}

Output
Enter a number
3
Enter a number
-2
Enter a number
10
sum=1

BREAK  AND  CONTINUE

 To interrupt the normal flow of control of a program. Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable to skip some statements inside loop and terminate the loop immediately without checking the test expression. In such cases, break and continue statements are used.

break Statement

In C programming, break is used in terminating the loop immediately after it is encountered.

 The break statement is used with conditional if statement

Syntax

break;

The break statement can be used in terminating all three loops for, while and do...while loops.

Example

Write a C program to find average of maximum of n positive numbers entered by user. But, if the input is negative, display the average(excluding the average of negative input) and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative number*/

# include <stdio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs\n");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       break;                     //for loop breaks if num<0.0
       sum=sum+num;
}
  average=sum/(i-1);      
  printf("Average=%.2f",average);
  return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07

In this program, when the user inputs number less than zero, the loop is terminated using break statement with executing the statement below it i.e., without executing sum=sum+num.


continue Statement

It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.

Syntax

continue;
Just like break, continue is also used with conditional if statement.

Example of continue statement
Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.

//program to demonstrate the working of continue statement in C programming
# include <stdio.h>
int main(){
    int i,num,product;
    for(i=1,product=1;i<=4;++i){
        printf("Enter num%d:",i);
        scanf("%d",&num);
        if(num==0)
            continue;  / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */
        product*=num;
}
    printf("product=%d",product);
return 0;
}

Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

Switch case statement


Decision making are needed when, the program encounters the situation to choose a particular statement among many statements.
If a programmar has to choose one among many alternatives if...else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch...case statement.

Syntax

switch (eeexpression)
{
case constant1:
   codes to be executed if expression equals to constant1;
   break;
case constant2:
   codes to be executed if expression equals to constant3;
   break;
   .
   .
   .
default:
   codes to be executed if expression doesn't match to any cases;
}

In switch...case, expression is either an integer or a character. If the value of switch expression matches any of the constant in case, the relevant codes are executed and control moves out of the switch...case statement. If the expression doesn't matches any of the constant in case, then the default statement is executed.

Example

Write a program that asks user n arithmetic operator('+','-','*' or '/') and two operands and perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */
/* Program to create a simple calculator for addition, subtraction, multiplication and division */
# include <stdio.h>
int main(){
     char operator;
     float num1,num2;
     printf("Enter operator +, - , * or / :\n");
     operator=getche();
     printf("\nEnter two operands:\n");
     scanf("%f%f",&num1,&num2);
     switch(operator)                            
     {
     case '+':
              printf("num1+num2=%.2f",num1+num2);
              break;
     case '-':
              printf("num1-num2=%.2f",num1-num2);
              break;
     case '*':
              printf("num1*num2=%.2f",num1*num2);
              break;
     case '/':
              printf("num2/num1=%.2f",num1/num2);
              break;
     default:                                
/* if operator is other than +, -, * or /, error message is shown */
              printf(Error! operator is not correct");
              break;
     }
     return 0;
}

Output
Enter operator +, -, * or / :
/
Enter two operators:
34
3
num2/num1=11.33

Notice break statement at the end of each case, which cause switch...case statement to exit. If break statement are not used, all statements below that case statement are also executed.

goto Statement

In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.

Syntax

goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of the program will jump to the label: and executes the code/s after it.


Example of goto statement

/* C program to demonstrate the working of goto statement.*/
# include <stdio.h>
int main(){
   float num,average,sum;
   int i,n;
   printf("Maximum no. of inputs: ");
   scanf("%d",&n);
   for(i=1;i<=n;++i){
       printf("Enter n%d: ",i);
       scanf("%f",&num);
       if(num<0.0)
       goto jump;             /* control of the program jumps to label jump */
       sum=sum+num;
}
jump:
  average=sum/(i-1);      
  printf("Average: %.2f",average);
  return 0;
}
Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.

Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement makes the logic of the program complex and tangled. In modern programming, goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue statements. In fact, any program in C programming can be perfectly written without the use of goto statement. All programmer should try to avoid goto statement as possible as they can

No comments:

Post a Comment