73
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 5: Statements and Control Flow

Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Chapter 5: Statements

and Control Flow

Page 2: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowcharts

There are 4 basic blocks: Example:

Page 3: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Common

Flowchart Symbols

Page 4: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

• A compound statement is a block of code enclosed with a pair of braces.

• A block allows a set of declarations and statements to be grouped into one syntactic unit.

• The initialization is performed for an initialization statement each time the declaration is reached in the order of execution.

Example:

int i = 10; // simple statement

{ // compound statement

int i;

i = 90;

...

}

printf(“%d”, i);

Simple and

Compound Statements

Page 5: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Expression and NULL Statements

• An expression statement contains an expression only. For example,

i*7+4;

• A null statement consisting of just a semicolon performs no operation.

/* … */

;

/* … */

Page 6: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Selection Statements

• If Statements– The syntax for an if-statement is as follows:

if(expression)

statement

– The controlling expression of an if statement should have a scalar type.

– The statement is executed if the expression compared is unequal to 0.

– The macros bool, true, and false are defined in header file stdbool.h for handling

Boolean numbers.

– bool is typedefed as char, true is defined as 1, and false is defined as 0.

Example:

#include<stdbool.h>

bool i = true;

/* ... */

if(i)

{

i = false;

}

Page 7: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart for an if-Statement

– The syntax for an if-statement is as follows:

if(expression)

statement

Page 8: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

• If-else Statements

– The syntax for an if-else statement is as follows:

if(expression)

statement1

else

statement2

– The controlling expression of an if-statement should have a scalar type.

– The statement1 is executed if the expression compared is unequal to 0, else statement2

is executed.

Page 9: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of an if-else Statement

– The syntax for an if-else statement is as follows:

if(expression)

statement1

else

statement2

Page 10: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

• Else-if Statements

- The else-if statement is simply cascaded (nested) if-else, as follows:

if(expression1)

statement1

else if(expression2)

statement2

else if(expression3)

statement3

else

statement4

- Semantically, the syntax of the else-if statement is an extension of the previous if-else

statement. Each else is associated with the preceding if.

Page 11: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of an else-if

Statement

The syntax for an else-if statement is as

follows:

if(expression1)

statement1

else if(expression2)

statement2

else if(expression3)

statement3

else

statement4

Page 12: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

/* File: ifc.c */

#include <stdio.h>

int main () {

int i;

i = 10;

if(i==2 || i == 4) {

printf("i = 2 or 4\n");

}

else if(i == 10) {

printf("i = 10\n");

}

else {

printf("i = %d\n", i);

}

return 0;

}

i = 10

Output:

Page 13: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Sample Problem

The system in Figure1 (a) consists of a single body with mass m moving on a

horizontal surface. An external force p acts on the body. The coefficient of

kinetic friction between body and horizontal surface is . The freebody diagram

for the system is shown in Figure1 (b).

Figure1: The system diagram and FBD of a sample problem

Page 14: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

The nomenclature related to the modeling of the system is listed below.

m -- mass of the body x -- position of the bodyv -- velocity of the bodya -- acceleration of the bodyg -- gravitational acceleration

-- friction coefficient f -- friction force N -- normal force

Equation of motion:

The equation of the motion of the system can be derived based on the Newton's

second law.

N = mg (1)

f = N (2)p-f = ma (3)

From equation (1), (2) and (3), the formula for calculating the acceleration

of the rigid body can be derived as follows.

a = (p- mg)/m (4)

Page 15: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Problem Statement:

For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s2, = 0.2.

The external force p is expressed as a function of time t,

p(t) = 20, if t <= 3 seconds

p(t) = 4(t-3)+20 if t >3 seconds.

Calculate the force p based on the time t input by the user.

A flowchart illustrating the flow of control for program force.c is on the next

slide. The C program of the problem is listed on the following slide.

Page 16: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of Program force.c

Page 17: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

/* File: force.c */

#include <stdio.h>

