INS2020 - Switch, Loops (For)
INS2020 - Switch, Loops (For)
1
CONTENTS
1. Review
2
1. Arithmetic operators
1.1 Binary operators work using two operands (a and b are variables)
The / and % operators require special care: the result of a division is always truncated toward zero and
the value of i % j has the same sign as i
3
1. Arithmetic operators
1.2 Unary operators work using one operands
5
3. Compound assignment operators
6
4. The ternary operator
• The ternary operator is the only operator in C that works with 3 operands, and it’s a short way
to express conditionals
<condition> ? <expression> : <expression>
Example:
a?b:c
Explain: If a is evaluated to true , then the b statement is executed, otherwise c is.
7
Order of Operators
8
5. Comparison operators
9
Logical operators
“If the hours worked are more than 40 OR the sales are more than $25000,... “
10
Conditional expressions:
If, If – Else, Else – If, Nested If
• Any programming language provides the programmers the ability to perform choices.
Using else, you can specify exactly what happens when the relational test is false.
By using else if, you can have several if statements piled on top of each other,
narrowing a complex decision tree into various possible outcomes
• The entire expression following the if statement requires parentheses
11
Exercise review
Ex 1. Write a simple program which ask user to input their age (integer number) and produce
the result as below:
• If the age is from 18, output the line “Age is > 18, you are ALLOW to get driver license”
• Otherwise, output the line “You are below 18 and NOT ALLOW to get driver license yet”
• Note: use a constant to store the comparison age (18)
Ex 2. Write a program to check over speed and produce appropriate message. Given that,
speed limit is 60 km/h.
Acknowledge:
- Multiple if?
- Nested if?
- If else?
- else if?
Ex 3. Modify the exercise 2, additional fine of 12 million for driving without a license is
applied. (Save file name as: yourname_DriverFine.c and upload to folder General
DriverFine on MSTeam) 12
Exercise review: Calculating a Broker’s Commission
• When stocks are sold or purchased
through a broker, the broker’s commission • Write yourname_broker.c program asks the user
often depends upon the value of the stocks to enter the amount of the trade, then displays the
traded. amount of the commission:
• Suppose that a broker charges the Enter value of trade: 30000
amounts shown in the following table: Commission: $166.00
Transaction size Commission rate
Under $2,500 $30 + 1.7% • The heart of the program is a cascaded if
$2,500–$6,250 $56 + 0.66% statement that determines which range the trade
$6,250–$20,000 $76 + 0.34% falls into.
$20,000–$50,000 $100 + 0.22%
$50,000–$500,000 $155 + 0.11%
Over $500,000 $255 + 0.09%
13
Exercise review
• Program to find the greatest digit from three digits:
Write yourname_MaxNum.c program asks the user to enter 3 integer
numbers, then displays the maximum number among those numbers.
14
switch case • In C, the switch-case structure is
used to handle multiple
- switch case only works with integer, character and decisions, similar to the endless
enumeration constants (user defined data type in C) else if structure
19
Sample Exercise using switch - case
• https://codeforwin.org/c-programming/switch-case-programming-exercise
20
Loop expressions:
For, While and Do – while
• C offers us three ways to perform a loop: for loops, while loops and do while loops.
• They all allow you to iterate over arrays, but with a few differences.
21
for loop
• Typically used when you know exactly how many times you want to loop through a block
of code;
• Expression 1 is executed (one time) before the execution of the code block;
• Expression 2 defines the condition for executing the code block;
• Expression 3 is executed (every time) after the code block has been executed.
• Example:
22
i can be accessed inside of this for loop only
Notice: i is declared as
local variable inside
main()
i can be accessed
outside of the for loop in
the body of main()
23
step size
24
Practice
• In Banking, a customer can deposit an amount of money for saving with a 12-month
term at the bank with an interest rate of x%/year (about 6.5-7.5%). Suppose that,
accumulated interest will be added to the principal amount of the current period.
Write a program to ask user to input the amount of money they deposit and the number of
year they wish to withdraw the money. Calculate the amount of money customer get at the
end.
25
WHILE loop
• Instead of defining all the loop data up front when you start the loop, like we do in the
for loop, using while we just check for a condition.
26
Do While loop
• always execute a block, and then maybe repeat it.
• using the do while keyword
28
Infinite Loops
• An infinite loop is a looping construct that does not terminate the loop and executes the
loop forever.
Example in:
Applications that accept the user input and generate the output continuously until the user
exits from the application manually;
operating systems run in an infinite loop as it does not exist after performing some task;
servers run in an infinite loop as the server responds to all the client requests;
game will accept the user requests until the user exits from the game.
29
Infinite Loops
loop will execute infinite times the condition (i>=1), which will always be true for
every condition
30
Infinite Loops
Solution: x<=4.0
32
break AND continue
• In C, jump statements are used to jump from one part of the code to another altering the normal flow of
the program. They are used to transfer the program control to somewhere else in the program.
• There are 4 types of jump statements in C:
1. Break
The break statement exits or terminates the loop or switch statement based on a certain condition, without
executing the remaining code.
2. Continue
The continue statement in C is used to skip the remaining code after the continue statement within a loop and
jump to the next iteration of the loop. When the continue statement is encountered, the loop control immediately
jumps to the next iteration, by skipping the lines of code written after it within the loop body.
3. Goto
The goto statement is used to jump to a specific point from anywhere in a function. It is used to transfer the
program control to a labeled statement within the same function.
4. Return
The return statement in C is used to terminate the execution of a function and return a value to the caller. It is
commonly used to provide a result back to the calling code.
33
break statement
• The break statement exits or terminates the loop or switch statement based on a certain
condition, without executing the remaining code.
34
break statement
• The break statement exits or terminates the current loop or switch statement based on
a certain condition.
35
#include <stdio.h>
int main()
{
// nested for loops with break statement
// at inner loop
for (int i = 1; i <= 10; ++i) {
for (int j = 1; j <= i; ++j) {
if (i <= 4) {
printf("%d ", j);
}
else {
// if i > 4 then this innermost loop will
// break
break;
}
}
printf("\n");
}
return 0;
}
36
continue statement
• The continue statement in C can be used in any kind of loop to skip the current iteration.
37
Practice
1. Write a program to print numbers from 1 to 100 in ascending order. (5 mins)
2. Write a program to print the numbers from 1 to 100 in descending order,
with 20 numbers per line. (10 mins)
3. Write a program that enters an integer, finds multiples of that number with
numbers from 1 to 20, then prints the result to the screen. (5 mins)
4. Write a program that requires input of a integer n. Print even and odd
numbers from 1 to n. (10 mins)
5. Write a program that enters any sentence, counts the number of words and
characters in that sentence, and prints the results to the screen.
6. Write a program to calculate the result of the expression
S= 1+1/23+1/33+...+1/n3 (rounded to 5 decimal places)
38