Download presentation
Presentation is loading. Please wait.
1
Chapter 5: Statements and Control Flow
Outline Simple and Compound Statements Expression and Null Statements Flowcharts Selection Statements Sample Problem Iteration Statements Jump Statements Labeled Statements Random Number Generation Extensions in Ch Switch Statement with Case of String Type The foreach Loop for String Type
2
Simple and Compound Statements
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);
3
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. /* … */ ;
4
Flowcharts Often, programmers use flowcharts to organize the order in which actions are to be performed. Common flowchart symbols are shown on the next slide.
5
Common Flowchart Symbols
6
Selection Statements If Statements Boolean numbers.
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; }
7
Flowchart for an if-Statement
The syntax for an if-statement is as follows: if(expression) statement
8
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.
9
Flowchart of an if-else Statement
The syntax for an if-else statement is as follows: if(expression) statement1 else statement2
10
- The syntax for the else-if statement is as follows:
Else-if Statements - The syntax for the else-if statement is 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.
11
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
12
Example: Output: i = 10 /* 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; Output: i = 10
13
Sample Problem Figure1: The system diagram and FBD of a 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
14
of the rigid body can be derived as follows. a = (p- mg)/m (4)
The nomenclature related to the modeling of the system is listed below. m -- mass of the body x position of the body v velocity of the body a acceleration of the body g 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)
15
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.
16
Flowchart of Program force.c
17
Please input time in seconds 4 Force p = 24.000000 (N)
/* 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: > force.c Please input time in seconds 4 Force p = (N)
18
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.
19
Flowchart of Program force2.c
20
Please input time in seconds 4 Force p = 24.000000 (N)
/* 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); else { printf(“Invalid input\n”); return 0; Note: (0 <= t && t <= 3) in C expression for (0 ≤ t ≤ 3) in math notation Program Output: > force2.c Please input time in seconds 4 Force p = (N)
21
Calculate the score based on a grade.
/* 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; Calculate the score based on a grade.
22
Switch Statements The syntax of a switch statement is as follows:
switch(expression) { case const-expr1: statement1 break; case const-expr2: statement2 default: statement } The controlling expression of a switch statement should have an integer or string type. The expression of each case label should be an integer constant expression or string. None of the case constant expressions in the same switch statement should have the same value. There may be at most one default label in a switch statement. A switch statement causes control to jump to, into, or past the statement that is the switch body. The executions inside a switch statement depends on the value of the controlling expression, the presence of a default label, and the values of any case labels on or in the switch body.
23
The number of case values in a switch statement is not limited.
If the controlling expression matches one of the case constant expressions, control jumps to the statement following the matched case label. If no match occurs and there is a default label, control jumps to the labeled statement. If no converted case constant expression matches and there is no default label, no part of the switch body is executed.
24
Flowchart of a switch Statement
switch(expression) { case const-expr1: statement1 break; case const-expr2: statement2 default: statement }
25
A program to program ifc.c using the switch statement is as follows:
Example: /* 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"); default: printf("i = %d\n", i); } return 0; Output: i = 10
26
Calculate the score based on a grade.
/* 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; case 'C': /* entered C */ score = 2.0; case 'D': /* entered D */ score = 1.0; case 'F': /* entered F */ score = 0.0; default: /* entered any other character */ 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; Calculate the score based on a grade.
27
Iteration Statements While Loop
The syntax of a while statement is as follows: The evaluation of the controlling expression takes place before each execution of the loop body. The loop body is executed repeatedly until the return value of the controlling expression is equal to 0. while(expression) statement
28
Flowchart of a while Loop
The syntax of a while loop is as follows: while(expression) statement
29
Example: Output: 0 1 2 3 4 int i = 0; while(i < 5){
printf(“%d “, i); i++; } Output:
30
A Typical Program Structure in C
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.
31
/* processing */ 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(“%d”, &n); while (i <= n) { f *= i; i++; } /* termination */ printf(“factorial %d! = %d\n", n, f); return 0; Execution and Output: > whilec.c 5 factorial 5! = 120
32
The flowchart for program whilec.c
33
Control of Repetition Counter-controlled repetition
Sentinel-controlled repetition.
34
Counter-controlled repetition
Loop repeated until counter reaches a certain value. Definite repetition: number of repetitions is known Example: 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.
35
The flowchart for program gpa.c
36
> gpa.c Execution and Output: Enter a grade: 4 Enter a grade: 3.7
/* 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; Execution and Output: > gpa.c Enter a grade: 4 Enter a grade: 3.7 Enter a grade: 3.3 The GPA is:
37
Sentinel-controlled repetition
Loop repeated until the sentinel (signal) value is entered. Indefinite repetition: number of repetitions is unknown when the loop begins execution. Example: Develop a GAP calculation program that will process grades with scores in the range of [0, 4] for an arbitrary number of courses.
38
The flowchart for program gpa2.c
39
/* 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');
40
> gpa2.c /* termination */ Execution and Output: if(count != 0) {
gpa = total/count; printf("The GPA is: %f\n", gpa); } else printf("No grade entered.\n"); return 0; Execution and Output: > gpa2.c 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: 10 Invalid grade Enter a grade [0, 4] or -1 to end: -1 The GPA is:
41
Do-While Loop The syntax of a do-while statement is as follows:
The evaluation of the controlling expression takes place after each execution of the loop body. The loop body is executed repeatedly until the return value of the controlling expression is equal to 0. do statement while(expression);
42
Flowchart of a do-while loop
The syntax of a do-while statement is as follows: do statement while(expression);
43
Example: int i = 0; do { printf(“%d ”, i); i++; } while(i < 5); Output:
44
10 What is the output of the following example? Example: int i = 10;
do { printf(“%d ”, i); i++; } while(i < 5); Output: 10
45
the controlling expression. execution of the loop body. loop body.
For Loop The syntax of a for statement is as follows: for(expression1; expression2; expression3) statement The expression expression1 is evaluated as a void expression before the first evaluation of the controlling expression. The expression expression2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression3 is evaluated as a void expression 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) { expression3; }
46
Flowchart of a for Loop The syntax of a for loop is as follows:
for(expression1; expression2; expression3) statement
47
0 1 2 3 4 Output: Example: int i; for(i = 0; i < 5; i++) {
printf(“%d ”, i); } Example: Output:
48
Calculating a factorial 5!. The factorial n! is defined as n*(n-1)!
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(“%d”, &n); for(i=1, f=1; i<=n; i++) { f = f*i; } printf(“factorial %d! = %d\n", n, f); return 0; Execution and Output: > forloop.c 5 factorial 5! = 120
49
A Mathematical Formula with a Single Variable
Calculate function sinc(x) = sin(x)/x from -10 <= x <= 10 with a step size 5. sinc(0) = sin(0)/0 is NaN inside a program. But, it can be proved that sin(0)/0 is 1 in calculus. Generate data points (x, y) for x in the range x0 <= x <= xf with step size xstep linearly. The number of points n = (xf – x0)/xstep + 1; Each data point can be calculated by for(i = 0; i <n; i++) { x = x0 + i*xstep; y = f(x); }
50
Output: /* File: forsinc.c */
#include <stdio.h> /* for printf() */ #include <math.h> /* for sin() and fabs() */ #include <float.h> /* for FLT_EPSILON */ int main() { double x, x0, xf, xstep, result; int i, n; printf(" x sinc(x)\n"); printf(" \n"); x0 = -10.0; /* initial value */ xf = 10.0; /* final value */ xstep = 5.0; /* step size */ n = (xf - x0)/xstep + 1; /* num of points */ for(i = 0; i < n; i++) { x = x0 + i*xstep; /* value x */ if(fabs(x) < FLT_EPSILON) result = 0.0; else result = sin(x)/x; printf("%8.4f %8.4f\n", x, result); } return 0; Output: x sinc(x)
51
Note: sin(x) can be calculated using a function declared in header file math.h. Use a loop control variable of int type. Use format specifier ”%8.4” with field width 8 and 4 digits after the decimal point.
52
Nested Loop For nested loops, the inner loops must be
finished before the outer loop resume iteration.
53
Write a program to print a multiplication table.
1| 1 2| 3| 4| 5| 6| 7| 8| 9| 10|
54
A program to print a multiplication table.
Example: A program to print a multiplication table. /* File: nestedloop.c */ #include <stdio.h> int main() { int i, j; printf(" \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"); return 0;
55
A Mathematical Formula with Multiple Variables
Calculate function for x from -10 <= x <= 10 with a step size 10 and y from -10 <= y <= 10 with a step size of 10.
56
/* File: forsinr.c */ #include <stdio.h> #include <math.h> int main() { double x, x0, xf, xstep, y, y0, yf, ystep, result; int i, j, nx, ny; printf(" x y sinr(x,y)\n"); printf(" \n"); x0 = -10.0; xf = 10.0; xstep = 10.0; nx = (xf - x0)/xstep + 1; /* num of points for x */ y0 = -10.0; yf = 10.0; ystep = 10.0; ny = (yf - y0)/ystep + 1; /* num of points for y */
57
Output: sin(0)/0 is NaN for(i = 0; i < nx; i++) {
x = x0 + i*xstep; /* caclulate value for x */ for(j = 0; j <ny; j++) { y = y0 + j*ystep; /* calculate value for y */ r = sqrt(x*x + y*y); result = sin(r)/r; printf("%10.4f %10.4f %8.4f\n", x, y, result); } return 0; x y sinr(x,y) NaN Output: sin(0)/0 is NaN
58
Note: Square root function sqrt() is declared in header file math.h. Use nested loops for x and y. Each has its own loop control variable of int type.
59
Jump Statements Break Statements Example: int i; 0 1 2
The break statement provides an early exit from the for, while, do-while, and foreach loops as well as 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
60
int i; Continue Statements and do-while loop to begin. Example:
The continue statement causes the next iteration of the enclosing for, while, and do-while loop to begin. A continue statement should only appear in a loop body. Example: int i; for(i=0; i<5; i++) { if(i == 3) { continue; } printf("%d", i); Output:
61
Pseudocode Pseudocode 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: while(expr) . . . endwhile dowhile . . . enddowhile(expr) for i = 1, …, n . . . endfor if(expr) . . . endif if(expr) . . . else endif if(expr) . . . else if(expr2) else endif
62
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.
63
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! 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 endwhile print expx and exp(x)
64
Modified pseudocode for calculating e0
Modified pseudocode for calculating e0.5 based on 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! 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)
65
Flowchart for the algorithm outlined in pseudocode exp2.p
66
Procedures 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. Update term = term * x/i, expx = expx + term, and i = i+1. 4. Repeat step 2.
67
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;
68
Output: expx = exp(x) =
69
Calculating the Square Root of Number Using Newton’s Method
70
Calculating square root of 3.
/* File: sqrtx.c Calculate square root sqrt(a) for a = 3.0 using Newton's method */ #include <stdio.h> #include <math.h> /* for fabs() */ #include <float.h> /* for FLT_EPSILON */ #define N /* the maximum number of iteration */ int main() { int i; double a, x0, x1, x2; a = 3.0; /* sqrt(a) with a = 0.3 */ x0 = a; /* an initial guess for x0 */ x1 = x0; /* set x1 to x0 */ for(i = 1; i <= N; i++) { x2 = (x1+a/x1)/2.0; /* Newton's recursive formula */ if(fabs(x2-x1) < FLT_EPSILON) break; x1 = x2; /* update value x1 for next iteration */ } if(i < N) { /* number of iteration is less than N */ printf("sqrtx(%.2f) = %f\n", a, x2); printf("sqrt(%.2f) = %f\n", a, sqrt(a)); printf("Number of iterations = %d\n", i); else { /* number of iteration equals N */ printf("sqrtx failed to converge\n"); return 0;
71
The output indicates that only 5 iterations are needed to converge
sqrtx(3.00) = sqrt(3.00) = Number of iterations = 5 The output indicates that only 5 iterations are needed to converge
72
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.
73
Write a program to simulate the rolling of a six-sided die 6000 times.
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 die 6000 times.
74
Output: Face Frequency 1 1003 2 994 3 996 4 1021 5 990 6 996
case 5: freq5 += 1; break; case 6: freq6 += 1; } printf(“Face Frequency\n"); printf(" %d\n", freq1); printf(" %d\n", freq2); printf(" %d\n", freq3); printf(" %d\n", freq4); printf(" %d\n", freq5); printf(" %d\n", freq6); return 0; /* File: srand.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int face, roll; 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; case 3: freq3 += 1; case 4: freq4 += 1; Output: Face Frequency
75
Indent a Program Using ChIDE
Click the command “Tools | Indent” to indent the program in the editing pane.
76
Additional Slides in C
77
Sample Problem Figure1: The system diagram and FBD of a 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
78
of the rigid body can be derived as follows. a = (p- mg)/m (4)
The nomenclature related to the modeling of the system.is listed below. m -- mass of the body x position of the body v velocity of the body a acceleration of the body g 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)
79
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+2) if t >3 seconds. Calculate and print out accelerations for time t from 0 to 10 seconds with an incremental step size of 1 second. A flowchart illustrating the flow of control for program accelmpts.c is on the next slide. The C program of the problem is listed on the following slide. n = (tf – t0)/step +1 = (10-0)/1 + 1 = 11 t = t0 + i*step = i
80
Flowchart of Program accelmpts.c
81
Using Connectors in a Flowchart
82
Solution using a for-loop
/* File: accelmpts.c */ #include <stdio.h> #define M_G int main() { /* declaration and initialization */ double a, mu = 0.2, m = 5.0, t0 = 0.0, tf = 10.0, step = 1.0, p, t; int i, n; /* processing and display output */ printf("time accel (m/s^2)\n"); printf(" \n"); n = (tf – t0)/step + 1; /* n is 11 */ for(i=0; i< n; i++) { t = t0 + i*step; if(t<= 3) { p = 20.0; } else { p = 4*(t+2); a = (p-mu*m*M_G)/m; printf("%3.0f %8.4f\n", t, a); return 0; Solution using a for-loop Program Output: time accel (m/s^2)
83
Solution using a while-loop
/* File: accelmpts2.c */ #include <stdio.h> #define M_G int main() { /* declaration and initialization */ double a, mu = 0.2, m = 5.0, t0 = 0.0, tf = 10.0, step = 1.0, p, t; int I, n; /* processing and display output */ printf("time accel (m/s^2)\n"); printf(" \n"); n = (tf – t0)/step + 1; /* n is 11 */ i = 0; while (i<n) { t = t0 + i*step; if(t<= 3) { p = 20.0; } else { p = 4*(t+2); a = (p-mu*m*M_G)/m; printf("%3.0f %8.4f\n", t, a); i++; return 0; Solution using a while-loop Program Output: time accel (m/s^2)
84
Problem Statement: For the system shown in Figure1(a), the external force p is expressed as a function of time t, p(t) = 4(t-3) when t >= 0 write a program to continuously calculate the acceleration a based on the user input values for m, , and t. The program shall be terminated when the user input a sentinel value of -1.
85
Program using sentinel number. Program: /* File: accelsentinel.c */
#include <stdio.h> #define M_G int main() { double a, mu, m, p, t; printf("***** Acceleration Calculator *****\n\n"); printf("Please enter value for mass in kilogram\n"); scanf("%lf", &m); while((int)m != -1) { // -1 is a sentinel number printf("mass is %lf (kg)\n\n", m); printf("Please enter value for friction coefficient\n"); scanf("%lf", &mu); printf("friction coefficient is %lf\n\n", mu); printf("Please enter value for time in second\n"); scanf("%lf", &t); printf("time is %lf (s)\n\n", t); p = 4*(t-3)+20.0; a = (p-mu*m*M_G)/m; printf("Acceleration a = %f (m/s^2)\n\n", a); printf("Please enter value for mass or -1 to quit the program\n"); } return 0; Program: Program using sentinel number.
86
Execution and Output: ***** Acceleration Calculator *****
Please enter value for mass in kilogram 5 mass is (kg) Please enter value for friction coefficient 0.2 friction coefficient is Please enter value for time in second 2 time is (s) Acceleration a = (m/s^2) Please enter value for mass or -1 to quit the program
87
Please input time in second 4 Force p = 24.000000 (N)
/* File: force2_2.c */ #include <stdio.h> int main() { double p, t; printf("Please input time in second \n"); scanf("%lf", &t); if(0 <= t && t <= 3){ p = 20; } else if (t>3){ p = 4*(t+2); else /* if (t < 0) */ { printf(“Invalid input\n”); return 0; printf("Force p = %f (N)\n", p); Program Output: > force2_2.c Please input time in second 4 Force p = (N)
88
Flowchart of Program force3.c
Alternative solution with different logic
89
Alternative solution Program Output: > force2.c
/* File: force3.c */ #include <stdio.h> int main() { double p, t; printf("Please input time in second\n"); scanf("%lf", &t); if(t < 0){ printf(“Invalid input\n”); return 0; } else if(t <= 3){ p = 20; else /* if(t > 3) */ { p = 4*(t+2); printf("Force p = %f\n", p); Program Output: > force2.c Please input time in second 4 Force p =
90
‡ Slides for optional topics in Ch
91
The goto Statements A goto statement causes an unconditional jump to the statement prefixed by the named label in the enclosing function. A goto statement can either transfer control forward or backward within a function. Example: for(/* ... */) { /* ... */ if(emergency) goto hospital; } hospital: emergency_action();
92
Labeled Statements The syntax for labeled statements is as follows:
identifier : statement case constant-integral expr : statement case string-expr : statement default : statement A case or default label should only appear in a switch statement. Label names should be unique within a function. Any statement may be preceded by a prefix that declares an identifier as a label name.
93
‡ Slides for optional topics in Ch
94
Extensions in Ch The controlling expression of a switch
statement can be of string type. A new foreach-loop for handling strings
95
unknown host Example: Output: /* switchstr.ch */
#include <stdio.h> #include <string.h> int main () { string_t str; str = `hostname`; // get host name from command 'hostname' char *s="host2"; switch (str) { // or switch (s) case "host1": printf("s = host1\n"); break; case "host2": printf("s = host2\n"); default: printf("unknown host\n"); } Output: unknown host
96
The foreach Loop The syntax of a foreach loop is as follow: foreach(token; expr1; expr2; expr3) statement foreach(token; expr1; expr2) foreach(token; expr1) The foreach loop is used to handle iterations based on the condition of string type or pointer to char. The expressions expr1, expr2, and expr3 shall have string type or pointer to char. The identifier token should also be of string type or pointer to char. In each iteration, the variable token takes a token from the original expression expr1 separated by the delimiter expr3. The loop body is executed repeatedly until token is a NULL pointer or the same as expr2. This is achieved by comparing the controlling expression (token == NULL || (expr2 != NULL && !strcmp(token, expr2))) to 0. The omitted expr2 and expr3 in the syntax of a foreach statement are replaced by NULL and “ ;”, respectively.
97
Example: Output: s1= ab s1= cd s1= cds s2= AB s2= CD
#include <stdio.h> int main() { char *s1, *str="ab cd cds", *cond=NULL, *delimit=" "; foreach(s1;str;cond; delimit) { printf("s1= %s\n", s1); } string_t s2; foreach(s2;"AB;CD") { printf("s2= %s\n", s2); return 0; Output: s1= ab s1= cd s1= cds s2= AB s2= CD
98
Example: Output: token= ab token= 12 after foreach token = cd
#include <stdio.h> int main() { char *token, *str="ab:12 cd ef", *cond="cd", *delimit=" :"; foreach(token; str; cond; delimit) { printf("token= %s\n", token); } printf("after foreach token = %s\n", token); printf("after foreach cond = %s\n", cond); printf("after foreach delimi= %s\n", delimit); return 0; Output: token= ab token= 12 after foreach token = cd after foreach cond = cd after foreach delimi= :
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.