Lecture 04
Lecture 04
(C Programming Language)
▪ 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
• 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
• Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition
printf( "%d ╲n", counter );
++counter; // increment
}
Counter-Controlled Repetition
• 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
• 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
• 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
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
• 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
• 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
• 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
• 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
• Structured programming
▪ Easier than unstructured programs to understand, test, debug and, modify programs
Summary
Summary
Summary
Summary
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 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 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.