control statementslibvolume8.xyz/statistics/bsc/semester4/computer... · • note the difference...

34
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana

Upload: others

Post on 30-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

CONTROL STATEMENTS

Lakhbir Singh(Lect.IT)

S.R.S.G.P.C.G. Ludhiana

Page 2: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Flow of Control • Unless specified otherwise, the order of

statement execution through a function is

linear: one statement after another in

sequence

• Some programming statements allow us to:

– decide whether or not to execute a particular

statement

– execute a statement over and over, repetitively

• These decisions are based on boolean

expressions (or conditions) that evaluate to

Page 3: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Conditional Statements • A conditional statement lets us choose which statement

will be executed next

• Therefore they are sometimes called selection statements

• Conditional statements give us the power to make basic

decisions

• The C conditional statements are the:

– if statement

– if-else statement

– switch statement

Page 4: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Logic of an if statement

conditionconditionconditioncondition evaluatedevaluatedevaluatedevaluated

statementstatementstatementstatement

truetruetruetrue falsefalsefalsefalse

Page 5: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The if Statement • The if statement has the following syntax:

if ( condition ) statement;

if is a Cis a Cis a Cis a C reserved wordreserved wordreserved wordreserved word

The The The The condition must be amust be amust be amust be a boolean expression. It mustboolean expression. It mustboolean expression. It mustboolean expression. It must evaluate to either true or false.evaluate to either true or false.evaluate to either true or false.evaluate to either true or false.

If the If the If the If the condition is true, the is true, the is true, the is true, the statement is executed.is executed.is executed.is executed. If it is false, the If it is false, the If it is false, the If it is false, the statement is skipped.is skipped.is skipped.is skipped.

Page 6: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Logic of an if-else statement

conditionconditionconditioncondition evaluatedevaluatedevaluatedevaluated

statement1statement1statement1statement1

truetruetruetrue falsefalsefalsefalse

statement2statement2statement2statement2

Page 7: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The if-else Statement • An else clause can be added to an if

statement to make an if-else statement if ( condition ) statement1; else statement2;

• If the condition is true, statement1 is executed;

if the condition is false, statement2 is executed

• One or the other will be executed, but not both

Page 8: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Boolean Expressions

• A condition often uses one of C's equality operators or relational

operators, which all return boolean results:

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

• Note the difference between the equality operator (==) and the

assignment operator (=)

Page 9: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Boolean Expressions in C

• C does not have a boolean data type.

• Therefore, C compares the values of variables and expressions against 0 (zero) to determine if they are true or false.

• If the value is 0 then the result is implicitly assumed to be false.

• If the value is different from 0 then the result is implicitly assumed to be true.

• C++ and Java have boolean data types.

Page 10: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Block Statements

• Several statements can be grouped together

into a block statement delimited by braces

• A block statement can be used wherever a

statement is called for in the C syntax rules if (total > MAX) { printf ("Error!!\n"); errorCount++; }

Page 11: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Block Statements • In an if-else statement, the if portion,

or the else portion, or both, could be block

statements if (total > MAX) { printf("Error!!"); errorCount++; } else { printf ("Total: %d“, total); current = total*2; }

Page 12: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Nested if Statements

• The statement executed as a result of an if statement or

else clause could be another if statement

• These are called nested if statements

• An else clause is matched to the last unmatched if (no

matter what the indentation implies)

• Braces can be used to specify the if statement to which an

else clause belongs

Page 13: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement

• The switch statement provides another way to

decide which statement to execute next

• The switch statement evaluates an expression,

then attempts to match the result to one of

several possible cases

• Each case contains a value and a list of

statements

• The flow of control transfers to statement

associated with the first case value that © 2004 Pearson Addison-Wesley. All rights reserved

Page 14: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement

• Often a break statement is used as the last

statement in each case's statement list

• A break statement causes control to transfer

to the end of the switch statement

• If a break statement is not used, the flow of

control will continue into the next case

• Sometimes this may be appropriate, but often

we want to execute only the statements

associated with one case

Page 15: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement

switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: otherCount++; break; }

• An example of a switch statement:

Page 16: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement

• A switch statement can have an optional

default case

• The default case has no associated value and

simply uses the reserved word default

• If the default case is present, control will

transfer to it if no other case value matches

• If there is no default case, and no other value

matches, control falls through to the

statement after the switch

Page 17: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement

• The expression of a switch statement must

result in an integral type, meaning an integer

(byte, short, int,) or a char

• It cannot be a floating point value (float or

double)

• The implicit test condition in a switch

statement is equality

• You cannot perform relational checks with a

switch statement

Page 18: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The switch Statement • The general syntax of a switch statement

is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... }

switch andandandand case areareareare

