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

Lect02c Overview of C Programming-3

Lecture #2 provides an overview of C programming, focusing on selection and repetition structures. It covers control structures like if-else, switch, while, for, and do-while loops, as well as logical and relational operators. Additionally, it discusses the use of break and continue statements in loops and evaluates Boolean expressions.

Uploaded by

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

Lect02c Overview of C Programming-3

Lecture #2 provides an overview of C programming, focusing on selection and repetition structures. It covers control structures like if-else, switch, while, for, and do-while loops, as well as logical and relational operators. Additionally, it discusses the use of break and continue statements in loops and evaluates Boolean expressions.

Uploaded by

maleliufb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

http://www.comp.nus.edu.

sg/~cs2100/

Lecture #2c

Overview of C Programming
Questions?
IMPORTANT: DO NOT SCAN THE QR CODE IN THE
VIDEO RECORDINGS. THEY NO LONGER WORK

Ask at
https://sets.netlify.app/module/676ca3a07d7f5ffc1741dc65

OR

Scan and ask your questions here!


(May be obscured in some slides)
Lecture #2: Overview of C Programming 3

6. Selection Structures (1/2)


 C provides two control structures that allow you to select
a group of statements to be executed or skipped when
certain conditions are met.

if … else …
if (condition) { if condition:
/* Execute these statements if TRUE */ # Statement
}
if condition:
if (condition) { # Statement
/* Execute these statements if TRUE */ elif
} condition:
else {
/* Execute these statements if FALSE */ # Statement
else:
} # Statement
Lecture #2: Overview of C Programming 4

6. Selection Structures (2/2)


Python
switch No counterpart
/* variable or expression must be of discrete type */
switch ( <variable or expression> ) {
case value1:
Code to execute if <variable or expr> == value1
break;

case value2:
Code to execute if <variable or expr> == value2
break;
...

default:
Code to execute if <variable or expr> does not
equal to the value of any of the cases above
break;
}
Lecture #2: Overview of C Programming 5

6.1 Condition and Relational Operators


 A condition is an expression evaluated to true or false.
 It is composed of expressions combined with relational
operators.
 Examples: (a <= 10), (count > max), (value != -9)

Relational Operator Interpretation Python


< is less than Allows
<= 1 <= x <= 5
is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Lecture #2: Overview of C Programming 6

Python
6.2 Truth Values NOTE: only integers!
In Python and JavaScript you have
 Boolean values: true or false. truthy and falsy values, but not in C
 There is no Boolean type in ANSI C. Instead, we use
integers:
 0 to represent false
 Any other value to represent true (1 is used as the representative
value for true in output)
 Example:
TruthValues.c
int a = (2 > 3);
int b = (3 > 2);
a = 0; b = 1
printf("a = %d; b = %d\n", a, b);
Lecture #2: Overview of C Programming 7

6.3 Logical Operators


 Complex condition: combining two or more Boolean expressions.
 Examples:
 If temperature is greater than 40C or blood pressure is greater than 200,
go to A&E immediately.
 If all the three subject scores (English, Maths and Science) are greater
than 85 and mother tongue score is at least 80, recommend taking Higher
Mother Tongue.
 Logical operators are needed: && (and), || (or), ! (not).

A B A && B A || B !A Python
False False False False True A || B  A or B
False True False True True A && B  A and B
!A  not A
True False False True False
True True True True False
Lecture #2: Overview of C Programming 8

6.4 Evaluation of Boolean Expressions (1/2)


 The evaluation of a Boolean expression is done according
to the precedence and associativity of the operators.
Operator Type Operator Associativity
Primary expression ( ) [ ] . -> expr++ expr-- Left to Right
operators
Unary operators * & + - ! ~ ++expr --expr (typecast) sizeof Right to Left
Binary operators * / % Left to Right
+ -
< > <= >=
Python
== !=
cond ? expr1 : expr2 
&& expr1 if cond else cond2
||
Ternary operator ?: Right to Left
Assignment = += -= *= /= %= Right to Left
operators
Lecture #2: Overview of C Programming 9

6.4 Evaluation of Boolean Expressions (2/2)


 What is the value of x?
int x, y, z, x is true (1)
a = 4, b = -2, c = 0;
x = (a > b || b > c && a == b); gcc issues warning (why?)

 Always good to add parentheses for readability.


y = ((a > b || b > c) && a == b); y is false (0)

 What is the value of z?


z = ((a > b) && !(b > c)); z is true (1)

Try out EvalBoolean.c


Lecture #2: Overview of C Programming 10

6.5 Short-Circuit Evaluation


 Does the following code give an error if variable a is zero?
if ((a != 0) && (b/a > 3)) {
printf(. . .);
}

 Short-circuit evaluation
 expr1 || expr2: If expr1 is true, skip evaluating expr2 and return true
immediately, as the result will always be true.
 expr1 && expr2: If expr1 is false, skip evaluating expr2 and return
false immediately, as the result will always be false.
Lecture #2: Overview of C Programming 11

7. Repetition Structures (1/2)


 C provides three control structures that allow you to