int main() {

double p, t;

printf("Please input time in

seconds \n");

scanf("%lf", &t);

if(t <= 3) {

p = 20.0;

}

else {

p = 4*(t+2);

}

printf("Force p = %f (N)\n", p);

return 0;

}

Program Output:

Please input time in seconds

4

Force p = 24.000000 (N)

Page 18: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Problem Statement:

For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s2, = 0.2.

The external force p is expressed as a function of time t,

p(t) = 20, if 0<= t <= 3 seconds

p(t) = 4(t-3)+20 if t >3 seconds.

Calculate the force p based on the time t input by the user.

The formula for the external force p(t) is changed in comparing with the previous

program statement.

A flowchart illustrating the flow of control for program force2.c is on the next

slide. The C program of the problem is listed on the following slide.

Page 19: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of Program force2.c

Page 20: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Program Output:

Please input time in seconds

4

Force p = 24.000000 (N)

Note:

(0 <= t && t <= 3)

in C expression

for (0 ≤ t ≤ 3)

in math notation

/* File: force2.c */#include <stdio.h>

int main() {double p, t;

printf("Please input time in seconds \n");scanf("%lf", &t);if(0 <= t && t <= 3){

p = 20.0;printf("Force p = %f\n", p);

}else if (t>3){

p = 4*(t+2);printf("Force p = %f\n", p);

}else {

printf(“Invalid input\n”);}

return 0;}

Page 21: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach/* File: ifgrade.c */

#include <stdio.h>

int main() {

char grade; /* grade */

double score; /* score */

printf("Enter a grade [A, B, C, D, F]: ");

scanf("%c", &grade);

if(grade == 'A') /* entered A */

score = 4.0;

else if(grade == 'B') /* entered B */

score = 3.0;

else if(grade == 'C') /* entered C */

score = 2.0;

else if(grade == 'D') /* entered D */

score = 1.0;

else if(grade == 'F') /* entered F */

score = 0.0;

/* entered any other character */

else {

score = -1;

printf("Invalid grade '%c'\n", grade);

}

if(score != -1)

printf("The score for the grade '%c' is

%.2f\n", grade, score);

return 0;

}

"else-if" example:

Calculate the

score based on a

grade.

Page 22: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Switch Statement– The syntax of a switch statement is as follows:

switch(expression) {

case const-expr1:

statement1

break;

case const-expr2:

statement2

break;

default:

statement

break;

}

– Expression should have integer or string type.

– case label should be an integer constant expression or string (No

two constant expressions should have the same value!)

– default label is optional

– break command jumps out of the switch

• If missing, the program continues to run sequentially!

Page 23: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of a switch Statement

switch(expression) {

case const-expr1:

statement1

break;

case const-expr2:

statement2

break;

default:

statement

break;

}

Page 24: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example: The previous program written

using the switch statement:

/* File: switchc.c */

#include <stdio.h>

int main () {

int i;

i = 10;

switch (i) {

case 2:

case 4:

printf("i = 2 or 4\n");

break;

case 10:

printf("i = 10\n");

break;

default:

printf("i = %d\n", i);

break;

}

return 0;

}

i = 10

Output:

Page 25: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach/* File: switchgrade.c */

#include <stdio.h>

int main() {

char grade; /* grade */

double score; /* score */

printf("Enter a grade [A, B, C, D, F]: ");

scanf("%c", &grade);

switch(grade) {

case 'A': /* entered A */

score = 4.0;

break;

case 'B': /* entered B */

score = 3.0;

break;

case 'C': /* entered C */

score = 2.0;

break;

case 'D': /* entered D */

score = 1.0;

break;

case 'F': /* entered F */

score = 0.0;

break;

default: /* entered any other character */

score = -1;

printf("Invalid grade '%c'\n", grade);

break;

}

if(score != -1)

printf("The score for the grade '%c' is %.2f\n", grade, score);

return 0;

}

Calculate the

score based on

a grade.

Page 26: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

5.5 Repetition/Iteration/Looping

While Loop

The evaluation of the controlling expression takes place before

each execution of the loop body.

– If expression is initially false, the body of the loop

executes zero times!

The loop body is executed repeatedly until the value of the

controlling expression becomes false (equal to 0)

while(expression)

statement

while(expression){

statement1

...

statement42

}

Page 27: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of a while Loop

while(expression)

statement

Page 28: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

0 1 2 3 4

int i = 0;

while(i < 5){

printf("%d ", i);

i++;

}

Output:

Page 29: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

A typical C program consists of four sections:

Declaration

declaration of variables.

Initialization

initialization of variables.

Processing

Data processing and computation.

Termination

Output the result.

Page 30: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

Calculating a factorial 5!.

The factorial n! is

defined as n*(n-1)!

/* File: whilec.c */

#include <stdio.h>

int main() {

/* declaration */

unsigned int i, f, n;

/* initialization */

i = 1;

f = 1;

/* processing */

printf(“Please input a number\n”);

scanf(“%u”, &n);

while (i <= n) {

f *= i;

i++;

}

/* termination */

printf(“factorial %d! = %d\n", n,

f);

return 0;

}

5

factorial 5! = 120

Execution and Output:

Page 31: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

• i is called a counter

•This loop is called a

counter-controlled loop

Page 32: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

Counter-controlled repetition

• Loop body is repeated until counter reaches a certain value.

• Number of repetitions must be known in advance!

A student takes four courses in a quarter. Each course

will be assigned a grade with the score from 0 to 4.

Develop a C program to calculate the grade point

average (GPA) for the quarter.

Page 33: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Page 34: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

/* File: gpa.c */

#include <stdio.h>

#define NUM 4

int main() {

/* declaration */

int count;

double grade, total, gpa;

/* initialization */

count = 0;

total = 0;

/* processing */

while(count < NUM) {

printf("Enter a grade: ");

scanf("%lf", &grade);

total += grade;

count++;

}

/* termination */

gpa = total/NUM;

printf("The GPA is: %f\n", gpa);

return 0;

}

Enter a grade: 4

Enter a grade: 3.7

Enter a grade: 3.3

Enter a grade: 4

The GPA is: 3.750000

Execution and Output:

Page 35: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

Develop a GAP calculation program that will process

grades with scores in the range of [0, 4] for an arbitrary

number of courses(not known in advance).

Sentinel-controlled repetition

• Loop repeated until the sentinel (signal) value is entered.

• Indefinite repetition: number of repetitions is unknown

when the loop begins execution.

Page 36: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Page 37: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach/* File: gpa2.c */

#include <stdio.h>

#define SENTINELNUM -1

#define HIGHESTMARK 4

int main() {

/* declaration */

int count;

double grade, total, gpa;

/* initialization */

count = 0;

total = 0;

/* processing */

printf("Enter a grade [0, %d] or %d to end: ",

HIGHESTMARK, SENTINELNUM);

scanf("%lf", &grade);

while((int)grade != SENTINELNUM) {

if(0 <= grade && grade <= HIGHESTMARK) {

total += grade;

count++;

}

else {

printf("Invalid grade %c\n", '\a');

}

printf("Enter a grade [0, %d] or %d to end: ",

HIGHESTMARK, SENTINELNUM);

scanf("%lf", &grade);

}

Why is this typecast

necessary?

Page 38: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

/* termination */

if(count != 0) {

gpa = total/count;

printf("The GPA is: %f\n", gpa);

}

else

printf("No grade entered.\n");

return 0;

}

Enter a grade [0, 4] or -1 to end: 4

Enter a grade [0, 4] or -1 to end: 3.7

Enter a grade [0, 4] or -1 to end: 3.3

Enter a grade [0, 4] or -1 to end: 4

Enter a grade [0, 4] or -1 to end: 10

Invalid grade

Enter a grade [0, 4] or -1 to end: 3.7

Enter a grade [0, 4] or -1 to end: -1

The GPA is: 3.740000

Execution and Output:

Page 39: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Do-While Loop

– The evaluation of the controlling expression takes place after each execution of the loop body.

– The loop body is executed repeatedly until the value of the controlling expression becomes false (equal to 0).

do

statement

while(expression);

do {

statement1

...

statement42

}

while(expression);

Page 40: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of a do-while loop

do

statement

while(expression);

Page 41: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

int i = 0;

do {

printf(“%d ”, i);

i++;

} while(i < 5);

Output:

0 1 2 3 4

Page 42: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

– What is the output of the following example?

Example:

int i = 10;

do {

printf(“%d ”, i);

i++;

} while(i < 5);

Output:10

Page 43: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

For Loop

for(expression1; expression2; expression3)

statement

• expression1 is evaluated once, at the beginning

• expression2 is the controlling expression that is evaluated before

each execution of the loop body.

• expression3 is evaluated after each execution of the loop body.

• Both expression1 and expression3 can be omitted.

– An omitted expression2 is replaced by a nonzero constant.

• The for-loop is semantically equivalent to the following while-loop:

expression1;

while(expression2) {

statement

expression3;

}

Page 44: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart of a for Loop

for(expression1; expression2; expression3)

statement

Page 45: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

0 1 2 3 4

int i;

for(i = 0; i < 5; i++) {

printf(“%d ”, i);

}

Output:

Page 46: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Example:

Calculating a factorial 5!. The factorial n! is defined as n*(n-1)!

/* File: forloop.c */

#include <stdio.h>

int main() {

unsigned int i, f, n;

printf(“Please input a number\n”);

scanf(“%u”, &n);

for(i=1, f=1; i<=n; i++) {

f = f*i;

}

printf(“factorial %d! = %d\n", n, f);

return 0;

}

Execution and Output:

5

factorial 5! = 120

Page 47: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

We have covered pp.143-151 of the text

To do for next time:

• Read and understand programs 5.9, 5.11

• Solve in notebook end-of-chapter problems

– 2, 3, 4

– Problem 6 first draw flowchart, then write

program!

Page 48: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

5.5.5 Nested Loops

The inner loops must finish execution before

the outer loop resumes.

Page 49: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Write a program to print a multiplication table.

1 2 3 4 5 6 7 8 9 10

------------------------------------------

1| 1

2| 2 4

3| 3 6 9

4| 4 8 12 16

5| 5 10 15 20 25

6| 6 12 18 24 30 36

7| 7 14 21 28 35 42 49

8| 8 16 24 32 40 48 56 64

9| 9 18 27 36 45 54 63 72 81

10| 10 20 30 40 50 60 70 80 90 100

------------------------------------------

Page 50: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

/* File: nestedloop.c */

#include <stdio.h>

int main() {

int i, j;

printf(" 1 2 3 4 5 6 7 8 9 10\n");

printf(" ------------------------------------------\n");

for(i=1; i<= 10; i++) { /* outer loop */

printf("%4d|", i);

for(j=1; j<=i; j++) { /* inner loop */

printf("%4d", i*j);

}

printf("\n");

}

printf(" ------------------------------------------\n");

return 0;

}

Page 51: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Fine point: We’re not concerned here too much with what exactly is

done inside the nested loops (printf). What we do care about is to

“touch” certain matrix elements in a certain order.

Extra credit: Modify the for loops to make the program “touch” the

top half of the matrix instead of the bottom half (including the

diagonal).

1 2 3 4 5 6 7 8 9 10

------------------------------------------

1| 1

2| 2 4

3| 3 6 9

4| 4 8 12 16

5| 5 10 15 20 25

6| 6 12 18 24 30 36

7| 7 14 21 28 35 42 49

8| 8 16 24 32 40 48 56 64

9| 9 18 27 36 45 54 63 72 81

10| 10 20 30 40 50 60 70 80 90 100

------------------------------------------

Page 52: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

5.6 Jump Statements (use with care!)

Break

– Provides an early exit from a loop (for, while, do-while) , and from the

switch statement.

– A break causes the innermost enclosing loop or switch to be exited

immediately.

Example:

int i;

for(i=0; i<5; i++) {

if(i == 3) {

break;

}

printf("%d", i);

}

Output: 0 1 2

Page 53: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Continue

– Causes the next iteration of the enclosing loop (for, while, do-while)to

begin.

– Should only appear in a loop body.

Example:

int i;

for(i=0; i<5; i++) {

if(i == 3) {

continue;

}

printf("%d", i);

}

Output:0 1 2 4

Page 54: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

goto– Causes an unconditional jump to a point in the program marked by a label

– Do not use it, it usually leads to unstructured, hard-to-understand

programs!

Example:

goto label1

label1:

We have already used labels in the switch statement!

Page 55: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

5.7 PseudocodePseudocode is an outline of a program written in a form that can be easily

converted into real programming statements. It is used for algorithm

development. There is no standard for pseudocode. We will the following

structures:

if(expr)

. . .

endif

for i = 1, …, n

. . .

endfor

while(expr)

. . .

endwhile

if(expr)

. . .

else

. . .

endif

if(expr)

. . .

else if(expr2)

. . .

else

. . .

endif

dowhile

. . .

enddowhile(expr)

Page 56: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Problem Statement:

Calculate ex with x = 0.5 using the Taylor series until the last term is less than

FLT_EPSILON defined in float.h.

Page 57: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Pseudocode for calculating e0.5

// File: expx.p

// Pseudocode for straightforward computation of exp(x)

// expx contains exp(x) and term is pow(x,i)/i!

declare x, expr, term

x = 0.5

expx = 1.0

term = 1.0

i = 1

while(term>FLT_EPSILON) // continue if pow(x,i)/i! > epsilon

// calculate factorial i!

factorial = 1

for j = 1, ..., i

factorial = factorial*j

endfor

term = pow(x, i)/factorial

expx = expx + term

i = i + 1

end while

print expx and exp(x)

Works, but it’s not very

efficient …

Page 58: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Improved pseudocode: The power and the factorial need not be

recomputed from scratch in every iteration! Instead, use the

recursive formula termi = termi-1 x/i

// File: expx2.p

// Pseudocode for recursive computation of exp(x)

// expx contains exp(x) and term is pow(x,i)/i!

declare x, expr, term

x = 0.5

expx = 1.0

term = 1.0

i = 1

while(term>FLT_EPSILON) // continue if pow(x,i)/i! > epsilon

term = term*x/i

expx = expx + term

i = i+1

endwhile

print expx and exp(x)

Page 59: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Flowchart for

the algorithm

outlined in

pseudocode exp2.p

Page 60: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Procedures (a.k.a. to do list)

for Algorithm Development

1. Initialize: x = 0.5, expx = 1.0, term = 1.0,

and i = 1.

2. If term > FLT EPSILON, continue at step 3.

Otherwise, print expx and exp(x), then stop.

3. Updates:term = term * x/I

expx = expx + term

i = i+1

4. Repeat from step 2.

Page 61: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Program exp2.c based on pseudocode exp2.p

/* File: expx2.c

Calculate the approximate value of exp(0.5) recursively */

#include <stdio.h>

#include <math.h> /* for exp() */

#include <float.h> /* for FLT_EPSILON */

int main() {

int i;

double x, expx, term;

x = 0.5;

expx = 1.0;

term = 1.0;

i = 1;

while(term>FLT_EPSILON) { /* continue if pow(x,i)/i! > epsilon */

term *= x/(double)i;

expx += term;

i++;

}

printf("expx = %f\n", expx);

printf("exp(x) = %f\n", exp(x));

return 0;

}

Page 62: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Output:

expx = 1.648721

exp(x) = 1.648721

Page 63: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

We have covered pp.143-151 of the text

To do for next time:

• Read and understand programs 5.9, 5.11,

5.15, 5.16, 5.17

• Solve in notebook end-of-chapter problems

– 2, 3, 4

– Problem 6 first draw flowchart, then write

program!

Page 64: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Random Number Generation

• Header file stdlib.h contains functions and definitions useful for

generating random numbers.

• Function rand() with prototype

int rand(void);

generates a sequence of pseudo-random integers in the range 0 to

RAND_MAX.

• The function prototype for function srand() is as follows

void srand(unsigned int seed);

Argument seed is an unsigned integer representing the seed to produce

a new sequence of random numbers to be returned by subsequent

calls to the rand() function.

What is a protoype?

Page 65: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

• For example

srand(time(NULL));

where function time() is defined in header file time.h. The time()function returns the current calendar time, which is converted to an unsigned int to seed the random number generator.

• In order to scale the random numbers directly generated by function rand(), the following formula may be used.

n = a + rand() % b

to generate an integer in the range of [a, a+b-1]. Here, a is considered the shifting value, which is equal to the first number of the desired range. Variable b is the scaling factor and is equal to the width of the desired range of numbers.

Example:

Write a program to simulate the rolling of a six-sided (fair) die 6000 times.

Page 66: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

/* File: srand.c */

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main() {

int face, rollcount;

int freq1=0, freq2=0, freq3=0,

freq4=0, freq5=0, freq6=0;

srand(time(NULL));

for (rollcount = 1; rollcount <= 6000;

rollcount ++) {

face = 1 + rand() % 6;

switch(face) {

case 1:

freq1 += 1;

break;

case 2:

freq2 += 1;

break;

case 3:

freq3 += 1;

break;

case 4:

freq4 += 1;

break;

case 5:

freq5 += 1;

break;

case 6:

freq6 += 1;

break;

}

}

printf(“Face Frequency\n");

printf(" 1 %d\n", freq1);

printf(" 2 %d\n", freq2);

printf(" 3 %d\n", freq3);

printf(" 4 %d\n", freq4);

printf(" 5 %d\n", freq5);

printf(" 6 %d\n", freq6);

return 0;

}

Output:

Face Frequency

1 1003

2 994

3 996

4 1021

5 990

6 996

How would you

handle the toss of a:

• coin?

• tetrahedral die?

• prismatic die with

42 sides?

Page 67: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

5.8 More on sentinels: EOF

If the loop processes data read from a file, then

the special character EOF can be used to

terminate the loop

Page 68: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

EOF

• Bad news: EOF is not an ASCII (or Unicode)

character!

– Why? B/c it depends on the Operating System

(which handles the files in a computer)

• Windows CTRL+Z, followed by ENTER

• All others CTRL+D

So then how can a C program test EOF?

• Good news: The OS can be “interrogated” using the feof() function

– Must include stdio.h

Page 69: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

EOF

• More good news: Although we will cover files

only in Ch.14, from the viewpoint of the OS,

the keyboard is a file, too!

– Use the stdin file handler, like this:

scanf("%d",&myVariable);

while (feof(stdin) == 0){

...

} A good C programmer will

rewrite this condition as:while (!feof(stdin))

Page 70: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

EOF

Show example program in MS Visual Studio

Now read and understand program

5.19/163

Page 71: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Skip Section 5.9, which is specific to Ch

We have finished Ch.5

Homework (Due next Wed, Oct 13):

• Programming problems (attach screenshots!)

– 7, 9, 10

– 15 – only point a.

– 45

– 46

• Pencil-and paper problem

– 13

Page 72: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Lab week 6

• 8

• 11

• 25

• 30 a, b, c

• 37

• 45 (different limits)

• 46 (different limits)

Page 73: Chapter 3 - Statements and Control Flow · p(t) = 4(t-3)+20 if t >3 seconds. Calculate the force p based on the time t input by the user. The formula for the external force p(t) is

Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.

C for Engineers and Scientists: An Interpretive Approach

Lab week 6 – problems assigned for

individual work

• 16

• 21

• 23

• 24

• 28

• 29