click on this link......

LinkGrand.com

Sunday, 31 March 2013

Decision making in C



Decision making in C

We have seen that a C program is group of statement which are normally executed
sequentially in order to appear .This happens when no options or no representation of certain calculations are necessary, but in practice we have number of  statements based on certain conditions or we have to repeat a group of statements until certain  specified conditions are made .This involves a kind of decision making to see whether a particular condition has occurred or not & these conditions direct  the computer to execute certain statement.
The C language has the decision making capability and following statement  supports decision making capability.
1 if statement
2 switch statement
3 conditional statement
4 go to statement

1 if statement

If statement is a powerful  decision making statement and is used to control the flow of execution of statements.

It is a  decision making statement & it has the following form

if( test expression / condition )

It allows the computer to evaluate the expression first and then depending on whether the
Value of expression is true or false , it transfers the control to a particular statement .
At this point it has two parts i.e. for true & for false.


          

Depending on the complexity of program the if statement are of following type

i. Simple if statement
the general form is

            if (test condition )
            {
                        statement block ;
            }
next statement;
statement block may have one or more than one statements .
if the test condition is true then statement block will be executed ; otherwise it is skipped & next statement is evaluated.
Eg.


main( )
{
            int a;
            printf ( "Enter value for a ");
            scant ( "%d", &a );
            if(a>100)
            {
                        printf ( "a is greater than 100" ) ;
            }
printf ( "HAVE  A GOOD DAY" ) ;
}

The if ….else statement
The if …else statement is an extention of the simple  if statement .
The general form of if - else  statement   is

if (test condition /expression)
{
            true block statement (s);
}
else
{
            false block statement (s);
}
next statement;

if the test expression is true then the true block statement s ,immediately following the if statement are executed ; otherwise the false block statement s are executed .
In either case ,either true block or false block will be executed ,not both .
In both the case ,the control is transferred subsequently to statement –x as shown below.




main( )
{
            int i;
            printf ( "Enter value of i ");
            scant ( "%d", &i ) ;
            if(i=5)
            {
                        printf ( "You entered 5" ) ;
            }
            else
            {
                        printf ( "You entered something other than 5" ) ;
            }
}

And here is the output of two runs of this program...

Enter value of i 200
You entered 5
Enter value of i 9999
You entered 5


Example :- In a company an employee is paid as under:
            If his basic salary is less than Rs. 1500, then HRA = 10% of basic
            salary and DA = 90% of basic. If his salary is either equal to or above
            Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the
            employee's salary is input through the keyboard write a program to
            find his gross salary.
main( )
{
            float bs, gs, da, hra;
            printf ( "Enter basic salary " ) ;
            scant ("%f",&bs);
            if (bs< 1500)
            {
                        hra=bs*10/100;
                        da=bs*90/100;
            }
            else
            {
                        hra = 500:
                        da=bs*98/100;
}
gs = bs+hra+da;
printf ( "gross salary = Rs. %f, gs);
}

Nesting of if..else statement
When a series of decisions are involved , we may have to use more than one if..else
Statement  in nested form as follows

The logic of execution is shown in the flowchart below
If the condition 1 is false , the statement 3 will be executed ; otherwise it continues to perform the second test .If the condition 2 is true ,the statement 1 will be evaluated ;
Otherwise the statement  2 will be evaluated & then the control is transferred to the statement x .

  if ( test condition )
{         
            if ( test condition )
            {
                        statement 1;
            }
            else
            {
                        statement 2;
            }
}
else
{
            statement 3 ;
}
statement x;


main()
{
            int ml , m2 , m3 , m4 , m5;
            printf ( "Enter marks in five subjects ") ;
            scant ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

            per = ( ml + m2 + m3 + m4 + m5 ) /5;

            if ( per >= 60 )
                        printf ( "First division ") ;
                        else
                        {
                        if ( per >= 50 )
                                    printf ( "Second division" ) ;
                                    else
                                    {
                                    if(per>=40)
                                                printf ( "Third division" ) ;
                                                else
                                                            printf ( "Fail" ) ;
}

Observe that the program uses nested if-elses. This leads to thre<
disadvantages:
(a)    As the number of conditions go on increasing the level o
indentation also goes on increasing. As a result the whol(
program creeps to the right.
(b)    Care needs to be exercised to match the corresponding ifs an(
ciscs.
(c)    Care needs to be exercised to match the corresponding pair o
braces.
The else if ladder
There is another way of putting ifs together when multipath  decision are involved .
A multipath decision is a chain of ifs in which the statement associated with each else is an it.
The general form is ;

if ( condition  1)
            statement 1;
else if ( condition )
                        statement  2;
                        else if (condition )
                                    statement 3;
                                    …………
                                    …………
                                    else if (condition n)
                                                statement –n ;
                                                else
                                                        default statement ;
            statement x ;

This construct is known as else if ladder .
The condition are evaluated from the top of the ladder , downwards  .As soon as atrue condition is found ,the statement associated with it is executed & control is transferred  to the statement x, skipping the rest of the ladder when all the n conditions become false , then the final else containing the default statement will be executed .
The flowchart shows the logic of execution of else it ladder statements.






Switch

It is also one kind of multi-way decision making structure .
So it is an option to nested if .
It is very easy to understand as compared to nested if  because when the conditions in the nested if statement increases its complexity also increases i.e. the structure becomes more & more complicated .
But with these advantages switch structure also have some limitations
In switch we can only test for fixed values of an expression .
But when we want to text the condition such as >= ,<=  etc .
There is no alternative to nested if in such situations you have to use nested if only the general form of switch is as follows:

switch(expression)
{         
             case value1:
                                    block of statements ;

case value2:
                                    block of statements ;

case value3:
                                    block of statements ;
                        .
                        .
                   .

case value n:
                                    block of statements ;

default :
                                    block of statements ;

}


In the above structure switch is a necessary keyword .
Expression can be any expression or a variable.
Case is the necessary keyword
value 1 will represent some fixed value of expression .
If the expression result in value 1  then , the block of statements in first case will be executed .
You  must provide colon ( :) after each case value .
Similarly value 2 ,value 3 …….value n are different possible values of the expression .
If no case value is matched ,
The expression the default part will be executed .
The default part is optional in switch .
One more advantage of is that in switch structure if we want to execute multiple statements after one case , there is no need of using curly brackets.

switch

#include<stdio.h>
main( )
I
char ch;
clrscr();
printf (" please enter your choice) ;
ch = touppcr(ch):
switch (ch)
{
case 'R':
            printf ("RED") ;
            break :
case 'w':
            printf (" white" ) ;
            break ;
case 'v':
            print (" violet ") ;
}
getch( );

}
The goto Statement

Avoid goto statements! They make a C programmer's life miserable.
There is seldom a legitimate reason for using goto, and its use is one
of the reasons that programs become unreliable, unreadable, and hard
to debug. And yet many programmers (especially those using
BASIC) find goto .
In a difficult programming situation it seems so easy to use a goto to
take the control where you want to. However, almost always, there
is a more elegant way of writing the same program using if, for, while
and switch. These constructs are far more logical and easy to under-
stand.
A goto statement can cause program control to end up almost
anywhere in the program, for reasons that are often hard to unravel.
Trust me, with good programming skills, goto can always be avoided.
This is the First and last time that we are going to use goto in this
book.
•For sake of completeness of the book, here is how the goto is used.
Consider the following program.

main( )
{
int goals;
printf ( "Enter the number of goals scored against India' ) ;
scant ( "%d", goats ) ;
           
if(goals<=5)
            goto sos :
           
      else
      {
                        printf ( 'About time soccer players learnt C\n" ) ;
                        printf ( 'and said goodbye! adieu! to soccer" ) ;
            exit( ) ; /* terminates program execution */
      };

sos:
            printf ( "To err is human!' ) ;
}
And here are two sample runs of the program...
Enter the number of goals scored against India 3
To err is human!
Enter the number of goals scored against India 7
About time soccer players learnt C
and said goodbye! adieu! to soccer





No comments:

Post a Comment