Ppi Handout 03
Ppi Handout 03
right
left
Angle-Right Learning Goals
Check inputs
Execute conditional code
Repeat code
Understand different repetition concepts
1
Award Challenge
Syntax
if (condition) { statements_true } else { statements_false }
FILE-CODE ex_branching.c
1 #include <stdio.h>
2
3
4 int main(void)
5 {
6 int n;
7
8 printf(”Please enter a number: \n”);
9 scanf(”%d”, &n);
10
11 if (n > 0) {
12 printf(”The number %d is positive\n”, n);
13 } else {
14 printf(”The number %d is *not* positive\n”, n);
15 }
16
17 return 0;
18 }
6
Complex Branching I
7
Boolean Operators
8
Complex Branching II
AND-composition OR-composition
1 if (condition_1 && condition_2) { 1 if (condition_1 || condition_2) {
2 statements_1_and_2_true 2 statements_1_or_2_true
3 } else { 3 } else {
4 statements_1_or_2_false 4 statements_1_and_2_false
5 } 5 }
A hideous example
1 if (x == 0 && ++y > 3) { // evaluation of ++y depends on value of x!
2 ...
3 }
9
Dos and Don’ts
10
Dos and Don’ts: Examples
FILE-CODE ex_branching-bad.c
1 #include <stdio.h>
2
3 int main(void)
4 {
5 short s = -1;
6 int n = 0;
7 double d = .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1;
SKULL-CROSSBONES
8
9 if (n) { /* obfuscating what is checked */ }
10 if (!n) { /* applying a logic operator to an int */ }
11 if (n < 0)
12 n *= -1;
13 /* adding something down here with indentation will lead to unintended behavior */
14 if (n++ < 0) {
15 /* obfuscating what happens */
16 }
17 if (s < 35000) {
18 /* always true */
19 }
20 if (d == 0.9) {
21 /* are these the same? */
22 printf(”d is 0.9”);
23 }
24
25 return 0;
26 }
11
Quiz 3.1
1 int x = 13;
TERMINAL
Consider the shown C source code. 2
3
char c = ’a’;
bool b = false;
true?
6 statements_1
7 } else {
8 if (c++ > ’b’ && (b = x == 13)) {
9 statements_2
10 } else if (b) {
This is really bad code! 11 statements_3
12 }
13 }
Syntax
condition ? expression_true : expression_false
12
Deciding between Discrete Alternatives
statements_2
the end of the switch block break;
...
Omitting a break statement causes a fall-through default:
statements_else
i.e., successive execution of statements regardless of the case value }
FILE-CODE ex_switch.c
1 #include <stdio.h>
2
3 #define CHOICE_DE 1
4 #define CHOICE_DE_STR ”DE”
5 #define CHOICE_EN 2
6 #define CHOICE_EN_STR ”EN”
7
8 int main(void)
9 {
10 int lang;
11 printf(”Choose your language (%d:%s, %d:%s)! ”, CHOICE_DE, CHOICE_DE_STR, CHOICE_EN, CHOICE_EN_STR);
12 scanf(”%d”, &lang);
13
14 switch (lang) {
15 case CHOICE_DE:
16 printf(”You chose %s\n”, CHOICE_DE_STR);
17 break; // see what happens, if you omit this and choose CHOICE_DE
18 case CHOICE_EN:
19 printf(”You chose %s\n”, CHOICE_EN_STR);
20 break;
21 default:
22 printf(”Invalid choice!\n”);
23 }
24
25 return 0;
26 }
14
GLASSES Remarks and Spoiler
FILE-CODE ex_noswitch.c
1 #include <stdio.h>
2
switch statements are frequently 3
4
enum { CHOICE_DE, CHOICE_EN, CHOICE_NUM };
const char * const CHOICE_STR[] = { ”DE”, ”EN” };
data types
7 int main(void)
8 {
we’ll talk about that later 9
10
unsigned lang;
printf(”Choose your language!\n”);
22 return 0;
23 }
15
Award Preparing for the Kitchen
FILE-CODE handson_sugar-input.c
5 #define F_MIN 2
6 #define F_MAX 10000
7
8 int main(void)
9 {
10 srand(time(NULL));
11
12 unsigned N;
13 printf(”Number of runs (N, N>0)? ”);
14
15
scanf(”%u”, &N);
if (N <= 0) {
Check-Circle Read input
Validate input
16 printf(”error”);
17 return 0; Check-Circle
18 }
19
20 unsigned F;
Times-Circle Repeat N times
21 printf(”Number of fields (F, %u<=F<=%u)? ”, F_MIN, F_MAX);
22 scanf(”%u”, &F); Times-Circle Try to get the sugar
23 if (F < F_MIN || F > F_MAX) {
24
25
printf(”error”);
return 0;
Check-Circle Write high-quality software
26 }
27
28 unsigned T;
29 printf(”Trap distance (T, 0<T<F)? ”);
30 scanf(”%u”, &T);
31 if (T < 1 || T >= F) {
32 printf(”error”);
33 return 0;
34 }
16
Control Flow: Branching and Repeating
3 2
Repetitions
Repetition Statements
Repetition statements
while-statement
do-while-statement
for-statement
17
while Loop
Syntax
while (condition) {
statements
}
Unless the statements inside the loop can be interrupted, condition must
become false due to a statement inside the loop
18
while Loop – Use Cases
FILE-CODE ex_while-loop.c
1 #include <stdio.h>
2
3 int main(void)
4 {
Typical use cases 5
6
unsigned x;
unsigned digits = 0;
iterations
9
10 while (x > 0) {
11 x /= 10;
Guarded (first) loop execution 12
13 }
digits++;
14
15 printf(”The number has %u decimal digits.\n”, digits);
16
17 return 0;
18 }
19
do-while Loop
Syntax
do {
statements
} while (condition);
statements are executed at least once and repeated until condition turns false
→ loop is always entered at least once
20
do-while Loop – Use Cases
FILE-CODE ex_do-while-loop.c
1 #include <stdio.h>
2
3 #define NUMBER_MIN 10
Typical use cases 4 #define NUMBER_MAX 20
5
Unknown number of loop iterations 6
7
int main(void)
{
8 unsigned x;
At least one execution 9 do {
10 printf(”Enter a number from [%u, %u]: ”,
Best to use with short loop bodies to 11
12
NUMBER_MIN, NUMBER_MAX);
scanf(”%u”, &x);
21
for Loop
Syntax
for (initialization; condition; stepping) {
statements
}
Equivalent while-statement
1 initialization
2 while (condition) {
3 statements
4 stepping
5 }
22
for Loop – Use Cases
FILE-CODE ex_for-loop.c
Typical use cases 1 #include <stdio.h>
2
Known number of executions 3
4
int main(void)
{
(counted) 5
6
unsigned n;
unsigned sum = 0;
Remark: Variables declared in the initialization part of a for-statement only exist inside
the (entire) for loop
23
Breaking a Loop
break-statement
2 #include <stdbool.h>
3
4 int main(void)
Statements inside the loop 5
6
{
bool isPrime = true;
following the break statement 7
8
unsigned int x;
or not executed 9
10
printf(”Enter a positive number: ”);
scanf(”%u”, &x);
11
The program continues behind 12
13
for (unsigned d = 2; d*d <= x; d++) {
if (x % d == 0) {
the loop 14
15
isPrime = false;
break;
Used to handle special 16
17 }
}
situations or to improve 18
19 printf(”%u is %s.\n”, x, isPrime ? ”prime” : ”not prime”);
readability
20
21 return 0;
e.g., avoid additional or long if 22 }
statements (blocks)
24
Shortcutting a Loop
the loop 4
5
#define N 100
6 int main(void)
Statements of the loop following the 7 {
8 unsigned int div;
continue statement are skipped 9
10 printf(”Enter a positive number: ”);
Program continues at top of the loop 11
12
scanf(”%u”, &div);
25
Infinite Loops
FILE-CODE ex_inf-loop.c
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 int main(void)
5 {
6 while (true) { // also frequently: while (1)
7 int x;
8 printf(”Enter a number to compute the square for (0 to exit): ”);
9 scanf(”%d”, &x);
10 if (x == 0) {
11 break;
12 }
13 printf(”(%d)^2 = %u\n”, x, (unsigned)(x*x));
14 }
15
16 return 0;
17 }
26
Dos and Don’ts
27
Award Trying to Get Some Sugar
FILE-CODE handson_sugar-loops.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4
5 #define F_MIN 2
6 #define F_MAX 10000
7
Read input
8 #define JUMP_MAX 6
Check-Circle
··· Check-Circle Validate input
38 unsigned sugars = 0;
39 for (unsigned n = 0; n < N; n++) { Check-Circle Repeat N times
40 unsigned field = 1;
41
42
while (field < F && (field == 1 || field % T != 0)) {
field += 1 + (rand() % JUMP_MAX);
Check-Circle Try to get the sugar
43 }
44 if (field >= F) { Check-Circle Write high-quality software
45 sugars++;
46 }
47 }
48
49 printf(”success probability: %.3f\n”, (double)sugars / N);
50
51 return 0;
52 }
28
Award Trying to Get Some Sugar Gracefully
FILE-CODE handson_sugar.c
5 #define F_MIN 2
6 #define F_MAX 10000
7
8 #define JUMP_MAX 6 Check-Circle Read input
9
10
11
int main(void)
{ Check-Circle Validate input
12 //srand(time(NULL));
13 srand(0); // remove randomness to compare results Check-Circle Repeat N times
14
15
16
unsigned N;
do { Check-Circle Try to get the sugar
17 printf(”Number of runs (N, N>0)? ”);
18
19
scanf(”%u”, &N);
} while (N <= 0);
Check-Circle Write high-quality software
20
21 unsigned F;
interactive implementation.
26
27 unsigned T;
28 do {
29 printf(”Trap distance (T, 0<T<F)? ”);
30 scanf(”%u”, &T);
29
Award Trying to Get Some Sugar Differently
30
Prozedurale Programmierung
für Informatiker (PPI)