0% found this document useful (0 votes)
1 views

Lecture 04

Uploaded by

Trọng Tân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Lecture 04

Uploaded by

Trọng Tân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Program Control

(C Programming Language)

Dr. Thien Huynh-The


Dept. Comp. Commun. Eng.
HCMC Technology and Education
Content

▪ Introduction
▪ Repetition Essentials
▪ Counter-Controlled Repetition
▪ for Repetition Statement
▪ for Statement: Notes and Observations
▪ Examples Using the for Statement
▪ switch Multiple-Selection Statement
▪ do...while Repetition Statement
▪ break and continue Statements
▪ Logical Operators
▪ Confusing Equality (==) and Assignment (=) Operators
▪ Structured Programming Summary
Introduction

• This chapter introduces


▪ Additional repetition control structures
− for
− do…while
▪ switch multiple selection statement
▪ break statement
− Used for exiting immediately and rapidly from certain control structures
▪ continue statement
− Used for skipping the remainder of the body of a repetition structure and proceeding with the next
iteration of the loop
Repetition Essentials

• Loop
▪ Group of instructions computer executes repeatedly while some condition remains true

• Counter-controlled repetition
▪ Definite repetition: know how many times loop will execute
▪ Control variable used to count repetitions

• Sentinel-controlled repetition
▪ Indefinite repetition
▪ Used when number of repetitions not known
▪ Sentinel value indicates "end of data"
Counter-Controlled Repetition

• Counter-controlled repetition requires


▪ The name of a control variable (or loop counter)
▪ The initial value of the control variable
▪ An increment (or decrement) by which the control variable is modified each time through the
loop
▪ A condition that tests for the final value of the control variable (i.e., whether looping should
continue)

• Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition
printf( "%d ╲n", counter );
++counter; // increment
}
Counter-Controlled Repetition

• C Programmers would make the program more concise


Initialize counter to 0
while ( ++counter <= 10 )
printf( “%d ╲n”, counter );

• Note:
▪ Controlling counting loops with floating-point variables may result in imprecise counter values
▪ Avoid using more than three levels of nesting.
for Iteration Statement
for Iteration Statement
for Iteration Statement

• Using the final value in the condition of a while or for statement and using the <= relational
operator will help avoid off-by-one errors.
• The loop-continuation condition should be counter <= 10 rather than counter < 11 or counter
< 10.
for Iteration Statement

• Format when using for loops


for ( initialization; loopContinuationTest; increment )
statement;

• Example (print the integers from one to ten):


for( int counter = 1; counter <= 10; counter++ )
printf( "%d ╲n", counter );
• for loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest ) {
statement;
increment;}
• Initialization and increment
▪ Can be comma-separated lists. Example (what does a program print?):
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d ╲n", j + i );
for Iteration Statement

• Using commas instead of semicolons in a for header is a syntax error.


for( int counter = 1, counter <= 10, counter++ )
• Placing a semicolon immediately to the right of a for header makes the body of
that for statement an empty statement. This is normally a logic error.
for( int counter = 1; counter <= 10; counter++ );
Exercises

• Bài 01: Viết chtrình tính tổng các số nguyên từ 1 đến 10


• Bài 02: Viết chtrình tính tổng các số lẻ từ 50 đến 100
• Bài 03: Viết chtrình nhập vào số a lớn hơn hoặc bằng 2, tính giai thừa của a
• Bài 04: Viết chtrình tính tiền lãi gửi tiết kiệm theo năm với lãi suất 8%/năm (đáo
hạn lãi nhập vốn)
• Bài 05: Viết chtrình nhập x và n và tính giá trị 𝑥^𝑛
• Bài 06: Viết chtrình nhập n và tính
1 1 1
1+ 1 + 2 +⋯+ 𝑛
2 2! 2 3! 2 (𝑛 + 1)!
Yêu cầu sử dụng vòng lặp for
for Iteration Statement

• Arithmetic expressions
▪ Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and
y equals 10

for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to

for ( j = 2; j <= 80; j += 5 )


• Notes about the for statement:
▪ "Increment" may be negative (decrement)
▪ If the loop continuation condition is initially false
− The body of the for statement is not performed
− Control proceeds with the next statement after the for statement
▪ Control variable
▪ Often printed or used inside for body, but not necessary
for Iteration Statement

• Although the value of the control variable can be changed in the body of a for loop, this can lead to
subtle errors. It is best not to change it.
• Limit the size of control-statement headers to a single line if possible.
Exercise

