Loops
03603111 Programming Fundamentals I
Department of Computer Engineering, Faculty of Engineering at Sriracha
Course outline and schedule
2
Overview
3
Previous lesson recaps
4
if statement – do it or skip it
Syntax: if (condition) statement
5
Statement(s)
Condition
True
False
if … else statement – do this or do that
Syntax:
if (condition) statement1 else statement2
int n = 123;
if (n % 2 == 0)
printf("%d is even.\n", n);
else
printf("%d is odd.\n", n);
~> 123 is odd.
6
Statement(s)1
Condition
Statement(s)2
True
False
Comparison and logical operators
7
Operator | Description |
== | Equal to |
!= | Not equal to |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
Operator | Description |
! | Negation (NOT) |
&& | AND |
|| | OR |
Multiway selection – the if … else if … else pattern
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf(" %c", &c); // note the space before %c
if (c >= 'A' && c <= 'Z') {
printf("'%c' is a capital letter.\n", c);
} else if (c >= 'a' && c <= 'z') {
printf("'%c' is a small letter.\n", c);
} else {
printf("'%c' is not a letter.\n");
}
}
8
Enter a character: x
'x' is a small letter.
// Re-run
Enter a character: A
'A' is a capital letter.
// Re-run
Enter a character: 9
'9' is not a letter.
Results
General cautions and guidelines
9
The U-SWACT Problem Solving Framework
10
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
The while loop
11
Let’s start with problems again
Conditional loops
13
while loop – check first, then act
14
Condition
Statement(s)
False
True
Problem: Printing N stars
#include <stdio.h>
int main()
{
int n;
printf("How many stars do you want? ");
scanf("%d", &n);
while (n > 0) {
printf("*");
n -= 1;
}
printf("\n");
return 0;
}
15
How many stars do you want? 5
*****
// Re-run
How many stars do you want? 0
Result:
Introducing the (in)famous ++ and -- operators
++ is the increment operator, and -- is the decrement operator
16
Problem: Printing N stars using -- operator
Direct substitution
int main()
{
int n;
printf("How many stars … ");
scanf("%d", &n);
while (n > 0) {
printf("*");
n--; // replaces n -= 1;
}
printf("\n");
}
Concise and idiomatic usage
int main()
{
int n;
printf("How many stars … ");
scanf("%d", &n);
// Check and decrease at once
while (n-- > 0) {
printf("*");
}
printf("\n");
}
17
Similar problem: Counting up to N
#include <stdio.h>
int main()
{
int n;
printf("Number to count up to: ");
scanf("%d", &n);
int v = 1;
while (v <= n) {
printf("%d\n", v);
v++;
}
return 0;
}
18
Number to count up to: 5
1
2
3
4
5
Result:
What happens if we try to combine the increment operator (++) with the condition?
Repeat N Times
PROBLEM: Given N, repeat an action N times
SOLUTION: We need a counter variable that counts up from 0 to N-1 (idiomatic) or 1 to N (less common)
Using while:
int i = 0; // counter variable
while (i < n) {
// Perform action ...
i++;
}
However, it is more common to use the for loop, which we will discuss next week
Using for:
for (int i = 0; i < n; i++) {
// Perform action ...
}
�Counter variables are commonly named i, j, or so, but you’re welcome to use a more meaningful name
19
CODING PATTERN
PATTERN NAME
++ and -- can make your head spin
20
INTERESTING BITS
Problem solving recipe: loop invariants
Problem: Sum of the inputs
5
1 3 2 -1 7
~> 12
22
Solution: Sum of the inputs
#include <stdio.h>
int main() {
int n;
int num;
int sum = 0;
// Read the number of inputs
scanf("%d", &n);
int i = 0;
while (i < n) {
scanf("%d", &num); // read each number
sum += num; // add to the sum
i++;
}
printf("%d\n", sum);
return 0;
}
23
Note the variable sum:
Loop invariants
24
A simple 4-step recipe to use loop invariants
25
Problem: Maximum of the inputs
26
Blank sheet – work out your solutions here
27
Problem: Factorial of N
28
Blank sheet – work out your solutions here
29
Solution: Factorial of 10
#include <stdio.h>
int main()
{
int n = 10;
int fact = 1;
int i = 1;
while (i <= n) {
fact *= i;
i++;
}
printf("%d! = %d\n", n, fact);
return 0;
}
30
10! = 3628800
Result:
Problem: Sum up until 50
31
Solution: Sum up until 50
#include <stdio.h>
int main()
{
int target = 50;
int n = 1, sum = 0;
while (sum + n < target) {
sum += n;
n++;
}
printf("N that sums up to %d = %d\n", sum, n - 1);
return 0;
}
32
N that sums up to 45 = 9
Result:
while (sum + n < target)
sum += n++;
More concise version
Interrupting the loop flow
break and continue
34
Sum of a series with skipping
#include <stdio.h>
int main()
{
int n = 0, sum = 0, last_add = 0;
while (1) { // infinite loop
n++;
// Skip any number divisible by 3
if (n % 3 == 0)
continue;
// Stop once target is reached
if (sum + n >= 35)
break;
sum += n;
last_add = n; // we record last_add because sometimes n is skipped
}
printf("N that sums up to %d = %d\n", sum, last_add);
return 0;
}
35
N that sums up to 27 = 8
Result:
We have just seen an infinite loop
36
The do … while loop
do … while loop – act first, then check
38
Condition
Statement(s)
False
True
Problem: Input validation
39
Input validation
#include <stdio.h>
int main()
{
int guess;
do {
printf("Enter your guess (1-100): ");
scanf("%d", &guess);
} while (guess < 1 || guess > 100);
printf("You guessed %d.\n", guess);
return 0;
}
40
Enter your guess (1-100): 0
Enter your guess (1-100): 101
Enter your guess (1-100): 100
You guessed 100.
Result:
Can we use while loop for that?
#include <stdio.h>
int main()
{
int guess;
printf("Enter your guess (1-100): ");
scanf("%d", &guess);
while (guess < 1 || guess > 100) {
printf("Enter your guess (1-100): ");
scanf("%d", &guess);
}
printf("You guessed %d.\n", guess);
return 0;
}
41
Code is repeated
When to use which?
42
When you’re lost, a reference is here to help…
C reference: https://en.cppreference.com/w/c
Still, I recommend getting a book – your life will be easier that way
43
That’s all for today!
44