Sei sulla pagina 1di 10

Problem Solving: Sum Digits

Write a function sumDigits to find the sum of


every digit in a given number n.

CS1010E Lecture 5

int sumDigits(int n);

Problem Solving with


Control Flow Statements

How to access each digit when the number of


digits is not fixed?

Henry Chia

Summing from left to right, or right to left?

hchia@comp.nus.edu.sg

Use a loop?
What is the loop termination condition?
How to generalize the statement body?

Semester 1 2011 / 2012


Department of Computer Science
School Of Computing
National University Of Singapore

CS1010E Lecture 5 p.1/40

CS1010E Lecture 5 p.3/40

Problem Solving: Sum Digits

Lecture Outline
Problem based approach to introduce more
selection and repetition constructs.

/*

Other selection constructs:


switch statement

*/
int sumDigits(int n)
{
int sum = 0;

Other repetition constructs:


do..while statement
for statement

Function sumDigits returns the sum


of the individual digits of n.

while (n > 0)
{
sum = sum + n%10;
n = n/10;
}

Count-controlled vs Sentinel-controlled input.


Shorthand operators.

return sum;
}

Programming exercises.
CS1010E Lecture 5 p.2/40

CS1010E Lecture 5 p.4/40

Problem Solving: Validate Matric


Write a function computeCheckDigit to
compute the check digit given the last 5 digits of
the matric number A00dddddX.
int computeCheckDigit(int n);

Problem Solving: Validate Matric


/*
Function computeCheckDigit returns the
check digit of num.
*/
int computeCheckDigit(int num)
{
int sum, check;

1. sum sumDigits(num)

sum = sumDigits(num);
check = 13 - sum%13;

2. checkDigit 13 sum%13

return check;
}

If matric is U0d1 d2 d3 d4 d5 , then


sum 2d1 + 6d2 + 2d3 + 4d4 + d5
CS1010E Lecture 5 p.5/40

Problem Solving: Validate Matric


Write a main function to perform the following:
1. Read a 5-digit num as input;
2. checkDigit computeCheckDigit(num);
3. Output the corresponding check letter according to the
following table.
1

E H

N R

10 11

12 13

If matric is U0d1 d2 d3 d4 d5 , use the following table.


1

10

11

12

13

Y
CS1010E Lecture 5 p.6/40

CS1010E Lecture 5 p.7/40

Problem Solving: Validate Matric


Implementing the output.
Multiple simple ifs.
if (checkDigit == 1) printf("B\n");
if (checkDigit == 2) printf("A\n");
... // other cases as if
if (checkDigit == 13) printf("Y\n");

Nested if..elses.
if (checkDigit == 1)
printf("B\n");
else if (checkDigit == 2)
printf("A\n");
... // other cases as nested if..else
else if (checkDigit == 12)
printf("X\n");
else
printf("Y\n");
CS1010E Lecture 5 p.8/40

switch Statement

switch Statement

The switch statement is used for


multiple-selection decision making.

The statements in the switch structure


usually contain the break statement.

It is often used to replace nested if..else


statements.

When the break statement is executed, the


execution of the program breaks out of the
switch structure, and continues executing
with the statement following the switch
structure.

switch (int_expression)
{
case label1: statement(s);
case label2: statement(s);

Without the break statement, the program


will execute all statements that follow the
ones selected with the case label.

// other cases
default: statements(s);
}
CS1010E Lecture 5 p.9/40

switch Statement

CS1010E Lecture 5 p.11/40

switch Statement

int_expression: An expression that is


evaluated to an integer-typed value.

Case statements determine which statements


are executed.
Case labels are unique values that
enumerate possible outcomes from the
evaluation of int_expression.
Default statement is executed if no other case
labels are satisfied.

void printCheckLetter(int checkDigit)


{
switch (checkDigit)
{
case 1 : printf("B\n");
break;
case 2 : printf("A\n");
break;
// other cases
case 12: printf("X\n");
break;
default: printf("Y\n");
}
return;
}

What if break statements are removed?


CS1010E Lecture 5 p.10/40

CS1010E Lecture 5 p.12/40

Sentinel-Controlled Input

Flowchart: while

Write a program that repeatedly reads matric


numbers as input, and prints out the check letter
for each input. The program stops when the input
is a not a valid matric number.
condition

// Assume 10000..99999 are valid


while (matric > 9999 && matric < 100000)
{
printf("Enter matric number: ");
scanf("%d", &matric);

FALSE

TRUE

looping
statement
block

checkDigit = computeCheckDigit(matric);
printCheckLetter(checkDigit);
}

A straightforward translation? Will it work?


CS1010E Lecture 5 p.13/40

CS1010E Lecture 5 p.15/40

while Statement

do..while Statement