A person invests 1000 usd in a savings account yielding 5% interest. Assuming that
all interest is left on deposit in the account, calculate and print the amount of money
in the account at the end of each year for 10 years. Use the following formula for
determining these amounts:
a = p(1+r)n
where
p is th original amount invested
r is the annual interest rate
n is the number of years
a is the amount on deposit at the end of the nth year
#include <stdio.h>
#include <math.h>
int main(){
double amount;
double principal = 1000.0;
double rate = 0.05;
int year;
printf("%4s%21s ╲n", "Year", "Amount on deposit");
for (year = 1; year <= 10; year++) {
amount = principal * pow(1.0 + rate, year);
printf("%4d%21.2f╲n", year, amount);
}
return 0;
}
switch Multiple-Selection Statement

• Switch: useful when a variable or expression is tested for all the values it can
assume and different actions are taken
• Format: series of case labels and an optional default case
switch ( value ){
case '1’:
actions
case '2’:
actions
default:
actions
}
break; //exits from statement
switch Multiple-Selection Statement
Exercises

• Viết chtrình C theo yêu cầu sau đây dùng lệnh switch
▪ Nhập vào toán tử muốn thực hiện (ví dụ, +, -, *, /)
▪ Nhập vào 2 biến a và b muốn thực hiện phép toán
▪ In ra kết quả của toán tử với 2 biến
Exercises

• Viết chtrình C theo yêu cầu sau đây dùng lệnh switch
▪ Nhập vào các chữ cái (ứng với xếp loại)
▪ Đếm có bao nhiêu chữ cái được nhập (chỉ tính a, b, c, d và không phân biệt viết hoa hay viết
thường)
− Nếu nhập chữ cái khác a,b,c,d thì báo sai và yêu cầu nhập lại
− Không muốn nhập nữa thì nhấn tổ hợp phím Ctrl+Z
▪ In ra có bao nhiêu lần nhập các chữ cái a, b, c, d
Example

getchar function (from <stdio.h>) reads one character


from the keyboard and stores that character in the
integer variable grade.

EOF stands for “end of file;” this


character varies from system to
system

switch statement checks each of


its nested cases for a match

break statement makes program


skip to end of switch
Example

default case occurs if none of the


cases are matched
Example
switch Multiple-Selection Statement

Notices:
• Testing for the symbolic constant EOF rather than –1 makes programs more portable.
Thus, EOF could have different values on different systems.
• Forgetting a break statement when one is needed in a switch statement is a logic error.
• Provide a default case in switch statements.
• Place the default clause last.
• The break statement is not required.
• Remember to provide processing capabilities for newline
do…while Repetition Statement

• The do…while repetition statement


▪ Similar to the while structure
▪ Condition for repetition only tested after the body of the loop is performed
▪ All actions are performed at least once
• Format:
do {
statement;
} while ( condition );
• Example (letting counter = 1):
do {
printf( "%d ", counter );
} while (++counter <= 10);
Prints the integers from 1 to 10
do…while Repetition Statement

• Some programmers always include braces in a do...while statement even if


the braces are not necessary.
• Infinite loops are caused when the loop-continuation condition in a while, for or
do...while statement never becomes false. To prevent this, make sure there is
not a semicolon immediately after the header of a while or for statement.
• In a counter-controlled loop, make sure the control variable is incremented (or
decremented) in the loop. In a sentinel-controlled loop, make sure the sentinel
value is eventually input.
do…while Repetition Statement

increments counter then checks if it


is less than or equal to 10
Exercise

• Viết chtrình sử dụng vòng lặp do...while


▪ Nhập điểm cho sinh viên
▪ Dừng việc nhập điểm nếu số sv dưới trung bình từ 5 bạn trở lên
▪ Sau khi dừng nhập điểm, in ra số sv trên trung bình cùng điểm trung bình của các sv đó
break and continue Statements

• break statement
▪ Causes immediate exit from a while, for, do…while or switch statement
▪ Program execution continues with the first statement after the structure
▪ Common uses of the break statement
− Escape early from a loop
− Skip the remainder of a switch statement
break and continue Statements

break immediately ends for loop


break and continue Statements

• Continue statement
▪ Skips the remaining statements in the body of a while, for or do…while statement
− Proceeds with the next iteration of the loop
▪ while and do…while
− Loop-continuation test is evaluated immediately after the continue statement is executed
▪ for
− Increment expression is executed, then the loop-continuation test is evaluated
break and continue Statements

continue skips to end of for loop


and performs next iteration
Exercise

• Viết chtrình nhập điểm cho sv (không biết số lượng sv)


