lecture 4 introduction to programming in c prof. dr. arne kutzner hanyang university / seoul korea

46
Lecture 4 Introduction to Programming in C Prof. Dr. Arne Kutzner Hanyang University / Seoul Korea

Upload: gordon-ball

Post on 26-Dec-2015

236 views

Category:

Documents


0 download

TRANSCRIPT

Lecture 4

Introduction to Programming in C

Prof. Dr. Arne Kutzner

Hanyang University / Seoul Korea

Control Structures in C

copyright © 2009 Arne Kutzner. All right reserved. L4.3

Control Structures (cont.)

• C provides the following control structures– compound structures (sequential Execution)– selection structures:

• if• if/else• switch

– repetition structures:• while• do/while• for

• Control structures are not thought to be statements in C. (Important regarding the placement of semicolons)

Sequential Execution of Statements in C

copyright © 2009 Arne Kutzner. All right reserved. L4.5

Sequential Execution (called Compound Statement)

• Statements are executed one by one in the order they are written in the curly braces:

{statement_1;statement_2;…statement_n;

}

begin in Pseudocode

end in Pseudocode

every statement in C ends with a semicolon !

Selection Structures:

if,if/else structures

copyright © 2009 Arne Kutzner. All right reserved. L4.7

if statement in C

if condition then statement

if (condition)statement;

Pseudocode

C Code

Parentheses necessary !

copyright © 2009 Arne Kutzner. All right reserved. L4.8

if-else statement in C

if condition then statement_1else statement_2

if (condition)statement_1;

elsestatement_2;

Pseudocode

C Code

Parentheses necessary !

copyright © 2009 Arne Kutzner. All right reserved. L4.9

if statement with one compound alternative

if condition then begin statement_1 statement_2 … end

if (condition) {statement_1;statement_2;…

}

Pseudocode

C Code

copyright © 2009 Arne Kutzner. All right reserved. L4.10

if Statement with Two Alternatives that are Compounds

if condition then begin statement_11 statement_12

… statement_1n endelse begin statement_21 statement_22

… statement_2m end

if (condition) { statement_11; statement_12; … statement_1n; } else { statement_21; statement_22; … statement_2m; }

Pseudocode C Code

copyright © 2009 Arne Kutzner. All right reserved. L4.11

Sequential if/else Structures• Test for multiple cases by placing if/else selection

structures inside if/else structures• Once condition is met, rest of statements is skipped

statement_1;if (condition_1){ statement_2; statement_3;}else if (condition_2){ statement_4; statement_5; }…else

statement_n;statement_m;

copyright © 2009 Arne Kutzner. All right reserved. L4.12

Example Program in Pseudocode

begin write "Enter midterm grade:" read midterm write "Enter final grade:" read final grade ← (0.6 * final) + (0.4 * midterm) write "Grade is " write grade

if grade > 60 then write " and passed" else write " and failed" end

copyright © 2009 Arne Kutzner. All right reserved. L4.13

Pseudocode in C#include <stdio.h>int main(){ double midterm, final, grade;

printf("Enter midterm grade:"); scanf ("%lf", &midterm); printf("\n Enter final grade:"); scanf ("%lf", &final); grade = 0.6 * final + 0.4 * midterm; printf("Grade is %lf and", grade);

if (grade > 60) printf(" passed!!\n");

else printf(" failed\n");

}

Variable Declaration necessary !

copyright © 2009 Arne Kutzner. All right reserved. L4.14

An ambiguous cases the last else-alternative belongs to the most recent if-structure in the same block. Example: int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf("A"); else printf("B");

is equivalent to int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) printf("A"); else printf("B"); }

Nested if/else

copyright © 2009 Arne Kutzner. All right reserved. L4.15

To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2;int k = 3; if (i > j) { if (i > k) printf("A"); } else printf("B");

This code prints B.

Nested if/else (cont.)

copyright © 2009 Arne Kutzner. All right reserved. L4.16

Caution (weird C)

• Adding a semicolon at the end of the condition of a if structure can be a serious mistake.if (grade > 60); printf("Passed\n");

• This mistake is hard to find, because the above code is correct. It results in a logic error !!