while (condition)
{
statement(s);
}

do
{
statement(s);
} while (condition);

While the condition is TRUE, execute the statement


block and re-test the condition.
Condition must eventually become FALSE to terminate
the loop; otherwise infinite loop.

do..while loop is similar to the while loop except


that the condition is tested at the end of the loop.
do..while loop is always executed at least once.

Curly braces are not required if only one single


statement within the statement block.

Curly braces are not required if only one single


statement within the statement block.

Note the semi-colon at the end of the do..while


statement.
CS1010E Lecture 5 p.14/40

CS1010E Lecture 5 p.16/40

Priming Read

Flowchart: do..while

printf("Enter matric number: ");


scanf("%d", &matric);
while (matric > 9999 && matric < 100000)
{
checkDigit = computeCheckDigit(matric);
printCheckLetter(checkDigit);

looping
statement
block
TRUE

condition

printf("Enter matric number: ");


scanf("%d", &matric);
}

Only one condition check per input.

FALSE

In the loop body, matric validation is


performed for the ith input, but reading is
done for the (i + 1)th input.
CS1010E Lecture 5 p.17/40

Sentinel-Controlled Input

CS1010E Lecture 5 p.19/40

Count-Controlled Input
Write a program that reads from the user a
specified number, say n, then proceeds to read n
matric numbers as input, and prints out the
check letter for each input.

do
{
printf("Enter matric number: ");
scanf("%d", &matric);
if (matric > 9999 && matric < 100000)
{
checkDigit = computeCheckDigit(matric);
printCheckLetter(checkDigit);
}
} while (matric > 9999 && matric < 100000);

Realize the condition is checked twice for


every matric input.

CS1010E Lecture 5 p.18/40

1. Simplest way to read multiple inputs, although


unnatural.
2. Requires a simple loop construct, e.g. while
statement.
3. Set up a counter to count from 1 to n in order
to loop n times.
CS1010E Lecture 5 p.20/40

Count-Controlled while Loop


int count=1, n, matric, checkDigit;

for Statement
for (init; condition; update)
{
statement(s);
}

printf("Enter number of records: ");


scanf("%d", &n);

init: to initialize the loop-control variable.

while (count <= n)


{
printf("Enter matric number: ");
scanf("%d", &matric);

condition: condition that should be true to


continue looping.

checkDigit = computeCheckDigit(matric);
printCheckLetter(checkDigit);

update: specifies the modification to the


loop-control variable.

count = count + 1;

Curly braces are not required if only one


single statement within the statement block.

Is there a way to not use count at all?


CS1010E Lecture 5 p.21/40

CS1010E Lecture 5 p.23/40

for statement

Flowchart: for

Many programs require loops that are based


on the value of a variable that increments (or
decrements) by the same amount each time
through a loop.
When the variable reaches a specified value,
we will want to exit the loop.
This type of loop can be implemented as a
while loop, but it can also be easily
implemented with the for loop.

init
update
condition

FALSE

TRUE

looping
statement
block
CS1010E Lecture 5 p.22/40

CS1010E Lecture 5 p.24/40

Count-Controlled Looping

Count-Controlled for Loop

Solutions to many problems require a


pre-specified number of loops to be executed.

int count, n, matric, checkDigit;


printf("Enter number of records: ");
scanf("%d", &n);
for (count = 1; count <= n; count = count + 1)
{
printf("Enter matric number: ");
scanf("%d", &matric);
checkDigit = computeCheckDigit(matric);
printCheckLetter(checkDigit);

The following printLine function takes as


argument an integer value n and outputs n
asterisks in a single line.
void printLine(int n)
{
int i;
for (i = 1; i <= n; i++)
printf("*");
printf("\n");

return;
}
CS1010E Lecture 5 p.25/40

CS1010E Lecture 5 p.27/40

Nested Loops

Shorthand Operators
Assignment

Compound

A table of asterisks can be printed by nesting


one looping statement within another.

Increment/Decrement

Assignment
a = a + x;

a += x;

a++; (postfix increment by only 1)


++a; (prefix increment by 1 only)

a = a - x;

a -= x;

a--; (postfix decrement by 1 only)


--a; (prefix decrement by 1 only)

a = a * x;

a *= x;

a = a / x;

a /= x;

a = a % x;

a %= x;

All assignments, compound assignments, and


increment/decrement operators should preferably be
used standalone to avoid side effects.
CS1010E Lecture 5 p.26/40

// printTable prints a table of asterisks


// consisting of m rows and n columns.
void printTable(int m, int n)
{
int i, j;
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
printf("*");
printf("\n");
}
return;
}
CS1010E Lecture 5 p.28/40

Ex #1: Body Mass Index, BMI

Timeline tracing
A timeline trace shows the progress of value
changes in variables with respect to time.
Allows one to make inferences on program
behaviour.

Version 1:
int getBMIcat(double w)
{
int cat;
if
if
if
if

Example trace of printTable(2,5):

(w < 18.5)
(18.5 <= w < 25)
(25 <= w < 30)
(30 <= w)

cat
cat
cat
cat

=
=
=
=

1;
2;
3;
4;

return cat;

i 1
.
j ..
..
.

1
..
.

2
..
.

3 4
.. ..
. .

5
..
.

2
.
6 .. 1
.. .. ..
. . .

2
..
.

3
..
.

4 5
.. ..
. .

3
.
6 ..
.. ..
. .

CS1010E Lecture 5 p.29/40

Ex #1: Body Mass Index, BMI


BMI Categories are given by the following
table.
Weight, w
Description
Category
w < 18.5
Underweight
1
18.5 w < 25 Normal weight
2
25 w < 30
Overweight
3
30 w
Obese
4
Which of the following implementations of
function getBMIcat is/are correct?
CS1010E Lecture 5 p.30/40

Version 2:
int getBMIcat(double
{
if (w < 18.5)
else if (w < 25)
else if (w < 30)
else if (w >= 30)
}

w)
return
return
return
return

1;
2;
3;
4;
CS1010E Lecture 5 p.31/40

Ex #2: Greatest Common Divisor


The greatest common divisor (gcd) of two
numbers is the largest positive integer that
divides the numbers without a remainder. For
example, the gcd of 539 and 84 is 7.
The classic Euclidean Algorithm:
Let the two values be a and b.
Replace b with the result of a%b, and a
with the original value of b (before the
replacement).
Keep doing this until b becomes zero; the
value of a is the gcd.
CS1010E Lecture 5 p.32/40

Ex #2: Greatest Common Divisor


/*

Ex #3: Prime Number


int isPrime(int num)
{
int div, prime=TRUE;

Function gcd returns the greatest


common divisor of a and b.
*/
int gcd(int a, int b)
{
int r;

for (div = 2; div < num && prime; div++)


{
if (num%div == 0)
prime = FALSE;
}

while (b > 0)
{
r = a%b;
a = b;
b = r;
}

if (num == 1) // special case


return FALSE;
else
return prime;
}

return a;
}
CS1010E Lecture 5 p.33/40

CS1010E Lecture 5 p.35/40

Ex #3: Prime Number

Ex #4: Pythagorean Triple

A prime number is a positive integer greater


than one that has no positive integer divisors
other than one and itself.

A Pythagorean triple consists of three positive


integers a, b, and c, such that a2 + b2 = c2 .

Write a boolean function isPrime(num) that


returns TRUE if num is prime, FALSE
otherwise.
If num is divisible by 1 and itself, can we conclude
that num is prime?
Should we test divisibility of num with all numbers
between 1 and num?

Find the number of triples with c 100.


Start off with a nave solution first.
Require exhaustive testing.
How to enumerate all possible
combinations of a, b and c?
Develop a function countTriple that takes
an argument n and returns the number of
triples with c n.

Suppose a value d, 1 < d < num, can perfectly


divide num. What can we conclude about num?
CS1010E Lecture 5 p.34/40

CS1010E Lecture 5 p.36/40

Ex #4: Pythagorean Triple

Lecture Summary
Selection and Repetition Statements:

int countTriple(int n)
{
int a, b, c, count = 0;

Selection
if..else is the most general form.
Nested if..else for one-of-many choices.
switch for case values only.

for (c = 1; c <= n; c++)


for (b = 1; b <= n; b++)
for (a = 1; a <= n; a++)
if (c*c == a*a + b*b)
{
count++;
//debugging
printf("%d %d %d\n", a, b, c);
}

Repetition
while is the most general form.
do..while for at least one loop.
for when loop is count-controlled.
Nested loops.
Familiarity with count-controlled and sentinel-controlled
input.

return count;
}
CS1010E Lecture 5 p.37/40

Ex #4: Pythagorean Triple


Find the number of triples without duplicates.
For example, (3,4,5) and (4,3,5) are
duplicates.
Find the number of non-duplicating primitive
Pythagorean triples.
For example, (30,40,50) is not a primitive
triple, since it can be reduced to (3,4,5).
Hint: use gcd.

CS1010E Lecture 5 p.39/40

Lecture Summary
Programming Strategy
Selection
Refrain from using multiple return statements in
if..else constructs to avoid issue of complete
path coverage.
Repetition
Consider the looping condition. What makes it
continue?
Consider a generalized statement body.
Timeline tracing for nested loops.
Develop programs incrementally.

CS1010E Lecture 5 p.38/40

CS1010E Lecture 5 p.40/40

Potrebbero piacerti anche