▪ Thực hiện việc nhập và đọc điểm cho đến khi nào có 2 điểm 10 đầu tiên thì dừng lại
▪ In ra số lượng sv có điểm từ 8 trở lên
break and continue Statements

• Some programmers feel that break and continue violate the norms of structured
programming.
• The break and continue statements, when used properly, perform faster than the
corresponding structured techniques that we will soon learn.
• There is a tension between achieving quality software engineering and achieving
the best-performing software. Often one of these goals is achieved at the
expense of the other.
Logical Operations

• && ( logical AND ) – Returns true if both conditions are true


• || ( logical OR ) – Returns true if either of its conditions are true
• ! ( logical NOT, logical negation ) – Reverses the truth/falsity of its condition,
unary operator, has one operand
• Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
Logical Operators
Logical Operators

• In expressions using operator &&, make the condition that is most likely to be
false the leftmost condition.
• In expressions using operator ||, make the condition that is most likely to be true
the leftmost condition. This can reduce a program’s execution time.
Operator Precedence
Confusing (==) and (=) Operators

• Dangerous error
▪ Does not ordinarily cause syntax errors
▪ Any expression that produces a value can be used in control structures
▪ Nonzero values are true, zero values are false
▪ Example using ==:
if ( payCode == 4 )
printf( "You get a bonus!\n" );
• Checks payCode, if it is 4 then a bonus is awarded
• Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
→ This sets payCode to 4
4 is nonzero, so expression is true, and bonus awarded no matter what the payCode was →
Logic error, not a syntax error
Confusing (==) and (=) Operators

• lvalues
▪ Expressions that can appear on the left side of an equation
▪ Their values can be changed, such as variable names
− x = 4;

• rvalues
▪ Expressions that can only appear on the right side of an equation
▪ Constants, such as numbers
− Cannot write 4 = x;
− Must write x = 4;
▪ lvalues can be used as rvalues, but not vice versa
− y = x;
Confusing (==) and (=) Operators

• When an equality expression has a variable and a constant, as in x == 1, some


programmers prefer to write the expression with the constant on the left and the
variable name on the right
(e.g. 1 == x as protection against the logic error that occurs when you
accidentally replace operator == with =).
• After you write a program, text search it for every = and check that it is being
used properly.
Summary
Summary

• Structured programming
▪ Easier than unstructured programs to understand, test, debug and, modify programs
Summary
Summary
Summary
Summary

• All programs can be broken down into 3 controls


▪ Sequence – handled automatically by compiler
▪ Selection – if, if…else or switch
▪ Repetition – while, do…while or for
− Can only be combined in two ways
• Nesting (rule 3)
• Stacking (rule 2)
▪ Any selection can be rewritten as an if statement, and any repetition can be rewritten as a while statement
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Assignment 1

Write a program using for, switch, do...while


Assignment 2

Write a program to read value of N entered by user and print all Leap Years from 1
to N years. There are two conditions for leap year: 1- If year is divisible by 400 ( for
Century years), 2- If year is divisible by 4 and must not be divisible by 100 (for Non
Century years).

Write a program using for, switch, do...while


Assignment 3

• Write a C program that allows the user to enter n number (n > 0 and must be
entered first), calculate and print the average of all positive number.

Write a program using for, switch, do...while


Assignment 4

Write a C program to collect the temperature in the garden. Your program should:
a) input the temperature at 12 different times of the day. If the temperature is higher than 44.30,
the message “Caution! High temperature” will be showed.
b) determine and display the average temperature in a day.
c) find and print the largest temperature in a day.
d) find and print the second largest temperature in a day. Use the function to complete
this task.

Write a program using for, switch, do...while


Assignment 5

Write a program in C to find the sum of the series as follows

with x and the number of terms are entered by user.

Write a program using for, switch, do...while


Assignment 6

Write a program using switch statement to calculate the weakly salary of


▪ Manager (codeID = 1) with a fixed salary 240 USD/day. Inputs (entered by user):
number of working day.
▪ Hourly worker (codeID = 2) with 22 USD/hour for the first 40 hours and 1.5 times for
overtime working. Inputs (entered by user): number of working hours in a week.
▪ Commission worker (codeID = 3) with 250 USD/week plus 7.2% of their gross weekly
sale. Inputs (entered by user): weekly sale money
▪ Seller (codeID = 4) with a fixed incentive money for each selling item. Inputs (entered
by user): a fixed incentive money and number of selling items.

Write a program using for, switch, do...while

You might also like