Ch 1: Intro to Computer and Programming - PowerPoint PPT Presentation

1 / 57
About This Presentation
Title:

Ch 1: Intro to Computer and Programming

Description:

... printf('Science Studentn'); break; case 2 : case 4 : printf('Art Studentn' ... integer number between 1 to 5 (inclusive), and prints the word equivalent to it. ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 58
Provided by: badariah5
Category:

less

Transcript and Presenter's Notes

Title: Ch 1: Intro to Computer and Programming


1
6
CHAPTER
Structured Programming
2
Objectives
  • Selection structures
  • One-way and two-way selection using the if
    statement
  • Multi-way selection using
  • Nested if statement
  • the switch statement
  • Repetition structures using
  • the while statement
  • do while statement
  • for statement
  • continue and break statements

3
Control Structures - Sequence
  • Recall (chapter 2) that any algorithm can be
    described using only 3 control program
    structures sequence, selection and repetition.
  • Sequence structure
  • Statements are executed one by one until the end
    of the program is reached.
  • A group of statements that executed sequentially
    which is usually grouped (bracketed) by is
    known as Compound Statement

4
Sequence - example
include ltstdio.hgt void main(void) int
count 0 printf(Count d\n, count)
count printf(Count d\n,
count) count printf(Count
d\n, count) count
printf(Count d\n, count)
5
Selection Structure
  • Defines two courses of action depending on the
    outcome of a condition. A condition is an
    expression that is either true or false.
  • The 4 general form of selection structure
  • 1. if(Expression)
  • then-statement
  • / end_if /

2. if (Expression) then-statement else
else-statement / end_if /
6
  • 3. switch (ControllingExpression)
  • case constant 1 statement
  • break
  • case constant-n statement
  • break
  • default statement
  • / end_switch /
  • 4. (Expression)? then-statement else-statement

7
if Selection Structure
  • Syntax
  • if (Expression)
  • then-statement
  • / end_if /
  • The then-statement is only executed if the
    condition is satisfied (Expression returns True).
  • Example
  • if (status 1)
  • printf(Kids!!\n)
  • / end_if /
  • if (status 2)
  • printf(Adults!!\n)
  • / end_if /

No semicolon at the end of the if statement.
8
Example
  • include ltstdio.hgt
  • main(void)
  • int status
  • printf(Enter your membership status)
  • scanf(d, status)
  • if (status 1)
  • printf(Kids!!\n)
  • / end_if /
  • if (status 2)
  • printf(Adults!!\n)
  • / end_if /

9
Exercise
Assume gender is M age is 35
  • includeltstdio.hgt
  • void main ( )
  • char gender
  • int age
  • float car_loan
  • printf(Enter your gender (f/F or m/M) and
    age)
  • scanf(c d, gender, age)
  • if ((genderf genderF) agegt20)
  • car_loan200000.00
  • / end_if /
  • printf(Your car loan is .2f\n, car_loan)
  • printf(Well done.\n)

10
More exercise
Assume first is 7 second is 99
  • includeltstdio.hgt
  • void main( )
  • int first, second, temp0
  • printf("Please enter the first number ")
  • scanf("d", first)
  • printf("Please enter the second number ")
  • scanf("d", second)
  • if(secondgtfirst)
  • tempsecond
  • secondfirst
  • firsttemp
  • printf("\nd is bigger than d. \n\n", first,
    second)

11
if else Selection Structure
  • Syntax
  • if (Expression)
  • then-statement
  • else
  • else-statement
  • / end_if /
  • If the condition is satisfied (Expression returns
    True), the then-statement will be executed.
    Otherwise, the else-statement will get executed.
  • Example
  • if (age lt 5)
  • status 1
  • else
  • status 2
  • / end_if /

12
Example
  • includeltstdio.hgt
  • void main ( )
  • char gender
  • int age
  • float car_loan
  • printf(Enter your gender (f/F or m/M) and
    age)
  • scanf(c d, gender, age)
  • if ((genderf genderF) agegt20)
  • car_loan200000.00
  • else
  • car_loan 500000.00
  • / end_if /
  • printf(Your car loan is .2f\n, car_loan)

Assume gender is M age is 35
13
Exercise
  • Write a program that asks users for their annual
    income. Print a congratulatory message if the
    user makes more than RM120,000.00 a year or an
    encouragement message if the user makes less

14
Nested if else
  • Is an ifelse statement with another ifelse
    statements inside it.
  • The else if statement (in the nested ifelse)
    means that if the condition above is not
    satisfied, then try checking this condition. If
    any one of the condition is already satisfied,
    the other conditions will be ignored completely.

15
Example
Messy!
if (score gt 90) printf(A\n) else if
(score gt 80) printf(B\n) else if
(score gt 70) printf(C\n) else if
(score gt 60)
printf(D\n) else
printf(F\n) / end_if /
More readable.
if (score gt 90) printf(A\n) else if
(score gt 80) printf(B\n) else if (score gt
70) printf(C\n) else if (score gt 60)
printf(D\n) else
printf(F\n) / end_if /
16
Example
  • includeltstdio.hgt
  • void main()
  • int i
  • printf("Enter a number between 1 and 4 ")
  • scanf("d", i)
  • if(i1)
  • printf("one\n")
  • else if(i4)
  • printf(four\n")
  • else
  • printf(Unrecognized number\n")
  • / end_if /

17
ifelse with Compound Statements
  • In the examples that we have seen so far, there
    is only one statement to be executed after the if
    statement.
  • If we want to execute more than one statement
    after the condition is satisfied, we have to put
    curly braces around those statements to tell
    the compiler that they are a part of the
    then-statement or else-statement.

18
Example
  • if (score gt 90)
  • printf(You have done very well\n)
  • printf(Please see your lecturer to get a
    present\n)
  • else if (score gt 60)
  • printf(You have passed the course\n)
  • printf(But do not ask for any present from your
    lecturer\n)
  • printf(Go and celebrate on your own\n)

19
Exercise
  • The unit for electricity usage is kWh. For
    domestic usage, the monthly rate is 21.8
    cents/unit for the first 200 unit, 25.8
    cents/unit for the next 800 units and 27.8
    cents/unit for each additional units.
  • Given the amount of electricity units (in
    kWh) used by a customer, write a program that
    will calculate and print the amount of money
    needs to be paid by the customer to TNB. Please
    include proper input validation.

20
  • Write a program that prompts the users to enter
    the value of Ritcher scale number (n), and print
    its equivalent effect to the users based on the
    following table

21
Selection Structure using ? Operators
  • / alternative if-else demonstration /
  • include ltstdio.hgt
  • void main( )
  • int mts, hr
  • printf(Enter time (minutes) )
  • scanf(d, mts)
  • mts gt 60 ? hr mts mts
  • printf(\nDone!\n)

22
Selection Structure Using switch Statement
  • A switch statement is used to choose one choice
    from multiple cases and one default case.
  • Syntax
  • The break statement is needed so that once a
    case has been executed, it will skip all the
    other cases and go outside the switch statement.
    If the break statement is omitted, the execution
    will be carried out to the next alternatives
    until the next break statement is found.
  • The default clause is executed if the cases are
    not met.

switch (ControllingExpression) case constant
1 statement break case constant-n
statement break default
statement / end_switch /
23
  • The value for case must be integer or character
    constant only.
  • Examples
  • switch (number)
  • case 1
  • statement
  • break
  • switch (color)
  • case R
  • statement
  • break
  • The order of the case statement is unimportant

24
Example
ControllingExpression must be of type int or char
only
  • include ltstdio.hgt
  • void main()
  • int i
  • printf("Enter a number between 1 and 4 ")
  • scanf("d", i)
  • switch(i)
  • case 1 printf(one\n)
  • break
  • case 4 printf(four\n)
  • break
  • default
  • printf(Unrecognized number\n)
  • / end_switch /

More examples in Uckan, pp. 376 -381
25
More Example
  • include ltstdio.hgt
  • void main()
  • int major_code
  • printf("Enter your majoring code ")
  • scanf("d", major_code)
  • switch(major_code)
  • case 1
  • case 3
  • case 5 printf(Science Student\n)
  • break
  • case 2
  • case 4 printf(Art Student\n)
  • / end_switch /

26
Exercise
  • Using switch statement, write a program that
    reads a positive single-digit integer number
    between 1 to 5 (inclusive), and prints the word
    equivalent to it. For example, if the user enters
    5, the program should print the word Five to
    the screen. Please include proper input
    validation.

27
Repetition Structure
  • Used to repeat a block of statements a finite
    number of time (loop) until a certain condition
    is met without having to write the same
    statements multiple times.
  • Two design of loop
  • Counter-controlled loop depends of arithmetic
    or conditional expression.
  • Sentinel-controlled loop depends on a sentinel
    value.

28
  • Counter-controlled
  • To execute a number of instructions from the
    program for a finite, pre-determined number of
    time
  • Loop depends of arithmetic or conditional
    expression.
  • Sentinel-controlled
  • To execute a number of instructions from the
    program indifinitely until the user tells it to
    stop or a special condition is met
  • Loop depends on a sentinel value.

29
  • There are 3 types of repetition structure
  • 1. while (LoopControlExpression)
  • LoopBody-statement
  • /end_while /
  • 2. do
  • LoopBody-statement
  • while (LoopControlExpression)
  • / end_do_while /
  • 3. for (InitializationExp LoopControlExp
    UpdateExp)
  • LoopBody-statement
  • /end_for /
  • Exp Expression

while
do .. while
for
30
Repetition while Statement
NO semicolon
  • Syntax
  • As long as the condition is met (the
    LoopControlExpression returns true), the
    statement inside the while loop will always get
    executed.
  • When the condition is no longer met (the
    LoopControlExpression returns false), the program
    will continue on with the next instruction (the
    one after the while loop).

while (LoopControlExpression)
LoopBody-statement /end_while /
31
The Counter-controlled while Statement Example
  • ...
  • int total 0
  • while (total lt 5)
  • printf(Total d\n, total)
  • total
  • ...
  • Counter-controlled while loop

total is the loop counter variable In this case,
this loop will keep on looping until the counter
variable is 4. Once total 5, the loop will
terminate
32
Example
Avoid having to write the same statements
multiple times.
  • includeltstdio.hgt
  • main ( )
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • includeltstdio.hgt
  • main ()
  • int num 1
  • while(num lt5)
  • printf("Hello World\n")
  • num
  • /end_while /

33
Infinite Loop
  • If somehow the program never goes out of the
    loop, the program is said to be stuck in an
    infinite loop.
  • The infinite loop error happens because the
    LoopControlExpression of the while loop always
    return a true.
  • If an infinite loop occurs, the program would
    never terminate and the user would have to
    terminate the program by force.

34
Examples
  • includeltstdio.hgt
  • void main()
  • int i0, x0
  • while(ilt20)
  • if(i 5 0)
  • x i
  • printf("d\n", x)
  • ii1
  • / end_while /
  • printf("\nx d\n", x)

Output 0 5 15 30 x 30
35
Example
  • includeltstdio.hgt
  • define MAX 8
  • void main()
  • int f1, f2, f3
  • int count 1
  • f1f21
  • while(countltMAX)
  • printf("d\n", f1)
  • f3f1f2
  • f1f2
  • f2f3
  • countcount1
  • / end_while /

Output 1 1 2 3 5 8 13 21
36
Exercise
  • For the following code fragment
  • sum 0
  • count 7
  • while (count lt 37)
  • sum sum count
  • count count 3
  • How many times will the while loop body be
    executed?
  • What will be the values computed for the
    variables sum and count?

37
Sentinel-controlled while Statement
  • includeltstdio.hgt
  • main ()
  • int num
  • printf("Enter an integer or zero")
  • scanf("d",num)
  • while(num)
  • printf(The number is d\n",num)
  • printf("Enter an integer or zero")
  • scanf("d",num)
  • / end_while /

If value of num is nonzero, the loop control
expression is considered True.
38
Exercise
  • Write a program that calculates and prints the
    average of several integers. Assume the last
    value read is the sentinel 999. Use a while loop
    to accomplish the task.
  • Sample inputs 10 12 8 6 999
  • Expected Output
  • Average is 9

39
Repetition do while Statement
NO semicolon
  • Syntax
  • the LoopBody-statement inside it will be executed
    once no matter what. Then only the condition will
    be checked to decide whether the loop should be
    executed again or just continue with the rest of
    the program.

do LoopBody-statement while
(LoopControlExpression) / end_do_while /
Semicolon is compulsory
40
Counter-controlled do while Statement Example
  • includeltstdio.hgt
  • main ( )
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • printf(Hello World\n)
  • includeltstdio.hgt
  • main ()
  • int num 1
  • do
  • printf("Hello World\n")
  • num
  • while(num lt5) /end_do_while /

41
Output?
  • includeltstdio.hgt
  • main ()
  • int j 10
  • while(j lt 10)
  • printf(J d\n, j)
  • j
  • /end_while /
  • includeltstdio.hgt
  • main ()
  • int j 10
  • do
  • printf(J d\n, j)
  • j
  • while(j lt 10) /end_do_while /

42
Sentinel-controlled dowhile Statement Example
Sentinel value 999 will terminate the loop.
  • includeltstdio.hgt
  • main ()
  • int num
  • printf("Enter an integer or 999")
  • scanf("d",num)
  • do
  • printf("Number is d\n",num)
  • printf("Enter an integer or 999")
  • scanf("d",num)
  • while (num ! 999)
  • / end_do_while /

43
Exercise
  • Re-write the program that calculates and prints
    the average of several integers (refer the
    exercise in page 39).
  • Use a dowhile loop to accomplish the task.

44
Repetition for Statement
  • The syntax
  • InitializationExp assign initial value to a
    loop control variable
  • UpdateExp change value of the loop control
    variable at the end of
  • each loop
  • LoopControlExp the loop condition - to compute
    to True (1) or false (0)

for (InitializationExp LoopControlExp
UpdateExp) LoopBody-statement /end_for /
Semicolons are compulsory
NO semicolon
45
Counter-controlled for Statement Example
  • includeltstdio.hgt
  • main ()
  • int num
  • for (num1numlt5num)
  • printf("Hello World\n")
  • /end_for /

includeltstdio.hgt main () int num 1
while(num lt5) printf("Hello
World\n") num /end_while /
Same output!
46
Example
  • includeltstdio.hgt
  • main ()
  • int num1
  • for (numlt5num)
  • printf("Hello World\n")
  • /end_for /

Omit the InitializationExpression. Initial value
of the variable num depends on what?
47
Sentinel-controlled for Statement
  • includeltstdio.hgt
  • main ()
  • char ans
  • printf(Do you want to continue? (y/n))
  • for (scanf(c,ans) ans ! y ans ! Y
    ans ! n ans ! N scanf(c,ans))
  • // Display the following
  • printf(Please type y or n")
  • /end_for /

Display this as long as the user does not key-in
y or n.
48
Nested for Statement Example
  • includeltstdio.hgt
  • void main( )
  • int i, j
  • for(i0 ilt6 i)
  • printf("\n")
  • for(ji1 jlt6 j)
  • printf("d", j)

Output 12345 2345 345 45 5
49
More Example
  • includeltstdio.hgt
  • void main()
  • int i, j, x, y
  • printf(Enter 2 integers in the range of
    1-20")
  • scanf("d d", x, y)
  • for(i1 iltyi)
  • for(j1 jltx j)
  • printf("")
  • printf("\n")

Output Enter 2 integers in the range of 1-205
3
50
Exercises
  • 1. Modify program in the previous slide to get
    the following output
  • _at__at__at__at__at_
  • _at__at__at__at_
  • _at__at__at_
  • _at__at_
  • _at_
  • _at__at__at__at__at_
  • _at__at__at__at_
  • _at__at__at_
  • _at__at_
  • _at_
  • 0
  • 01
  • 012
  • 0123
  • 01234
  • 0123
  • 012
  • 01
  • 0

51
  • Write a program that keeps printing the
    multiples of the integers 2, namely 2, 4, 8, 16,
    32, 64 and128. Your loop should terminate at 128.
  • Use a for loop to implement this.

52
  • Write a calculator program that takes two
    (integer) numbers as input and allows the user to
    select which operation they would like to perform
    on the two numbers, either
  • Addition
  • Subtraction
  • Multiplication
  • Division
  • and display the result. Terminate the
    program when user enters n.

53
The continue and break Statements
  • Both of these statements are used to modify the
    program flow when a selection structure or a
    repetition structure is used.

54
The break Statement
  • Used to forced exit of selection or terminate
    repetition structure.

includeltstdio.hgt main () int num for
(num1numlt5num) if (num2)
break / end_if / printf("Hello
World\n") /end_for /
When the value of num is equal to 2, the program
will break out of the for loop.
Output Hello World Hello World
55
The continue Statement
  • Used to skip the rest of the loop body statements
    and continue with the next repetition of the
    loop.

includeltstdio.hgt main () int num for
(num1numlt5num) if (num2)
continue / end_if / printf(Number
d\n,num) /end_for /
When the value of num is equal to 2, the program
will skip the printf statement and continue with
the for loop.
Output Number 1 Number 3 Number 4 Number 5
56
Exercise
  • include ltstdio.hgt
  • void main()
  • int i, num, posValue 0
  • for (i0ilt10i)
  • if (num lt 0) //skip negative value
  • continue
  • / do positive elements /
  • posValue posValue num

57
Summary
  • You learned
  • Selection structures
  • One-way and two-way selection using the if
    statement
  • Multi-way selection using nested if statement and
    the switch statement
  • Repetition structures using
  • the while statement
  • do while statement
  • for statement
  • continue and break statements
Write a Comment
User Comments (0)
About PowerShow.com