misplaced semicolon

if grade > 60 thenbeginend

write "Passed"

Problem shown Pseudocode:

Repetition Structures

while - loops

copyright © 2009 Arne Kutzner. All right reserved. L4.18

while statement in C

while condition do statement

while (condition)statement;

Pseudocode

C Code

Parentheses necessary !

copyright © 2009 Arne Kutzner. All right reserved. L4.19

while statement combined with compound structure

while condition do begin statement_1 statement_2 … end

while (condition) {statement_1;statement_2;…

}

Pseudocode

C Code

copyright © 2009 Arne Kutzner. All right reserved. L4.20

Factorial Computation in Pseudo Code

begin write "Enter n:" read n product ← 1 i ← 1 while i <= n do begin product ← product * i i ← i + 1 end write product end

copyright © 2009 Arne Kutzner. All right reserved. L4.21

Factorial Computation in C

#include <stdio.h>void main() {

int n, i, product; printf("Enter n:"); scanf("%d", &n); product = 1; i = 1; while (i <= n) {

product = product * i; i = i + 1; } printf("%d", product);}

while loop in C

copyright © 2009 Arne Kutzner. All right reserved. L4.22

Caution (weird C)

• Adding a semicolon at the end of the condition of a while structure can be a serious mistake.i = 10;while (i > 0); i = i – 1;

• The above statements results in an infinite loop

Misplaced semicoloni ← 10while i > 0 do

beginend

i ← i - 1

Problem shownPseudocode:

copyright © 2009 Arne Kutzner. All right reserved. L4.23

Nested Loops

• Loops (like all other control structures as e.g. the if-structure) may be nested

• A nested loop consists of an outer loop with one or more inner loops.

copyright © 2009 Arne Kutzner. All right reserved. L4.24

Example of nested while loop

compute

N

i

M

j

ji0 0

*

int sum, i, j;sum = 0; i=0;

while (i <= N) { j = 0;

while (j <= M) { sum = sum + (i * j); j = j + 1; } i = i + 1;}

printf("The total sum is %d", sum);

outer loop

inner loop

copyright © 2009 Arne Kutzner. All right reserved. L4.25

Exercise

• Develop some program in Pseudocode that contains if/else, while structures and translate this program into C

Boolean Values and Conditional Expressions in

C

copyright © 2009 Arne Kutzner. All right reserved. L4.27

Representation of Boolean Values in C

• VERY IMPORTANT:In the C the boolean values true and false are represented by integer values.

• The rules for interpreting integer values:– false : the value 0– true : any value other then 0

(typically 1)

• Remark:C does not have a separated boolean datatype as e.g. Java (serious design lack of C)

copyright © 2009 Arne Kutzner. All right reserved. L4.28

Conditional Expression in C - Introductionif (condition)

statement;we call the code inside

the parentheses conditional expression

while (condition)statement;

• A conditional expression in C is an expression whose evaluation delivers a numerical value that is interpreted as a boolean value (true / false)

copyright © 2009 Arne Kutzner. All right reserved. L4.29

Constants as Conditional Expressions

• The two constants 0 and 1 are the simplest form of conditional expressions– The following statements prints asterisks

“forever”:

while (1)printf("*");

copyright © 2009 Arne Kutzner. All right reserved. L4.30

Single Variables as Conditional Expressions

• A single variable of type int represents a valid conditional expressions– The following statements prints asterisks

“forever”:

int i;i = 1;while (i)

printf("*");

copyright © 2009 Arne Kutzner. All right reserved. L4.31

Compound Conditional Expressions

• Compound conditional expressions can be created by the use of conditional operators.

• Simple forms of compound expressions:– variable conditional_operator variable

Example: x > y– variable conditional_operator constant

Example: x == 4

copyright © 2009 Arne Kutzner. All right reserved. L4.32

Types of conditional operators

1. Relational and equality operators for comparisons

2. Operators for the representation of the boolean operations and/or/not(called logical operators)

copyright © 2009 Arne Kutzner. All right reserved. L4.33

Relational and Equality Operators

Operator Meaning

< less than

