ICP - Lecture 7 and 8

Post on 07-Nov-2014

360 views 0 download

Tags:

description

 

Transcript of ICP - Lecture 7 and 8

CSC 103

Lecture 7 & 8

Introduction to Computers and Programming

The Decision Control

2

We need to alter our actions in the face of changing circumstances

If the weather is fine then I will go for a walk

If the highway is busy I would take a diversion

If the pitch takes spin, we would win the match

If I am feeling well then I will watch a movie

You can notice that all these decisions depend on some condition being met

C language too must be able to perform different sets of actions depending on the circumstances

3

Decision control instruction can be implemented in C using:

(a) The if statement

(b)The if-else statement

(c)The conditional operators

The if Statement

4

C uses the keyword if to implement the decision control instruction

Syntax is :

if ( expression )

execute this statement ;

The keyword if tells the compiler that what follows is a decision control instruction

The expression following the keyword if is always enclosed within a pair of parentheses

if the expression is true then the statement is executed otherwise not

5

In general, the condition is expressed using C’s ‘Relational Operator’

Following are different relational operators:

!= is inequality or not equals to operator

== is used for comparison of two quantities

= is an assignment operator

Example

6

/* Demonstration of if statement */

main( )

{

int num ;

printf ( "Enter a number less than 10 " ) ;

scanf ( "%d", &num ) ;

if ( num <= 10 )

printf ( “The number is less than 10!" ) ;

}

7

The general form of if statement is: if (expression) statement; Here the expression can be any valid expression including a

relational expression We can use arithmetic expressions in the if statement e.g. if (3+5-2) printf(“ This works”); if (a=10) printf(“ Even this works”); if(-5) printf (“And even this works”);

if-else Statement

8

Statements are executed when if condition is true

We also want to execute statements when condition is false

if ( condition )

do this ;

else

do this ;

if block

else block

Some if-else rules in C

9

else block should come immediately after if block

When if and else blocks contain only one statement

then we can drop pair of braces i.e. { }

Example:

Take two values from user and determine which one is smaller and which one is greater.

Solution:

First we draw a flow chart

Making decisions in C

Sometimes your programs need to make logical choices.

Example:

IF score is higher than 50

THEN grade is "pass"

ELSE grade is "fail"

10

Making decisions in C

Example:

IF score is higher than 50

THEN grade is PASS

ELSE grade is FAIL

In C, this corresponds to one statement with 3 parts:

if (score > 50) {

grade = PASS;

}

else {

grade = FAIL;

}

11

Making decisions in C

Part 1 : the condition

An expression that evaluates to TRUE or FALSE

if (score > 50)

{

grade = PASS;

}

else

{

grade = FAIL;

}

12

Making decisions in C

Part 2 : the TRUE part A block of statements that are executed if the condition

has evaluated to TRUE

if (score > 50)

{

grade = PASS;

}

else

{

grade = FAIL;

}

True part

13

Making decisions in C

Part 3 : the FALSE part A block of statements that are executed if the condition

has evaluated to FALSE

if (score > 50)

{

grade = PASS;

}

else

{

grade = FAIL;

}

if the condition

evaluates to FALSE,

the true part is skipped.

False part

14

Making decisions in C

If the true part (or false part) consists of only one statement, then the curly braces may be omitted.

Example: these two statements are equivalent:

if (score > 50)

{

grade = PASS;

}

else

{

grade = FAIL;

}

if (score > 50)

grade = PASS;

else

grade = FAIL;

15

Making decisions in C

Sometimes there are more than two parts. In those cases you may use cascading (a.k.a. nested) if/else statements:

if (score > 90)

lettergrade = 'A';

else if (score > 75)

lettergrade = 'B';

else if (score > 60)

lettergrade = 'C';

else if (score > 50)

lettergrade = 'D';

else

lettergrade = 'F';

16

Making decisions in C

if(condition)

statement;

if (condition) {

statements;

statements; …

}

if (condition) {

statements;

statements;…

}

else {

statements;

statements;...

}

3 forms of if statements;

(note indenting)

Note condition is

always in parentheses,

All TRUE parts and

all FALSE parts are

a single statement

or a single block

of statements

{} 17

Some Valid if Statements in C

18

if ( 3 + 2 % 5 )

printf ( "This works" ) ;

if ( a = 10 )

printf ( "Even this works" ) ;

if ( -5 )

printf ( "Surprisingly even this works" ) ;

“Condition is false only if expression evaluates to 0”

Multiple Statements within if (Flowchart)

19

Multiple Statements within if (C Language)

20

/* Calculation of bonus */

main( )

{

int bonus, cy, yoj, yr_of_ser ;

printf ( "Enter current year and year of joining " ) ;

scanf ( "%d %d", &cy, &yoj ) ;

yr_of_ser = cy - yoj ;

if ( yr_of_ser > 3 )

{

bonus = 2500 ;

printf ( "Bonus = Rs. %d", bonus ) ;

}

}

21

#include<stdio.h>

#include<conio.h>

main()

{

int a,b;

printf("Enter 1st Number: ");

scanf("%d", &a);

printf("Enter 2nd Number: ");

scanf("%d", &b);

if( a > b )

printf("%d is greater than %d", a, b);

else

printf("%d is greater than %d", b, a);

getch();

}

Some tests

22

Test

No. Output Remarks

01 Enter 1st Number: 15 Enter 2nd Number: 25 25 is greater than 15

2nd number is greater than 1st number

02 Enter 1st Number: 35 Enter 2nd Number: 20 35 is greater than 20

1st number is greater than 2nd number

03 Enter 1st Number: 300 Enter 2nd Number: 300 300 is greater than 300

Both numbers are equal…..Logical Error!

nested if-else

23

if ( condition )

do this ;

else

{

if ( condition )

do this ;

else

do this ;

}

“Modify our flow chart to solve logical error”

24

#include<stdio.h>

#include<conio.h>

main()

{

int a,b;

printf("Enter 1st Number: ");

scanf("%d", &a);

printf("Enter 2nd Number: ");

scanf("%d", &b);

if( a > b )

printf("%d is greater than %d", a, b);

else {

if( a == b )

printf("%d is equal to %d", a, b);

else

printf("%d is greater than %d", b, a);

}

getch();

}

else if Statement

25

Every else is associated with its previous if

The last else goes to work only if all the conditions fail

In else if the last else is optional

The else if clause is nothing different, it’s just a way of rearranging the else with the if that follows it

e.g.

Use of Logical Operators

26

C allows usage of three logical operators

&&, ||, !

These are to be read as AND, OR, NOT respectively

&& and || are composed of double symbols

Don’t use the single symbols & , |

These single symbols also have meaning. These are bitwise operators

The && and || allow two or more conditions to be combined in an if statement

27

Write a program to calculate the division obtained by a student. The marks obtained by the student in 5 different subjects are input through the keyboard

There are two ways to solve this problem

28

/* Method – I */

main( )

{

int m1, m2, m3, m4, m5, per ;

printf ( "Enter marks in five subjects " ) ;

scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

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

if ( per >= 60 )

printf ( "First division \n") ;

else

{

if ( per >= 50 )

printf ( "Second division\n" ) ;

else

{

if ( per >= 40 )

printf ( "Third division\n" ) ;

else

printf ( "Fail\n" ) ;

}

}

}

29

This program uses nested if-else

Three disadvantages of this method

As the number of conditions go on increasing the level of indentation also goes on increasing. As a result the whole program creeps to the right.

Care needs to be exercised to match the corresponding ifs and elses.

Care needs to be exercised to match the corresponding pair of braces.

All these three problems can be eliminated by usage of ‘Logical operators’

30

/* Method – II */

main( )

{

int m1, m2, m3, m4, m5, per ;

printf ( "Enter marks in five subjects " ) ;

scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

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

if ( per >= 60 )

printf ( "First division\n" ) ;

if ( ( per >= 50 ) && ( per < 60 ) )

printf ( "Second division\n" ) ;

if ( ( per >= 40 ) && ( per < 50 ) )

printf ( "Third division\n" ) ;

if ( per < 40 )

printf ( "Fail\n" ) ;

}

31

In the second if statement, the && operator is used to combine two conditions

‘Second division’ gets printed if both conditions are true

Two advantages of this method

The matching of the ifs with their corresponding elses gets avoided

In spite of using several conditions, the program doesn’t expand to the right

Solution Using else if

32

/* Use of else if */

main( )

{

int m1, m2, m3, m4, m5, per ;

printf ( "Enter marks in five subjects " ) ;

scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

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

if ( per >= 60 )

printf ( "First division\n" ) ;

else if ( per >= 50 )

printf ( "Second division\n" ) ;

else if ( per >= 40 )

printf ( "Third division\n" ) ;

else

printf ( "fail\n" ) ;

}

Problem!

33

Find smallest and greatest number among three input numbers?

The ! (NOT) Operator

34

The third logical operator is ! (NOT operator)

This operator reverse the result of an expression

If the result of an expression is TRUE, the ! operator will make it FALSE and vice versa

e.g.

!(y<10) it means that “not y less than 10”

if y is less than 10, the expression will be FALSE

the same condition can be written as (y>=10)

The NOT operator is often used to reverse the logical value of a single variable

if (!flag) is same as if(flag==0)

Hierarchy of Operators Revisited

35

Since we have added the logical operators, so it’s time to review the priorities of these operators

The higher the position of an operator in the table, the higher is its priority

Summary of Logical Operators

36

Following figure summarizes the working of logical operators

X 1

Logical Operators (Exercise)

37

A company insures its drivers in the following cases:

If the driver is married.

If the driver is unmarried, male & above 30 years of age.

If the driver is unmarried, female & above 25 years of age.

In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not.

38

// One way to solve the problem main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c", &age, &sex, &ms ) ; if ( ms == 'M' ) printf ( "Driver is insured" ) ; else { if ( sex == 'M' ) { if ( age > 30 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } else { if ( age > 25 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } } }

Solution by using Logical Operators

39

main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c“, &age, &sex, &ms ) ; if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) || ( ms == 'U' && sex == 'F' && age > 25 ) ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; }

The Conditional Operators

40

The conditional operators are ? and : Sometimes called Ternary Operators since they take three

arguments The general form is: expression 1 ? expression 2 : expression 3

It means that if expression 1 is TRUE then the value returned will be expression 2 otherwise the value returned will be expression 3

e.g. int x,y; scanf (“%d”, &x); y=(x>5 ? 3 : 4)

This statement will store 3 in y if x is greater than 5 otherwise it will store 4 in y

41

Another example

int x,y;

scanf("%d", &x);

y = (x >= 10 && x <= 50 ? 1 : 0);

Here if x>=10 && x<=50 evaluates to TRUE then y=1 otherwise y=0

The following points may be noted about conditional operators

42

It’s not necessary that the conditional operators should be used only in arithmetic statements int i ; scanf ( "%d", &i ) ; i == 1 ? printf ("You have entered 1" ) : printf ( "Entered value is other than 1" ) ;

The conditional operators can be nested as shown below:

int big, a, b, c ;

big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;

43

Check out the following conditional expression: a > b ? g = a : g = b ;

This will give you an error ‘Lvalue Required’. To remove the error just enclose the statement in : part within a pair of parenthesis

a > b ? g = a : ( g = b ) ;

In absence of parentheses the compiler believes that b is being assigned to the result of the expression to the left of second =.

The limitation of the conditional operators is that after the ? or after the : only one C statement can occur

What is the Output?

44

#include<stdio.h>

#include<conio.h>

main()

{

int a, b, g;

a=10;b=5;

a > b ? g = a : (g = b) ;

g == 10 ? printf ( "true" ) : printf ( "false" );

getch();

}

Some Rules

45

The default scope of the if statement is only the next statement. So, to execute more than one statement they must be written

in a pair of braces.

An if block need not always be associated with an else block. However, an else block is always associated with an if

statement.

&& and || are binary operators, whereas, ! is a unary operator

In C every test expression is evaluated in terms of zero and non-zero values. A zero value is considered to be false and a non-zero value is

considered to be true.

Assignment statements used with conditional operators must be enclosed within a pair of parenthesis.

Output of program!

46

main( )

{

int a = 300, b, c ;

if ( a >= 400 )

b = 300 ;

c = 200 ;

printf ( "\n%d %d", b, c ) ;

}

main( )

{

int x = 10, y = 20 ;

if ( x == y ) ;

printf ( "\n%d %d", x, y ) ;

}

47

main( )

{

int i = 4, j = -1, k = 0, y, z ;

y = i + 5 && j + 1 || k + 2 ;

z = i + 5 || j + 1 && k + 2 ;

printf ( "\ny = %d z = %d", y, z ) ;

}