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

INS2020 - Switch, Loops (For)

The document discusses different types of loops in C programming including for, while, and do-while loops; it explains that for loops are used when the number of iterations is known, while and do-while loops check a condition on each iteration, and provides examples of calculating a sum using a for loop and implementing an infinite loop using a while loop without incrementing the counter variable.

Uploaded by

Duy Phung Duc
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

INS2020 - Switch, Loops (For)

The document discusses different types of loops in C programming including for, while, and do-while loops; it explains that for loops are used when the number of iterations is known, while and do-while loops check a condition on each iteration, and provides examples of calculating a sum using a for loop and implementing an infinite loop using a while loop without incrementing the counter variable.

Uploaded by

Duy Phung Duc
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

INS2020 – C Programming

LESSON 3 – CONDITIONAL EXPRESSION (SWITCH)


- LOOPS: FOR, WHILE, DO WHILE

1
CONTENTS

1. Review

2
1. Arithmetic operators
1.1 Binary operators work using two operands (a and b are variables)

Note: You can put a math expression inside a printf():

printf("In 3 years, I'll be %d years old.\n", age + 3);

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

Example of unary minus:


newValue = oldValue - -factor;
The difference between a++ and ++a:
a++ increments the variable a after using it.
++a increments the a variable before using it.
The same applies to the decrement operator
Increase_Decrease_Sample 4
3. Compound assignment operators
• Those operators are useful to perform an assignment and at the same time perform
an arithmetic operation:

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.

suppose s1 and s2 are two values and we have this statement:


((s1 < s2) ? s1 : s2);
Explain: If s1<s2 then get s1, otherwise, get s2

7
Order of Operators

8
5. Comparison operators

a comparison (such as i < j) yields an integer: either 0 (false) or 1 (true)

9
Logical operators

Those operators are very useful


when working with Boolean
values (TRUE / FALSE)

“If the age is at least 21 AND no more than 65,...”

“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.

 The if statement uses relational operators to perform data testing.

 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%

• The minimum charge is $39.

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

- case’s value is followed by a colon


- The last statement to follow case is traditionally a
break command. If not, the program would
continue executing the statements belonging to the
next case statement. – see Example
- default: is optional
- If a break isn’t found in the last case statement, the
program falls through and executes the default
statements as well.

This type of structure is often used in menu systems


switchCase_Sample 15
Practice

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

10 minutes - Try this: with n is an integer, write a


program to calculate: 1 + 2 + …. + n

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.

This loop will be an infinite loop unless


you increment the i variable at some
point inside the loop.

26
Do While loop
• always execute a block, and then maybe repeat it.
• using the do while keyword

The block that contains the /* do something */


comment is always executed at least once,
regardless of the condition check at the bottom.

Then, until i is less than 10, we'll repeat the


block.
27
While and Do While

Code block inside the while loop is executed


only when the condition check is passed. Code block inside the while loop always executed at
least once, regardless of the condition check at the
bottom

28
Infinite Loops
• An infinite loop is a looping construct that does not terminate the loop and executes the
loop forever.

• It is also called an indefinite loop or an endless loop. It either produces a continuous


output or no output.

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

Because all the parts of the 'for' loop are


optional, when no condition have mentioned

 loop will execute infinite times the condition (i>=1), which will always be true for
every condition

30
Infinite Loops

- non-zero integer represents the true condition;

 While loop does not contain any condition to


end. 31
Infinite Loops

The computer will represent the value of 2.0 as


1.999999 or 2.000001  so the condition (x !
Note: The loop value should not be interfered with
=2.0) will never be false.

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.

#include <stdio.h> #include <stdio.h>


int main() { int main() {
// for loop to print 1 to 8 int i = 0;
for (int i = 1; i <= 8; i++) { // while loop to print 1 to 8
// when i = 4, the iteration will be while (i < 8) {
skipped and 4 will not be printed // when i = 4, the iteration will
be skipped and 4 will not be printed
if (i == 4) { i++;
continue; if (i == 4) {
} continue;
printf("%d ", i); }
} printf("%d ", i);
printf("\n"); }
return 0; return 0;
}
}

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

You might also like