> greater than

<= less than or equal to

>= greater than or equal to

== equal to

!= not equal to

copyright © 2009 Arne Kutzner. All right reserved. L4.34

Examplesx power y item MIN DAY num MAX Sens

-5 1024 7 1.5 -12.0 'M' 12 1024 12

Operator Condition Meaning Value

<= x <= 0 x less than or equal to 0 1 (true)

< power < MAX power less than MAX 0 (false)

>= x >= y x greater than or equal to y 0 (false)

> item > MIN item greater than MIN 1 (true)

== DAY == 'M' DAY equal to 'M' 1 (true)

!= num != Sens num not equal to Sens 0 (false)

copyright © 2009 Arne Kutzner. All right reserved. L4.35

Logical Operators in Conditional Expressions

• Logical Operators in C:

Operator Meaning

&& AND

|| OR

! NOT

copyright © 2009 Arne Kutzner. All right reserved. L4.36

Logical Operator: AND Operator

• Example: Suppose x=0.5, y=0.4, z=4

(y>z)&&(x<z) delivers value 0(x>y)&& z delivers value 1

x y x && ynonzero (true) nonzero (true) 1(true)

nonzero (true) 0 (false) 0 (false)

0 (false) nonzero (true) 0 (false)

0 (false) 0 (false) 0 (false)

copyright © 2009 Arne Kutzner. All right reserved. L4.37

Logical Operator: OR Operator

• Example: Suppose x=0.5, y=0.4, z=4

(y>z)||(x<z) delivers value 1(x<y)||(z!=4) delivers value 0

x y x || ynonzero (true) nonzero (true) 1(true)

nonzero (true) 0 (false) 1(true)

0 (false) nonzero (true) 1(true)

0 (false) 0 (false) 0 (false)

copyright © 2009 Arne Kutzner. All right reserved. L4.38

Logical Operator: NOT Operator

• Example: Suppose x=0.5, y=0.4, z=4

!(y > z) delivers value 1!z delivers value 0

x !xnonzero (true) 0 (false)

0 (false) 1 (true)

copyright © 2009 Arne Kutzner. All right reserved. L4.39

Binding Rules (Operator Precedence)

• How to evaluate a == b && c ?Two alternatives:1. First equality check and then AND-operation:

(a == b) && c

2. First AND-operation and then equality check: a == (b && c)

• This ambiguity is resolved by operator precedence rules

copyright © 2009 Arne Kutzner. All right reserved. L4.40

Operator PrecedenceOperator Precedence

highest (strong binding)

!

* / %

+ -

< <= >= >

== !=

&&

||

= lowest (weak binding)

arithmetic operators

assignment operator

copyright © 2009 Arne Kutzner. All right reserved. L4.41

Exercise• Compute the values for all

following expressions:

z y x a

1 1 0 10

Expression Value

a != 10 || a == 0 0 (false)

a > x && x < y 1 (true)

!x == 0 0 (false)

x && y || z 1 (true)

!a 0 (false)

!a + y + !x 2 (true)

copyright © 2009 Arne Kutzner. All right reserved. L4.42

Parentheses in Conditional Expressions

• Using parentheses you can always change the precedence of operators in a conditional expression.Example:!(a && b)The AND-operation is here more binding than the NOT-operation

copyright © 2009 Arne Kutzner. All right reserved. L4.43

Operator Associativity

When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to  ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b = c = 5 is equivalent to a = (b = (c = 5))

Logical Assignments in C

copyright © 2009 Arne Kutzner. All right reserved. L4.45

Logical Assignments

• Logical assignments are assignments where the right side represents a conditional expression.Examples:senior_citizen = (age >= 65); in_range = (i > -10) && (i < 10);

is_even = ((n % 2) == 0);

conditional expressions

copyright © 2009 Arne Kutzner. All right reserved. L4.46

Caution (weird C)

• Logic assignments can trigger big trouble in the context of an intended equality checki = 0;if (i = 1) printf("true");else printf("false");

• The above statements prints true !

please distinguish = and ==

i ← falsei ← trueif i==true then

write "true"else

write "false"

identical logic in Pseudocode: