chapter 4 control structures c programming for scientists & engineers with applications by reddy...
TRANSCRIPT
Chapter 4 Control Structures
C Programming for Scientists & C Programming for Scientists & Engineers with ApplicationsEngineers with Applications
by Reddy & Zieglerby Reddy & Ziegler
Control StructuresControl Structures
Sequence Structure Selection Structure
Want your programs to make decisions regarding which calculations to perform
Repetition Structure May want to repeat calculations without
writing the statement over and over This is called looping..
4.1 Relational and Logical Operations
Relational Operators and Relational Expressions
Logical Operator and Logical Expressions
Relational OperatorsRelational Operators
C contains six relational operators: < less than < = less than or equal to = = equal to > greater than > = greater than or equal to ! = not equal to
4.2 Selection Structures4.2 Selection Structures
Two-Way Selection StructuresTwo-Way Selection Structures Compound ConditionsCompound Conditions Multiway StructuresMultiway Structures
Conditional OperatorConditional Operator
How does the ? : conditional operator work?How does the ? : conditional operator work? The ? : operator requires three operands.The ? : operator requires three operands. expression1 ? expression2 : expression3 expression1 ? expression2 : expression3 If expression1 is true, expression2 is executed.If expression1 is true, expression2 is executed. If expression1 is false, expression3 is executed.If expression1 is false, expression3 is executed. Can be used to find the smaller of two numbers.Can be used to find the smaller of two numbers.
x = (y < z) ? y : zx = (y < z) ? y : z Assigns x the value of the smaller of y and z.Assigns x the value of the smaller of y and z.
Statements using the ? : operator are good Statements using the ? : operator are good shorthand for longer if-else type control structures.shorthand for longer if-else type control structures.
Logical ExpressionsLogical Expressions
The results of a logical expression (using the symbols A and B to indicate relational expressions)
A B A && B A | | B !A !B T T T T F F T F F T F T F T F T T F F F F F T T
Precedence of Precedence of OperatorsOperators
What are the precedence and associativity of logical, relational, and arithmetic operators?
Operator Name Associativity Precedence() parentheses L to R 1 (highest)++, -- post-increment L to R 2 ++, -- pre-increment R to L 2! Logical NOT L to R 3+, - Positive, negative sign L to R 3 +=,-=,*=,/=,%= compound assignment R to L 3*, / multiplication, division L to R 4+, - Addition, subtraction L to R 5 ==,>=,<=,>,<,!= relational operator L to R 6&& Logical AND L to R 7|| Logical OR L to R 8
= Assignment R to L 9 (lowest)
Precedence of Operators
x = (a>b || b>c && a==b) x = ( a>b || b>c && a==b ) (6) x = ((a>b)) || (b>c) && (a==b)) x = ((4>-2) || (-2>0) && 4==-2) x = ( True || False && False ) (7) x = ( True || False ) (8) x = ( True )
Switch Control Structures What does the switch statement do?
Commonly is constructed similarly to the if-else-if control structure. Transfer control
Syntax switch(expression) { case constant1: statement1a statement1b … case constant2: statement2a statement2b … default: statements }
4.3 Repetition Structures4.3 Repetition Structures
Iterative LoopsIterative Loops Nested Iterative LoopsNested Iterative Loops Nested Iterative LoopsNested Iterative Loops Conditional LoopsConditional Loops
While Loop: Part IWhile Loop: Part I
TopicsTopics Using while loopsUsing while loops
A test condition partA test condition part An execution partAn execution part
C provides a number of iterative control C provides a number of iterative control structures, known like structures, known like loopinglooping. .
The repeated execution of one or more The repeated execution of one or more statements.statements.
While LoopWhile Loop The structure of a C The structure of a C while loopwhile loop::
while (while (expressionexpression))
{{
statement1statement1
statement2statement2
……
}} The The expressionexpression is a relational expression (variable, is a relational expression (variable,
constant, or an arithmetic expression) that results in constant, or an arithmetic expression) that results in either True or False.either True or False.
If the result is true, the If the result is true, the statementsstatements between the between the braces are executedbraces are executed
A Generic IllustrationA Generic IllustrationCode before loop
{Block of Statements}
Loop keyword
Code after loop
yes
No
Source CodeSource Code #include <stdio.h>#include <stdio.h> void main(void)void main(void) {{ int i;int i; i = 1; i = 1;
while (i<= 5 )while (i<= 5 ) {{ printf (" Loop number %d in the while printf (" Loop number %d in the while
loop\n", i); loop\n", i); i++; i++; }} }}
Test expression
Incrementing counter variable
Statement block is repeatedly executed until test expression becomes false.
Do-While LoopsDo-While Loops
TopicsTopics Using do-while loopsUsing do-while loops Differences between do-while loops and Differences between do-while loops and
while loopswhile loops What is the structure of a do-while What is the structure of a do-while
loop?loop?
Do-while LoopsDo-while Loops What is the structure of a do-while loop?What is the structure of a do-while loop? dodo statementstatement whilewhile ( (expressionexpression););oror dodo {{ statement1;statement1; statement2;statement2; …… }} whilewhile ( (expressionexpression););
Do-while LoopsDo-while Loops The The statementsstatements between the braces are between the braces are
executed at least once regardless of whether executed at least once regardless of whether the the expressionexpression is True or False. is True or False. If the If the expressionexpression is True, the is True, the statementsstatements are are
executed again.executed again. What are the differences between do-while What are the differences between do-while
loops and while loops?loops and while loops? In the while loops, the test expression is tested In the while loops, the test expression is tested
first, and, if the test result is false, the loop body is first, and, if the test result is false, the loop body is not executed.not executed.
In the do-while loops, the loop body is executed In the do-while loops, the loop body is executed once. After that, if the test expression is False, the once. After that, if the test expression is False, the loop body is not executed again.loop body is not executed again.
void
main(void)
{
…
{…}
{…}
{…}
{…}
……}
do
while
Source code L4_9.CSource code L4_9.C /*For Lesson 4_9 *//*For Lesson 4_9 */ #include <stdio.h> #include <stdio.h> void main(void)void main(void) {{ int i=4, j=1;int i=4, j=1;
do do {{ printf("old_i=%2d, ",i);printf("old_i=%2d, ",i); i--;i--; printf("new_i=%2d\n",i); printf("new_i=%2d\n",i); } while(i);} while(i);
do ++j; do ++j; while(j>999);while(j>999);
printf("j=%2d\n",j); printf("j=%2d\n",j); } }
Test expression
Statement block is executed repeatedly until test expressionbecomes false
Test expression is always false
Simple For LoopSimple For Loop TopicsTopics
The The forfor loop control structure loop control structure Structure of a simple Structure of a simple forfor loop loop Difference between Difference between for for loops and loops and whilewhile
loopsloops Appropriate when you know how many Appropriate when you know how many
times the operations needs to be times the operations needs to be repeated.repeated.
Simple For LoopSimple For Loop What is a What is a for loopfor loop??
The simplest for loopThe simplest for loop for (for (loop expressionsloop expressions)) single statement for_loop bodysingle statement for_loop body;; for (day = 1; day <= 3; day++)for (day = 1; day <= 3; day++) printf(printf(““Day = %2d\nDay = %2d\n””, day);, day);
The loop expression must consist three The loop expression must consist three parts:parts: An initialization expressionAn initialization expression A loop repetition conditionA loop repetition condition An increment expressionAn increment expression
Simple For LoopSimple For Loop
The general structure of a for loopThe general structure of a for loop for (for (loop_expressionloop_expression)) {{ for_loop_bodyfor_loop_body }} loop_body loop_body ExampleExample { { minutes = 60 * hour; minutes = 60 * hour; printf("Hour = %2d, Minutes=%3d\printf("Hour = %2d, Minutes=%3d\
n",hour, minutes); n",hour, minutes); }}
Simple For LoopSimple For Loop Difference between Difference between for for loops and loops and whilewhile loops loops
Item Item forfor loop loop whilewhile looploop
Initialization one of the loop expressions given prior to the loopInitialization one of the loop expressions given prior to the loop
Test expression one of the loop expressions one of the loop Test expression one of the loop expressions one of the loop expressions expressions
Increment expression one of the loop expressions must be in the loop Increment expression one of the loop expressions must be in the loop bodybody
The number of iteration convenient and clear less convenient and The number of iteration convenient and clear less convenient and clear clear
Is knowIs know
The number of iteration less convenient and clear more convenient and The number of iteration less convenient and clear more convenient and clear clear
Is unknow than Is unknow than forfor loop loop
/*For Lesson 4_10 *//*For Lesson 4_10 */
#include <stdio.h>#include <stdio.h> void main(void) void main(void) {{ int day, hour, minutes;int day, hour, minutes;
for(day=1; day<=3; day++)for(day=1; day<=3; day++) printf("Day=%2d\n", day);printf("Day=%2d\n", day);
for (hour=5; hour>2; hour--)for (hour=5; hour>2; hour--) { { minutes = 60 * hour; minutes = 60 * hour; printf("Hour = %2d, Minutes=%3d\n",hour, printf("Hour = %2d, Minutes=%3d\n",hour,
minutes); minutes); } } } }
initialization
Test expression
“Increment” expression
Body of for loop
void
main(void)
{
…
Repetition condition
……}
An incrementexpression
for
initialization
No
yesyes
yes
Nested For LoopsNested For Loops The syntax of a nested for loop The syntax of a nested for loop
forfor (loop_1_expressions) (loop_1_expressions) {{ loop_body_1a /* optional loop_body for loop_body_1a /* optional loop_body for
outer loop */outer loop */ forfor (loop_2_expressions) /* this is an inner loop (loop_2_expressions) /* this is an inner loop
*/*/ { /* start inner loop */ { /* start inner loop */ loop_body_2 /* loop_body for inner loop */loop_body_2 /* loop_body for inner loop */ } /* end of inner loop */} /* end of inner loop */ loop_body_1b /* optional loop_body for loop_body_1b /* optional loop_body for
outer loop */outer loop */ } /* end of outer loop */} /* end of outer loop */
Nested For LoopsNested For Loops How to make the code easy to read?How to make the code easy to read?
Indentation Indentation for (for (……) )
{{
……
……
for (for (……))
{{
……
……
}}
……
……
}}
#include <stdio.h>#include <stdio.h> void main(void) void main(void) {{ int i, j, k, m=0;int i, j, k, m=0;
for (i=1; i<=5; i+=2) for (i=1; i<=5; i+=2) { { for (j=1; j<=4; j++) for (j=1; j<=4; j++) {{ k = i+j;;k = i+j;; printf("i=%3d, j=%3d, k=%3d\n", i, printf("i=%3d, j=%3d, k=%3d\n", i,
j, k);j, k); } } m=k+i; m=k+i; } } } }
Inner loop
Outer loop
4.4 Stacking and Nesting of Control Structures
Control Structure Stacking Nested Control Structures
4.5 Sample Problems and 4.5 Sample Problems and ProgramsPrograms
Impedance and Inductance of an Impedance and Inductance of an Electrical CoilElectrical Coil
Altitude of a ProjectileAltitude of a Projectile Shear Stress of a Metallic MemberShear Stress of a Metallic Member Table of Periods of PendulumTable of Periods of Pendulum Compression Stress and Strain in Compression Stress and Strain in
Steel RodsSteel Rods Types of TrianglesTypes of Triangles