reservedreservedreservedreserved wordswordswordswords

If If If If expression matches matches matches matches value2,,,, control jumpscontrol jumpscontrol jumpscontrol jumps to hereto hereto hereto here

Page 19: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Repetition in Programs

• In most software, the statements in the

program may need to repeat for many times.

– e.g., calculate the value of n!.

– If n = 10000, it’s not elegant to write the code as

1*2*3*…*10000.

• Loop is a control structure that repeats a group

of steps in a program.

– Loop body stands for the repeated statements.

• There are three C loop control statements:

–while, for, and do-while. 5-19

Page 20: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Flow Diagram of Loop Choice Process

Copyright ©2004 Pearson Addison-Wesley.

All rights reserved. 5-20

e.g., calculate the value of n!

e.g., read the content in a file

Page 21: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Comparison of Loop Choices (1/2)

Kind When to Use C Structure

Counting loop We know how many loop

repetitions will be needed

in advance.

while, for

Sentinel-

controlled loop

Input of a list of data ended

by a special value

while, for

Endfile-

controlled loop

Input of a list of data from

a data file

while, for

5-21

Page 22: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Comparison of Loop Choices (2/2)

Kind When to Use C Structure

Input validation

loop

Repeated interactive input

of a value until a desired

value is entered.

do-while

General

conditional

loop

Repeated processing of

data until a desired

condition is met.

while, for

5-22

Page 23: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The while Statement in C

• The syntax of while statement in C:

while (loop repetition condition)

statement

• Loop repetition condition is the condition

which controls the loop.

• The statement is repeated as long as the loop

repetition condition is true.

• A loop is called an infinite loop if the loop

repetition condition is always true.

5-23

Page 24: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

An Example of a while Loop

5-24

Statement

Loop repetition condition

Loop control variable is the variable whose value controls

loop repetition.

In this example, count_emp is the loop control variable.

Page 25: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Flowchart for a while Loop

5-25

Loop repetition condition

Statement

Page 26: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Compound Assignment Operators (1/2)

• The loop body usually consists of statements

of the form: variable = variable op expression.

– e.g., count_emp = count_emp + 1;

• C provides compound assignment operators

which enable a more concise notation for this

kind of statements.

– “variable op = expression” is the same to

“variable = variable op expression.”

Page 27: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Compound Assignment Operators (2/2)

Simple Assignment

Operators

Compound Assignment

Operators

count_emp = count_emp + 1;

count_emp += 1;

time = time -1; time -= 1;

product = product * item;

product *= item;

total = total / number;

total /= number;

n = n % (x+1); n %= x+1; 5-27

Page 28: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The for Statement in C • The syntax of for statement in C:

for (initialization expression;

loop repetition condition;

update expression)

statement

• The initialization expression set the initial value of the

loop control variable.

• The loop repetition condition test the value of the

loop control variable.

• The update expression update the loop control

variable. 5-28

Page 29: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

An Example of the for Loop

5-29

Loop repetition condition

Initialization Expression

Update Expression

count_emp is set to 0 initially.

count_emp should not exceed the value of number_emp.

count_emp is increased by one after each iteration.

Page 30: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Increment and Decrement Operators

• The statements of increment and decrement are

commonly used in the for loop.

• The increment (i.e., ++) or decrement (i.e., --)

operators are the frequently used operators

which take only one operand.

• The increment/decrement operators increase or

decrease the value of the single operand.

– e.g., for (int i = 0; i < 100; i++){ … }

– The variable i increase one after each iteration.

5-30

Page 31: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Comparison of Prefix and Postfix

Increments

Copyright ©2004 Pearson Addison-Wesley.

All rights reserved. 5-31

The value of the expression (that uses the ++/-- operators)

depends on the position of the operator.

The value

of j is

increased

The value

of j is not

increased

Page 32: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

Nested Loops

• Nested loops consist of an outer loop with one

or more inner loops.

• e.g.,

for (i=1;i<=100;i++){

for(j=1;j<=50;j++){

}

}

• The above loop will run for 100*50 iterations. 5-32

Inner loop

Outer loop

Page 33: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

The do-while Statement in C

• The syntax of do-while statement in C:

do statement

while (loop repetition condition);

• The statement is first executed.

• If the loop repetition condition is true, the

statement is repeated.

• Otherwise, the loop is exited.

5-33

Page 34: CONTROL STATEMENTSlibvolume8.xyz/statistics/bsc/semester4/computer... · • Note the difference between the equality operator (== ) and the assignment operator ( =) Boolean Expressions

An Example of the do-while Loop

/* Find even number input */

do{ printf(“Enter a value: ”);

scanf(“%d”, &num);

}while (num % 2 !=0)

5-34

This loop will repeat if the user

inputs odd number.