• No results found

conditionalstatement6-9-11.ppt

N/A
N/A
Protected

Academic year: 2020

Share "conditionalstatement6-9-11.ppt"

Copied!
56
0
0

Loading.... (view fulltext now)

Full text

(1)

Flow of Control

True and False in C

Conditional Execution

Iteration

(2)

True and False in C

False

is represented by any

zero

value

.

– The int expression having the value 0.

– The floating expression having the value 0.0. – The null character ‘\0’.

– The NULL pointer (for pointer see chap. 8).

True

is represented by any

nonzero

value

.

A logical expression, such as a<b, is either

true or false.

(3)

Examples

int

i=1, j=2, k=3

;

double

x=5.5, y=7.7, z=0.0

;

i

<

j-k

i<(j-k)

0

-i+5*j

>=

k+1 ((-i)+(5*j))>=(k+1)

1

x-y

<=

j-k-1

(x-y)<=((j-k)-1)

1

x+k+7

<

y/k ((x+k)+7)<(y/k)

0

i

!=

j

1

!!

5

!(!5)

1

(4)

Selection

if

(5)

if statement

Conditional Execution:

if (Boolean expression) statement; else statement;

Where a statement may consist of a single statement, a code block, or empty statement.

(6)

if – logic: if (Boolean Expression) statement_1;

If-else-logic: if (Boolean Expression){ compound_1

} else{

compound_2 }

• Conditional execution allows you write

No Semi-colon

Yes-For a

(7)

Example

#include <stdio.h>

WHY?

int main ( )