select a group of statements to be executed repeatedly.
while ( condition ) do
{ {
// loop body // loop body
} } while ( condition );

for ( initialization; condition; update )


{
// loop body
}
Update: change
Initialization: value of loop
initialize the loop Condition: repeat loop variable
variable while the condition on
loop variable is true
Lecture #2: Overview of C Programming 12

7. Repetition Structures (2/2)


 Example: Summing from 1 through 10.
Sum1To10_While.c
Sum1To10_While.py Sum1To10_DoWhile.c
Sum1To10_DoWhile.py
sum,i
int sum
= 0,
= 0,
1 i = 1; sum,sum
int i ==0,0,1i = 1;
while (i
i <=
<=10:
10) { sum{= sum + i
do
sum = sum + i;
i i =sum
i +=1sum + i;
i = i + 1
i++; while
i++;
i <= 10:
} } sum = sum + i
while
i =(ii <=
+ 110);

Sum1To10_For.py
Sum1To10_For.c
int sum,
sum = 0 i;
for (sum
i in range(1,
= 0, i = 1;
11):
i <= 10; i++) {
sum = sum + i;
i
}
Lecture #2: Overview of C Programming 13

7.1 Using ‘break’ in a loop (1/2)


BreakInLoop.py
BreakInLoop.c Without 'break':
//without
# without'break'
'break' 1
print("Without
printf ("Without
'break':");
'break':\n"); Ya
for (i=1;
i in range(1,6):
i<=5; i++) { 2
print(i)
printf("%d\n", i); Ya
print("Ya")
printf("Ya\n"); 3
Ya
}
4
Ya
//with
# with'break'
'break'
5
print("With
printf ("With
'break':");
'break':\n"); Ya
for (i=1;
i in range(1,6):
i<=5; i++) {
print(i)
printf("%d\n", i); With 'break':
if (i==3)
i == 3: 1
break
break; Ya
print("Ya")
printf("Ya\n"); 2
} Ya
3
Lecture #2: Overview of C Programming 14

7.1 Using ‘break’ in a loop (2/2)


With 'break’ in …
BreakInLoop.c
BreakInLoop.py
1, 1
# with
// with'break'
'break'in
inaanested
nestedloop
loop Ya
print("With 'break'
printf("With 'break'in
inaanested
nestedloop:")
loop:\n");
1, 2
for (i=1;
i in range(1,4):
i<=3; i++) { Ya
for (j=1;
j in range(1,6):
j<=5; j++) { 1, 3
print(i, ",",
printf("%d, %d\n",
j) i, j); 2, 1
if (j==3)
j == 3: Ya
break; 2, 2
print("Ya")
printf("Ya\n"); Ya
} 2, 3
} 3, 1
Ya
 In a nested loop, break only breaks 3, 2
Ya
out of the inner-most loop that 3, 3
contains the break statement.
Lecture #2: Overview of C Programming 15

7.2 Using ‘continue’ in a loop (1/2)


Without 'continue':
1
ContinueInLoop.py
ContinueInLoop.c Ya
# without
// without'continue'
'continue' 2
print("Without
printf ("Without
'continue':")
'continue':\n"); Ya
for (i=1;
i in range(1,6):
i<=5; i++) { 3
Ya
print(i)
printf("%d\n", i); 4
print("Ya")
printf("Ya\n"); Ya
} 5
Ya

//with
# with'continue'
'continue' With 'continue':
print("With
printf ("With
'continue':")
'continue':\n"); 1
for (i=1;
i in range(1,6):
i<=5; i++) { Ya
2
print(i)
printf("%d\n", i); Ya
if (i==3)
i == 3: 3
continue
continue; 4
print("Ya")
printf("Ya\n"); Ya
5
} Ya
Lecture #2: Overview of C Programming 16

7.2 Using ‘continue’ in a loop (2/2)


With ...
ContinueInLoop.c
ContinueInLoop.py 1, 1
# with
// with'continue'
'continue'in
inaanested
nestedloop
loop Ya
print("With 'continue'
printf("With 'continue'in
inaanested
nestedloop:")
loop:\n"); 1, 2
for (i=1;
i in range(1,4):
i<=3; i++) { Ya
1, 3
for (j=1;
j in range(1,6):
j<=5; j++) {
1, 4
print(i, ",",
printf("%d, %d\n",
j) i, j); Ya
if (j==3)
j == 3: 1, 5
continue
continue; Ya
2, 1
print("Ya")
printf("Ya\n"); 3, 1
Ya
} 2, 2 Ya
} Ya 3, 2
2, 3 Ya
 In a nested loop, continue only skips 2, 4 3, 3
Ya 3, 4
to the next iteration of the inner-most 2, 5 Ya
loop that contains the continue Ya 3, 5
Ya
statement.
Lecture #2: Overview of C Programming 1 - 17

Quiz
• Please complete the “CS2100 C Programming Quiz 2” in
Canvas.
• Access via the “Quizzes” tool in the left toolbar and select the quiz
on the right side of the screen.
Lecture #2: Overview of C Programming 18

End of File

You might also like