{

double salary, payrate;

int hours, union;

(8)

printf (“Enter 1 if a union member, 0 if not”);

scanf (“%d%lf%d”, &hours, &payrate, &union);

if (hours > 40 && union = = 1)

salary = (40 * payrate) + ((1.5 * payrate) * (hours - 40));

else

salary = payrate * hours;

(9)

Nested ifs

Nested: One statement coded within another statement.

Nested ifs: An nested if is an if that is the

target of another if or else.

Why Nested ifs?

Needed to handle tasks

where we have 3 or More

options that are mutually exclusive.

(10)

The if-else-if ladder

Linear nested If

General form:

OLD STYLE

if (expression) statement; else

if (expression) statement;      else

if (expression) statement; .

(11)

• The conditions are evaluated from the top

downward.

As soon as a true condition is found, the

statement associated with it is executed and the rest of the ladder is bypassed.

If none of the conditions are true, the final else

is executed. That is, if all other conditional tests

fail, the last else statement is performed.

(12)

E.g.

You are a salesperson for the Widget

Manufacturing Co. You will earn a salary

bonus according to the

following rules

:

Sales > = $50,000

earn $5,000

Sales > = $100,000 earn $15,000

Sales > = $150,000

earn $30,000

(13)

double sales, bonus;

printf (“please enter total sales”); scanf (“%lf”, &sales);

if (sales < 50000)

bonus = 0;

else if (sales < 100000)

bonus = 5000;

else if (sales < 150000)

bonus = 15000;

(14)

In a nested if, an else always refers to the nearest if

that is within the same block as the else and that is not already associated with an else.

if(i) {

if(j) dosomething1();

if(k) dosomething2(); /* this if */

else dosomething3(); /* goes with this else */ }

(15)

Conditional Expression

• The expressions must simply evaluate to

either a

true or false

(zero or nonzero)

value.

(16)

x = 10;

y =

x>9 ? 100 : 200;

x = 10;

if

(x>9)

y = 100;

else

y = 200;

The ?: Alternative

(17)

#include <stdio.h> int f1(int n);

int f2(void);

int main(void) {

int t;

printf("Enter a number: "); scanf("%d", &t);

t ? f1(t) + f2() : printf("zero entered."); printf("\n");

(18)

/* Divide the first number by the second. */ #include <stdio.h>

int main(void) {

int a, b;

printf("Enter two numbers: "); scanf(''%d%d", &a, &b);

if(b)

printf("%d\n", a/b);

else printf("Cannot divide by zero.\n");

return 0;

(19)

switch statement

switch

is a

multiple-branch selection

statement, which successively tests the

value of an expression against a list of

integer or character constants

(floating

point expression, for example, are not

allowed).

• When a match is found, the statements

(20)

General Form

switch (expression) { case constant1:

    statement sequence     break;

case constant2:

    statement sequence     break;

. .

default

(21)

Execution

• The value of the expression is tested against the constants specified in the case statements in a

top-down order..

• When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch

statement is reached.

• When break is encountered in a switch, program execution "jumps" to the line of code following the switch statement.

(22)

• The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression.

No two case constants in the same switch can

have identical values. Of course, a switch

statement enclosed by an outer switch may have

case constants that are in common.

• If character constants are used in the switch

(23)

• The switch statement is often used to process keyboard commands, such as menu selection. The following function will when called: display the options, allow the user to make a selection, and then

evoke the appropriate function to perform the task selected.

void menu(void) {

char ch;

printf("1. Check Spelling\n");

printf(''2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n");

printf("Strike Any Other Key to Skip\n"); printf(" Enter your choice: ");

(24)

24

switch(ch) {

case '1':

check_spelling (); break;

case '2':

correct_errors (); break;

case '3':

display_errors (); break;

default :

(25)

int flag, k; /* Assume k is initialized */ flag = -1;

switch(k) {

case 1: /* These cases have common */ case 2: /* statement sequences. */

case 3:

flag = 0; break; case 4:

flag = 1; case 5:

error(flag); break;

default: •The break inside

the switch is optional.

•If the break is omitted,

execution will continue on into the next case until either a break or the end of the

(26)

Nested Switch

• You can have a

switch

as a part of the

statement sequence of an outer switch.

• Even if the

case

constants of the inner and

the outer

switch

contain common values,

(27)

switch(x) {

case 1:

switch

(y) {

case 0:

printf(''Divide by zero error.\n");

break;

case 1:

process(x, y);

break;

}

(28)

Iteration

• Iteration statements (also called

loops

)

allow a set of instructions to be

repeatedly executed until a certain

condition is reached.

(29)

for loop

for (initialization; testing; increment)

Loop Body;

• The initialization is an assignment statement

that is used to set the loop control variable.

• The testing is a relational expression that determines when the loop exits.

(30)

Execution

• The

for

loop

continues to execute

as long

as the condition is

true.

• Once the condition becomes false, program

execution resumes on the statement

(31)

#include <stdio.h>

int main(void) {

int x;

for(x=1; x <= 100; x++)

printf("%d ", x);

return 0; }

for(x=100; x != 65; x -= 5)

{

(32)

The Elements of the For-loop

• The initialization, testing and

incrementation can be any valid C

expression.

for (

x=0

; Ajax>Manchester;

Ajax=Q*7/i)

• Common use as a

counting loop

.

(33)

Pieces of the loop definition need not be

there.

• The

i

ncrementation

of the loop control

variable can occur

outside the

for

statement.

for(x=0; x != 123; ) scanf("%d", &x);

for( x=1 ; x < 10; ) {

(34)

The Infinite Loop

• Since none of the three expressions that

form the

for

loop are required, you can

make an

endless loop

by leaving the

conditional expression empty.

for( ; ; ) printf("This loop will run forever.\n");

for( ; ; ) {

ch = getchar(); /* get a character */ if(ch == 'A') break; /* exit the loop */

(35)

For Loops With No Bodies

• A loop body may be

empty.

• This fact is used to simplify the coding of

certain algorithms and to create time delay

loops.

Does what

?

(36)

Declaring Variables within a For

Loop

• A variable so declared has its

scope

limited

to the block of code controlled by

that statement.

/* i is local to for loop; j is known outside loop.*/ int j;

(37)

While Loop

General form:

while(condition) 

statement;

Execution:

– Check the test condition at the top of the loop. – The loop iterates while the condition is true.

(38)

Example

char wait_for_char(void)

{

char ch;

ch = '\0'; /* initialize ch */

while(ch !

= 'A') ch = getchar();

(39)

Example 2 void func1()

{int process1(void);

int process2(void); int process3(void);

int working; working = 1; while (working) {

working = process1(); if (working)

working = process2(); if (working)

(40)

For loop Vs While Loop

A

-(Assignment),

T

-(testing),

I

-(Increment)

for

(A; T; I)

{

Body;

}

A;

While (T)

{

(41)

NESTED LOOPS

Nested 1 loop syntax coded inside another

Loop syntax.

Why?

- Single -Loop? Have a statement or statements that you

want to repeat. A

repetitive task that you must solve.

Why?

- Nested-Loops? You have a single -
(42)

General Format:

while (boolean expression){

while (boolean expression) {

}

}

(43)

/* Find triples of integers that add up to n. */ #include <stdio.h>

#define N 7

main()

{ int cnt = 0, j , k , m;

for(j = 0; j <= N; ++j)

for( k = 0; k <= N; ++k)

for( m = 0: m <= N; ++m)

if ( j + k + m == N) { ++cnt;

printf(“%d%d%d”, j , k , m); }

(44)

How many times will “if” be executed

?

512 timesj range 0

7

k range 0

7

m range 0

7

(45)

What will the values of j, k, and m be in sequence

J K M

0 0 0

0 0 1

0 0 2

0 0 7

0 1 0

0 1 1

0 1 2

(46)

0

2

0

0

2

1

0

2

7

Cont...

(47)

do-while Loop

General form:

do {

statement

;

} while(

condition

);

Execution:

– Always executes at least once.

– Iterates until condition becomes false.

(48)

•The most common use of the

do-while

loop is in a

menu selection

function.

void menu(void)

{

char ch;

printf("1. Check Spelling\n");

(49)

do {

ch = getchar(); /* read the selection from the keyboard */

switch(ch) { case '1':

check_spelling(); break;

case '2':

correct_errors(); break;

case '3':

display_errors(); break;

(50)

Jump

break

continue

(51)

break Statement

Two uses:

You can use it to

terminate

a case in the switch

statement

.

You can also use it to force immediate termination of a loop, bypassing the normal

#include <stdio.h>

int main (void) {

int t;

for(t=0; t < 100; t++) { printf(''%d ", t);

if(t == 10) break; }

(52)

•A

break

causes an exit from only the

innermost loop

.

for

(t=0; t < 100; ++t) {

count = 1;

for(;;)

{

printf(''%d ", count);

count++;

if(count == 10)

break

;

}

}

(53)

Breaking out of loops

Sometimes loops need to be cut short:

– You can break out of any loop with break ;

statement.

– A break will cause the loop to be aborted immediately.

– The next statement executed is the statement following the loop.

• Compare this with

return

:

(54)

Continue Statement

• General form

continue;

break

forces termination of the loop.

(55)

continue

can expedite the exit from a loop

by

forcing the conditional test to be

performed sooner.

– For the for loop, continue causes the increment and then the conditional test portions of the loop to execute.

(56)

void code(void)

{

char done, ch;

done = 0;

while(!done)

{

ch = getchar();

if(ch == ‘S') {

done = 1;

continue

;

}

/* test the condition now */

putchar

(ch+1);

This function codes a message by shifting all characters you type

one letter higher. For example, an A

becomes a B. The

References

Related documents

I NDIANA C ODE § 31-19-9-8 are written in the disjunctive and each provides independent grounds for dispensing with parental consent. Because we have found that Father’s failure

The aim of this study was to extract new or known compounds from South African Laurencia species that might have been omitted by other researchers and then test these compounds for

only because the State, pursuant to statutory authority, applied to the trial court for the enforcement of the State’s subpoena duces tecum under a criminal cause number after

conclude that the trial court did not abuse its discretion in denying his motion because it was untimely. Bank filed its motion for summary judgment and its designated

dismissal order was void. 1991) (trial court erred in denying motion to set aside dismissal under Rule 41(E); plaintiff had not received notice of the defendants’ motion to

In the current thesis four empirical studies are presented in which we tested the general hypothesis of disturbed anticipatory state-to-state switch-related neural

Drawing on published document collections from the Central Powers (Germany, Austria-Hungary) and the Allies (Great Britain, France, and Russia), as well as unpublished materials from

Since TS fuzzy models can well approximate a large class of nonlinear systems, and the TS model based approach can apprehend the nonlinear behavior of a system while keeping the