0% found this document useful (0 votes)
8 views348 pages

CS1 Materials

Uploaded by

LiaAjah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views348 pages

CS1 Materials

Uploaded by

LiaAjah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 348

7/28/24, 6:07 PM Coursemology

https://coursemology.org/courses/2806/materials/folders/90165/ 1/1
CS1:
Programming Methodology
UNIT 1

Computational Thinking

CeNCE Computational Thinking Unit1 - 2

CeNCE programming pathway


CeNCE Computational Thinking Unit1 - 3

Unit 1: Computational Thinking


1. Computational Thinking
2. Polya’s Problem Solving Process
3. Understanding the Problem
4. Problem Formulation/Definition

CeNCE Computational Thinking Unit1 - 4

Computational Thinking
Breaking the problem into smaller,
more manageable parts.

Recognising which parts are the same


and the attributes that define them.

Filtering out info not needed and


generalising info that is needed.

Creating solutions using a series of


ordered steps.
CeNCE Computational Thinking Unit1 - 5

CT: Decomposition
Breaking the problem into smaller,
more manageable parts.

Why is this important?


 To manage and overcome complexity.
 Leads to pattern recognition and generalization.

Example:
 Baking a cake

Video:
https://www.youtube.com/watch?v=yQVTijX437c

CeNCE Computational Thinking Unit1 - 6

CT: Pattern Recognition

Recognising which parts are the same


and the attributes that define them.

Why is this important?


 Finding similarities and patterns in order to solve complex
problems more efficiently.

Example:
 Detecting and classifying whether an email is a spam

Video:
https://www.youtube.com/watch?v=SixLnIDV1yY
CeNCE Computational Thinking Unit1 - 7

CT: Abstraction
Filtering out info not needed and
generalising info that is needed.

Why is this important?


 A means to distil what is essential.
 To create models, rules, principles or theories to test predicted outcomes.
 So that one solution works for multiple problems with similar nature.
Examples:
 Google maps
 Baking a cake
Video:
https://www.youtube.com/watch?v=RdzYOtxhuDc

CeNCE Computational Thinking Unit1 - 8

CT: Algorithms
Creating solutions using a series of
ordered steps.

Why is this important?


 Algorithms are plans/procedures that can be communicated at an
abstract level and implemented on different platforms.
 Can be analysed and studied.

Example:
 A recipe to bake chocolate cake.

Video:
https://www.youtube.com/watch?v=N91oCQbWUvA
CeNCE Computational Thinking Unit1 - 9

Problem Solving
The most widely cited
reference for problem solving
in all disciplines!

George Polya
(1887 – 1985)

CeNCE Computational Thinking Unit1 - 10

Steps to Problem Solving


1. Understand the Problem 2. Make a Plan
Can you state the problem in your own words? Look for a pattern.
What are you trying to find or do? Remember related problems.
What are the unknowns? Break problem down into different parts.
What info do you obtain from the problem? Make a table, diagram or write equation.
What info, if any, is missing or not needed? Use guess and check.
Work backward.
4. Look Back Identify a subgoal.
Check the results in the original problem.
Interpret the solution in terms of the original 3. Do the Plan
problem. Does your answer make sense? Is
Implement the strategy in step 2.
it reasonable?
Check each step of the plan as you do it.
Determine whether there is another method
of finding the solution. Keep an accurate record of your work.
If possible, determine other related or more Organize your work into easy to
general problems for which the techniques understand visuals.
will work. Double check your math work.
CeNCE Computational Thinking Unit1 - 11

Develop habit of ASKING


1. Understand the Problem
Can you state the problem in your own words?
What are you trying to find or do?
What are the unknowns?
What info do you obtain from the problem?
What info, if any, is missing or not needed?

Do not just understand the solution;


Understand how and why of getting the solution.
Do I understand the problem?
Do I understand the solutions?
Why does the solution work?
Why did he do it like that?
How can I invent such a solution?
Can I do it differently?

CeNCE Computational Thinking Unit1 - 12

How hard can “understanding the problem” be?


(1) The Hungry Bear Problem

Oh no! Run!
CeNCE Computational Thinking Unit1 - 13

How hard can “understanding the problem” be?


(1) The Hungry Bear Problem

But you Let me put on my


can’t outrun running shoes.
a bear!

CeNCE Computational Thinking Unit1 - 14

How hard can “understanding the problem” be?


(1) The Hungry Bear Problem

I only need to
@*%$#! outrun you!

Perceived problem: How to outrun the bear.

Right problem: How to outrun your companion!


CeNCE Computational Thinking Unit1 - 15

How hard can “understanding the problem” be?


(2) Bargain Buy
Observation: A particular brand is
selling very well elsewhere but not
in this store.

Perceived problem: Price


not competitive.

$5.50 Solution: Reduce the price.


$5.00
Observation: Still not selling well.
$4.50
Solution: Reduce the price further.

Observation: Still not selling well!

CeNCE Computational Thinking Unit1 - 16

How hard can “understanding the problem” be?


(2) Bargain Buy

Real problem: Item not


prominently displayed!

Solution: Display item at


prominent location.
$5.50
$5.00
$4.50
CeNCE Computational Thinking Unit1 - 17

Problem Definition
Guidelines for good problem definition
Clear, concise, unambiguous.

Capture all relevant information


 What are the inputs (data)?
 What are the outputs (unknowns)?
 What are the constraints?
 Connection/relationship between inputs
and outputs?

CeNCE Computational Thinking Unit1 - 18

Problem Definition
Verifying your problem definition
Is a solution possible?
Is a solution desirable?

Is there a trivial undesirable solution?


Do the constraints conflict?

Anything missing?
Anything extraneous?
CeNCE Computational Thinking Unit1 - 19

Example #1: Tourist Problem


Verbal statement:
Given a group of tourists, each with a list of places to visit,
schedule bus trips so that each tourist gets to visit all
the places in his/her list.
Tourist Places of Interest
Aaron SZG, BG, JB
Betty CG, JG, BG
Cathy VC, SI, OR
David JG, CG, OR
Evans CG, JG, SZG
Frances BG, SZG, JB
Gary CG, OR
Harry JG, CG
An instance of the tourist problem

CeNCE Computational Thinking Unit1 - 20

Example #1: Tourist Problem


Problem definition (first attempt):
 Inputs: A list of tourists, each with a list of places to visit.
 Outputs: Bus trips.
Tourist Places of Interest
Is this good enough? Aaron SZG, BG, JB
Betty CG, JG, BG
Cathy VC, SI, OR
David JG, CG, OR
Evans CG, JG, SZG
Frances BG, SZG, JB
Gary CG, OR
Harry JG, CG
An instance of the tourist problem
CeNCE Computational Thinking Unit1 - 21

Example #1: Tourist Problem


Revised problem definition:
 Inputs: A list of tourists, each with a list of places to visit.
 Outputs: A list of bus trips, each with a list of places to
visit, and the tourists visiting.
 Constraints: Each tourist gets to visit all the places in
his/her list.

Happy tourists

CeNCE Computational Thinking Unit1 - 22

Example #1: Tourist Problem


Revised problem definition:
 Inputs: A list of tourists, each with a list of places to visit.
 Outputs: A list of bus trips, each with a list of places to visit, and the tourists
visiting.
 Constraints: Each tourist gets to visit all the places in his/her list.

Is a solution possible/desirable?
A no-brainer solution:

One bus for each tourist!

Unhappy boss
CeNCE Computational Thinking Unit1 - 23

Example #1: Tourist Problem


Revised problem definition:
 Inputs: A list of tourists, each with a list of places to visit.
 Outputs: A list of bus trips, each with a list of places to visit, and the tourists
visiting.
 Constraints: Each tourist gets to visit all the places in his/her list.
 Constraints:
 Each tourist gets to visit all the places in his/her list.
 Each tourist visits at most one place per day.
 Fewest possible days.
 At most one bus trip to each place.

Happy tourists Happy boss

CeNCE Computational Thinking Unit1 - 24

Example #1: Tourist Problem


 Revised constraints:
 Each tourist gets to visit all the places in his/her list.
 Each tourist visits at most one place per day.
 Fewest possible days.
 At most one bus trip to each place.
Tourist Places of Interest
 Each bus takes at most 4 tourists.
Aaron SZG, BG, JB
Betty CG, JG, BG
Do the constraints conflict? Cathy VC, SI, OR
David JG, CG, OR
Evans CG, JG, SZG
Frances BG, SZG, JB
Gary CG, OR
Harry JG, CG
CeNCE Computational Thinking Unit1 - 25

Lessons Learned
Verbal statements can be vague.

Constraints may be implicit.

Without constraints, may get trivial but


undesirable solution.

When constraints conflict, no solution.

Use Polya’s questions to guide your reasoning.

CeNCE Computational Thinking Unit1 - 26

Example #2: Cube in Pyramid


Verbal statement:
What is the largest cubical space in a
square-base pyramid?
(Or, what is the largest cubical box
we can put inside a square-base
pyramid?)
CeNCE Computational Thinking Unit1 - 27

Example #2: Cube in Pyramid


Problem definition:
 Inputs (data):
 Square-base pyramid with base width b and height h.
 Outputs (unknowns):
 Cube of width w.
 Constraints (conditions):
 Base of cube rests on base of pyramid.
 Top 4 corners of cube touch some surfaces of the pyramid.

Too hard!
What do you do when a problem
looks too hard?

CeNCE Computational Thinking Unit1 - 28

Example #2: Cube in Pyramid


Simplified problem definition in 2D:
 Inputs (data):
 Triangle with base width b and height h.
 Outputs (unknowns):
 Square of width w.
 Constraints (conditions):
 Base of square rests on base of triangle.
 Top 2 corners of square touch some
edges of the triangle.

Still too hard!


CeNCE Computational Thinking Unit1 - 29

Example #2: Cube in Pyramid


More simplified problem definition in 2D:
 Inputs (data):
 Triangle with base width b and height h.
 Outputs (unknowns):
 Square of width w.
 Constraints (conditions):
 Base of square rests on base of triangle.
 Top 1 corner of square touches an edge
of the triangle.

CeNCE Computational Thinking Unit1 - 30

Example #2: Cube in Pyramid


The more simplified problem is so simple
it has many simple solutions!

Can you see the solution of the


original problem now?
CeNCE Computational Thinking Unit1 - 31

Example #2: Cube in Pyramid


Polya heuristic:
After solving simpler problem, generalize.

Generalized problem:
What is the largest rectangular
block in a rectangular-base
pyramid?

CeNCE Computational Thinking Unit1 - 32

Lesson Learned

Generalized
problem

Generalize Simplify, if too hard

Simplified
problem

Solve it
CeNCE Computational Thinking Unit1 - 33

End of File

CeNCE Algorithmic Problem Solving Unit2 - 1

CS1:
PROGRAMMING METHODOLOGY

UNIT 2

Algorithmic Problem Solving


CeNCE Algorithmic Problem Solving Unit2 - 2

Unit 3: Algorithmic Problem Solving

1. Computational Thinking: Coin Change


2. Euclid’s Algorithm
3. Algorithmic Problem Solving Process
4. Algorithm
5. Control Structures
6. Examples of Pseudocodes

CeNCE Algorithmic Problem Solving Unit2 - 3

Coin Change
Problem statement
Given the above coin denominations: 1¢, 5¢, 10¢, 20¢, 50¢, and
$1, assuming that you have unlimited supply of them, find the
minimum number of coins needed for a given amount.

This is called optimisation problem in CS –


finding the best among all possible solutions.
Examples:
 375¢  ? coins Question you may ask:
 543¢  ? coins Do I need to report how many
coins of each denomination in
my solution?
No, you don’t have to. (But in the process of computing
the solution you will somehow get to know how many
coins of each denomination you need.)

CeNCE Algorithmic Problem Solving Unit2 - 4

Contract of a Task
The Task Giver The Task Solver

The amount (in ¢)

The min. no. of coins

The Task Giver: The Task Solver:


 Provides the necessary inputs  Accepts the necessary inputs
(arguments) to the Task Solver (arguments) from the Task Giver
 Does not provides unnecessary  Returns the result to the Task
data to the Task Solver Giver
 Does not care/need to know how  Does not provides extraneous
the Task Solver solves the task data to the Task Giver or
perform extraneous work

CeNCE Algorithmic Problem Solving Unit2 - 5

Euclid’s Algorithm (1/3)


 First historically documented algorithm by Greek
mathematician Euclid in 300 B.C.
 Also known as Euclidean Algorithm
 q is not important;
1. Let A and B be integers with A > B ≥ 0. r is the one that
2. If B = 0, then the GCD is A and algorithm ends. matters.
3. Otherwise, find q and r such that  r could be obtained
A = q.B + r where 0 ≤ r < B by A modulo B (i.e.
remainder of A / B)
4. Replace A by B, and B by r. Go to step 2.
 Assumption on A > B
unnecessary

 We will rewrite the


algorithm
CeNCE Algorithmic Problem Solving Unit2 - 6

Euclid’s Algorithm (2/3)


1. Let A and B be integers with A > B ≥ 0.
2. If B = 0, then the GCD is A and algorithm ends.
3. Otherwise, find q and r such that
Rewritten in modern form
A = q.B + r where 0 ≤ r < B // Pre-cond: A and B are non-negative
// integers, but not both zeroes.
4. Replace A by B, and B by r. Go to step 2.

Algorithm GCD( A, B ) {
while (B > 0) {
What the Task Giver Details of Task r  A modulo B
must provide to this Solver unknown to AB
Task Solver Task Giver Br
}
return A
} Pre-condition: What
must be true for this
What this Task Solver Task Solver to work.
returns to the Task Giver.

CeNCE Algorithmic Problem Solving Unit2 - 7

Euclid’s Algorithm (3/3)


You might have guess what this algorithm does from its
name but let’s trace it with some examples.
Very important skill!

// Pre-cond: A and B are non-negative Let’s trace GCD(12, 42)


// integers, but not both zeroes.
(B > 0)? r A B
Algorithm GCD(A, B) { 12 42
while (B > 0) { true 12 42 12
r  A modulo B true 6 12 6
AB
So do you know what true 0 6 0
Br
does the Euclid’s false
} Algorithm do now?
return A Result returned: ?
}


CeNCE Algorithmic Problem Solving Unit2 - 8

Polya’s Problem Solving Process


We (roughly)map Polya’s steps to algorithmic problem solving.

1. Understand the Analysis


Problem

2. Make a Plan
Design Iterative
process

3. Do the Plan Implementation

4. Look back Testing

CeNCE Algorithmic Problem Solving Unit2 - 9

Algorithmic Problem Solving

Determine
problem features Analysis

Write algorithm Design Iterative


process

Write code Implementation What is an


algorithm?

Check for correctness


and efficiency Testing
CeNCE Algorithmic Problem Solving Unit2 - 10

Algorithm (1/3)
 An algorithm is a well-defined computational
procedure consisting of a set of instructions,
that takes some value or set of values as
input, and produces some value or set of
values as output.

Input Algorithm Output

‘Algorithm’ stems from ‘Algoritmi’, the Latin form of al-


Khwārizmī, a Persian mathematician, astronomer and geographer.
Source: http://en.wikipedia.org/wiki/Algorithm

CeNCE Algorithmic Problem Solving Unit2 - 11

Algorithm (2/3)
 An algorithm has these properties:
The
Each step
algorithm
must be exact.
(Or it will not be
must
precise.)
Exact Terminate terminate.
(Or no solution
will be obtained.)
The
algorithm The algorithm
must be must be
Effective General
effective. general.
(i.e. it must solve (Within the
the problem.) constraints of the
system/language.)
CeNCE Algorithmic Problem Solving Unit2 - 12

Algorithm (3/3)
 Ways of representing an algorithm:
Flowchart Pseudocode

lynda.com

CeNCE Algorithmic Problem Solving Unit2 - 13

Algorithm: Example #1
CeNCE Algorithmic Problem Solving Unit2 - 14

Algorithm: Example #2 (1/2)


 Find maximum and average of a list of numbers:
Terminator box
start
Flowchart
Process box
sum  count  0
max  0
Decision box

Yes end of
input?

No

Enter num
increment count
ave  sum/count sum  sum + num

print max, ave Yes


num > max? max  num

No
end

CeNCE Algorithmic Problem Solving Unit2 - 15

Algorithm: Example #2 (2/2)


 Find maximum and average of a list of numbers:
Pseudocode The need to initialise variables.

sum  count  0 // sum = sum of numbers


// count = how many numbers are entered?
max  0 // max to hold the largest value eventually
for each num entered,
count  count + 1
sum  sum + num The need to indent.
if num > max
then max  num

ave  sum / count Are there any errors


in this algorithm?
print max, ave
CeNCE Algorithmic Problem Solving Unit2 - 16

Algorithm: Pseudocode
 We will write algorithms in pseudocode instead of
flowchart as the former is more succinct
 However, unlike programming languages, there are
no standard rules on how pseudocodes should look
like
 General guidelines:
 Every step must be unambiguous, so that anybody is able
to hand trace the pseudocode and follow the logic flow
 Use a combination of English (but keep it succinct) and
commonly understood notations (such as  for assignment
in our previous example)
 Use indentation to show the control structures

CeNCE Algorithmic Problem Solving Unit2 - 17

Control Structures (1/2)


 An algorithm is a set of instructions, which are
followed sequentially by default.
 However, sometimes we need to change the
default sequential flow.
 We study 3 control structures.
CeNCE Algorithmic Problem Solving Unit2 - 18

Control Structures (2/2)

Sequence • Default

True False
• Also called ?
Selection branching

• Also called False


Repetition loop
?
True

CeNCE Algorithmic Problem Solving Unit2 - 19

Control Structures: Sequence (1/2)


 Task: Compute the average of three integers
A possible algorithm: Variables used:
num1 num2 num3
enter values for num1, num2, num3
ave  ( num1 + num2 + num3 ) / 3
ave
print ave

Variables used:
Another possible algorithm:
num1 num2 num3
enter values for num1, num2, num3
total  ( num1 + num2 + num3 ) total
ave  total / 3
print ave ave

Each box represents a variable.


Important concepts: Each variable has
a unique name and contains a value.
CeNCE Algorithmic Problem Solving Unit2 - 20

Control Structures: Sequence (2/2)


 Task: Compute the average of three integers
 How the program might look like Unit2_prog1.c
// This program computes the average of 3 integers
#include <stdio.h>
Don’t worry about the C syntax; we will
discuss it next week. For now, just to show
int main(void) { you how the algorithm is translated into the
int num1, num2, num3; code. The logic remains the same, but you
float ave; need to write the code according to the
rules of the programming language.
printf("Enter 3 integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

ave = (num1 + num2 + num3) / 3.0;


printf("Average = %.2f\n", ave);

return 0;
}

CeNCE Algorithmic Problem Solving Unit2 - 21

Control Structures: Selection (1/3)


True False
?

 Task: Arrange two integers in ascending order (sort)


Algorithm A:
enter values for num1, num2 Variables
// Assign smaller number into final1, used:
// and larger number into final2 num1 num2
if (num1 < num2)
then final1  num1 final1 final2
final2  num2
else final1  num2
final2  num1
// Transfer values in final1, final2 back to num1, num2
num1  final1
num2  final2
// Display sorted integers
print num1, num2
CeNCE Algorithmic Problem Solving Unit2 - 22

Control Structures: Selection (2/3)


True False
?

 Task: Arrange two integers in ascending order (sort)

Algorithm B:
enter values for num1, num2 Variables
used:
// Swap the values in the variables if necessary
if (num2 < num1) num1 num2

then temp  num1


temp
num1  num2
num2  temp
// Display sorted integers
print num1, num2

Compare Algorithm A with Algorithm B.

CeNCE Algorithmic Problem Solving Unit2 - 23

Control Structures: Selection (3/3)


True False
?

 How the program might look like for Algorithm B


Unit2_prog2.c
// This program arranges 2 integers in ascending order
#include <stdio.h>

int main(void) {
int num1, num2, temp;

printf("Enter 2 integers: ");


scanf("%d %d", &num1, &num2);

if (num2 < num1) {


temp = num1; num1 = num2; num2 = temp;
}
printf("Sorted: num1 = %d, num2 = %d\n", num1, num2);

return 0;
}
CeNCE Algorithmic Problem Solving Unit2 - 24

False

Control Structures: Repetition (1/3)


?
True

 Task: Find sum of positive integers up to n (assume n>0)


Algorithm:
enter value for n Variables
// Initialise a counter count to 1, and ans to 0 used:
count  1 n
ans  0
while (count ≤ n) do count
ans  ans + count // add count to ans
count  count + 1 // increase count by 1 ans

// Display answer
print ans

Initialisation is
very important!

CeNCE Algorithmic Problem Solving Unit2 - 25

False

Control Structures: Repetition (2/3)


?
True

 Important to trace pseudocode to check its correctness


Algorithm: Assume user enters 3 for n.
enter value for n
(count <= n)? count ans
count  1
ans  0 1 0

while (count ≤ n) do true 2 1


ans  ans + count true 3 3
count  count + 1 true 4 6
// Display answer false
print ans
Output: 6
CeNCE Algorithmic Problem Solving Unit2 - 26

False

Control Structures: Repetition (3/3)


?
True

 How the program might look like


Unit2_prog3.c
// Computes sum of positive integers up to n
#include <stdio.h>
int main(void) {
int n; // upper limit
int count = 1, ans = 0; // initialisation
printf("Enter n: ");
scanf("%d", &n);
while (count <= n) {
ans += count;
count++;
}
printf("Sum = %d\n", ans);
return 0;
}

CeNCE Algorithmic Problem Solving Unit2 - 27

Coin Change
Problem statement
Given the above coin denominations: 1¢, 5¢, 10¢, 20¢, 50¢, and $1,
assuming that you have unlimited supply of them, find the minimum
number of coins needed for a given amount.
 Can you write out the pseudocode of your algorithm?
 What must the Task Giver send to the Task Solver?
 What must the Task Solver return to the Task Giver?

Algorithm CoinChange(amt) {

...

return coins
}
CeNCE Algorithmic Problem Solving Unit2 - 28

Knowing the algorithmic problem solving process

Knowing the properties of an algorithm

Knowing the three control structures

Knowing how to write algorithms in pseudocode

Knowing how to trace algorithms to verify their correctness

CeNCE Algorithmic Problem Solving Unit2 - 29

End of File
CeNCE Overview of C Programming Unit3 - 1

CS1:
PROGRAMMING METHODOLOGY

UNIT 3
Overview of C Programming

CeNCE Overview of C Programming Unit3 - 2

Unit 3: Overview of C Programming


1. A Simple C Program
2. Variables and Data Types
3. Program Structure
 Preprocessor directives
 Input
 Compute
 Output
4. Math Functions
5. Programming Style
6. Common Mistakes
CeNCE Overview of C Programming Unit3 - 3

Introduction
 C: A general-purpose computer programming
language developed in 1972 by Dennis Ritchie
(1941 – 2011) at Bell Telephone Lab for use
with the UNIX operation System
 We will follow the ANSI C (C99) standard
https://en.wikipedia.org/wiki/ANSI_C#C99

CeNCE Overview of C Programming Unit3 - 4

Quick Review: Edit, Compile, Execute


Edit Compile

Test, test, and test!


Execute
Source code
Edit produces
first.c
eg: vim first.c

Executable code
Compile produces
a.out Cannot
eg: gcc first.c
compile?

Program output Incorrect


Execute produces result?
The value of c is 3.
eg: a.out
CeNCE Overview of C Programming Unit3 - 5

Quick Review: Edit, Compile, Execute


Edit Compile

Test, test, and test!


Execute
Source code
Edit produces
first.cpp
eg: vim first.cpp

Executable code
Compile produces
a.out Cannot
eg: g++ first.cpp
compile?

Program output Incorrect


Execute produces result?
The value of c is 3.
eg: a.out

CeNCE Overview of C Programming Unit3 - 6

A Simple C Program (1/3)


 General form of a simple C program

preprocessor directives
main function header
{
declaration of variables
executable statements
} “Executable statements”
usually consists of 3 parts:
 Input data
 Computation
 Output results
© CeNCE Overview of C Programming Unit3 - 7

A Super Simple C Program Edit Compile

 Use vim to create this C program first.c


Execute
#include <stdio.h>
preprocessor directives
int main(void) {
main function header
printf(“ @..@\n”);

return 0;
}

declaration of variables

executable statements

© CeNCE Overview of C Programming Unit3 - 8

The Less Simple C Program Edit Compile

Execute

#include <stdio.h>
#include <IOStream> // to use C++ I/O
using namespace std; // to use C++
int main(void) {
int a,b,c;
a = 2001;
b = 4002;
c = a + b;
printf(“ The value of %d + %d = %d\n”,a,b,c);
cout << “The value of “;
cout << 2001 << “ + “ << 4002 << ‘=‘ << c << endl;
return 0;
}
© CeNCE Overview of C Programming Unit3 - 9

A Simple C Program (1/3)


 General form of a simple C program

preprocessor directives
main function header
{
declaration of variables
executable statements
} “Executable statements”
usually consists of 3 parts:
 Input data
 Computation
 Output results

© CeNCE Overview of C Programming Unit3 - 10

The Less Simple C Program Edit Compile

 Use an editor to create this C program first.c


Execute
#include <stdio.h>
preprocessor directives
int main(void) { main function header
int a,b,c;
a = 2001;
b = 4002;
c = a + b; declaration of variables
printf(“ The value of %d + %d = %d\n”,a,b,c);
return 0;
}

executable statements
© CeNCE Overview of C Programming Unit3 - 11

The Less Simple C Program Edit Compile

Declared 3 variables,Execute
their
#include <stdio.h>
names are a,b and c
int main(void) {
int a,b,c; put the value 2001 into a
a = 2001;
b = 4002; a
c = a + b;
printf(“ The value of %d + %d = %d\n”,a,b,c); 2001
return 0;
}
b
4002

Read the data in a and b, add c


them and put the sum in c 6003

CeNCE Overview of C Programming Unit3 - 12

A Simple C++ Program (2/3)


Unit3_MileToKm.cpp
// Converts distance in miles to kilometres.
#include <iostream> /* cin, cout definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */

int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometres

/* Get the distance in miles */


cout << "Enter distance in miles: ");
cin >> miles;

// Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

// Display the distance in kilometres


cout << "That equals “ << kms << “km” << endl;
Sample run
return 0;
$ g++ –Wall Unit3_MileToKm.c
}
$ a.out
Enter distance in miles: 10.5
That equals 16.89 km.
CeNCE Overview of C Programming Unit3 - 13

A Simple C Program (3/3)


// Converts distance in miles to kilometres.
standard header file
preprocessor #include <iostream> /* cin, cout definitions */
directives #define KMS_PER_MILE 1.609 /* conversion constant */
Using namespace std;
constant
int main(void) {
float miles, // input – distance in miles
reserved
words kms; // output – distance in kilometres

/* Get the distance in miles */


variables cout << "Enter distance in miles: “; comments
cin >> miles;
functions
// Convert the distance to kilometres
kms = KMS_PER_MILE * miles;
special // Display the distance in kilometres
symbols cout << "That equals “ << kms;
cout << “ in kms” << endl;;

return 0; punctuations
}

CeNCE Overview of C Programming Unit3 - 14

What Happens in the Computer Memory


memory memory memory

Executable code of Executable code of Executable code of


Unit3_MileToKm.c Unit3_MileToKm.c Unit3_MileToKm.c

miles miles miles


? 10.5 10.5

kms kms kms


? ? 16.89

At the beginning
After user enters: 10.5 to After this line is executed:
Do not assume that
uninitialised variables scanf("%f", &miles); kms = KMS_PER_MILE * miles;
contain zero! (Very
common mistake.)
CeNCE Overview of C Programming Unit3 - 15

Variables
 Data used in a program are stored in variables
 Every variable is identified by a name (identifier), has a
data type, and contains a value which could be modified
 (Each variable actually has an address too, but for the
moment we will skip this, until we discuss pointers.)
 A variable is declared with a data type
 Eg: int count; // variable ‘count’ of type ‘int’

 Variables may be initialized during declaration:


 Eg: int count = 3; // count is initialized to 3

 Without initialization, the variable contains an unknown


value (Cannot assume that it is zero!)

© CeNCE Overview of C Programming Unit3 - 16

What if Edit Compile

Execute
#include <iostream>
using namespace std;
int main(void) {
int a,b,c;

b = 4002; a
c = a + b;
cout << “ The value of << a << “ + “;
cout << b << “ = “ << c << endl;
return 0;
b
} 4002

Read the data in a and b, add c


them and put the sum in c ?
CeNCE Overview of C Programming Unit3 - 17

Variables: Mistakes in Initialization


 No initialization
int count;

count = count + 12; Does ‘count’ contain 12


after this statement?

 Redundant initialization
int count = 0;
Initialization here
count = 123; is redundant.

© CeNCE Overview of C Programming Unit3 - 18

The Less Simple C Program Edit Compile

Declared 3 variables,Execute
their
#include <stdio.h>
names are a,b and c
int main(void) {
int a,b,c; put the value 2001 into a
a = 2001;
b = 4002; a
c = a + b;
printf(“ The value of %d + %d = %d\n”,a,b,c); 2001
return 0;
}
b

And the variable a, b, c are storing


integers c
Can we do a = 0.1?
CeNCE Overview of C Programming Unit3 - 19

Data Types
 To determine the type of data a variable may hold
Integer
and Char

Float

http://www.tutorialspoint.com/cprogramming/c_data_types.htm

CeNCE Overview of C Programming Unit3 - 20

Notes (1/2)
 Basic steps of a simple program
1. Read inputs (cin/scanf)
2. Compute
3. Print outputs (cout/printf)
 For now we will use interactive inputs
 Standard input stream (stdin) – default is keyboard
 Use the cin/scanf() function
 Assume input data always follow specification
 Hence no need to validate input data (for now)
 Outputs
 Standard output stream (stdout) – default is monitor
 Use the cout/printf() function
CeNCE Overview of C Programming Unit3 - 21

Notes (2/2)
 Include header file <stdio.h> to use scanf() and
printf(), include header file <iostream> to use
cin and cout.
 Include the header file (for portability sake) even
though some systems do not require this to be done
 Important! (Coursemology issue)
 Make sure you have a newline character (‘\n’) at the
end of your last line of output, or CodeCrunch may
mark your output as incorrect.
printf("That equals %9.2f km.\n", kms);
cout << "That equals “;
cout << kms << “ km” << endl;

CeNCE Overview of C Programming Unit3 - 22

Type of Errors Easiest to spot – the


 Syntax errors (and warnings) compiler helps you!
 Program violates syntax rules
 Warning happens, for example, incomparable use of types for
output
 Advise to use gcc –Wall to compile your programs
 Run-time errors Moderately easy to spot
 Program terminates unexpectedly due to illegal operations, such
as dividing a number by zero, or user enters a real number for an
integer data type
 Logic errors Hard to spot
 Program produces incorrect result
 Undetected errors May never be spotted!
 Exist if we do not test the program thoroughly enough
The process of correcting errors in programs is
called debugging.
This process can be very time-consuming!
CeNCE Overview of C Programming Unit3 - 23

Program Structure
 A basic C program has 4 main parts:
 Preprocessor directives:
 eg: #include <stdio.h>, #include <math.h>, #define PI 3.142
 Input: through stdin (using cin/scanf), or file input
 Compute: through arithmetic operations
 Output: through stdout (using cout/printf), or file output
We will learn
file input/output
later.

CeNCE Overview of C Programming Unit3 - 24

Program Structure: Preprocessor Directives (1/2)


Preprocessor
 The C preprocessor provides the following Input
Compute
 Inclusion of header files Output

 Macro expansions
 Conditional compilation
 For now, we will focus on inclusion of header files and simple
application of macro expansions
 Inclusion of header files
 To use input/output functions such as scanf() and printf(), you
need to include <stdio.h>: #include <stdio.h>
 To use mathematical functions, you need to include <math.h>:
#include <math.h>
CeNCE Overview of C Programming Unit3 - 25

Program Structure: Preprocessor Directives (2/2)


Preprocessor
 Macro expansions Input
Compute
 One of the uses is to define a macro for a constant value Output

 Eg: #define PI 3.142 // use all CAP for macro


#define PI 3.142 Preprocessor replaces all instances
of PI with 3.142 before passing the
int main(void) { program to the compiler.
...
areaCircle = PI * radius * radius;
volCone = PI * radius * radius * height / 3.0;
}

What the compiler sees:


int main(void) {
...
areaCircle = 3.142 * radius * radius;
volCone = 3.142 * radius * radius * height / 3.0;
}

CeNCE Overview of C Programming Unit3 - 26

Preprocessor

Program Structure: Input/Output (1/3)


Input
Compute
Output

 Input/output statements:
age Address of variable
 printf ( format string, print list ); ‘age’ varies each
20
 printf ( format string ); time a program is
run.
 scanf( format string, input list );
One version: “age” refers to value in the variable age.
int age; “&age” refers to (address of) the memory
double cap; // cumulative average cell where the value of age is stored.
point
printf("What is your age? ");
scanf("%d", &age);
printf("What is your CAP? ");
scanf("%lf", &cap);
printf("You are %d years old, and your CAP is %f\n", age, cap);
Unit3_InputOutput.c
Another version:
int age;
Unit3_InputOutputV2.c
double cap; // cumulative average point
printf("What are your age and CAP? ");
scanf("%d %lf", &age, &cap);
printf("You are %d years old, and your CAP is %f\n", age, cap);
CeNCE Overview of C Programming Unit3 - 27

Preprocessor

Program Structure: Input/Output (2/3)


Input
Compute
Output

 %d and %lf are examples of format specifiers; they are placeholders


for values to be displayed or read
Placeholder Variable Type Function Use
%c char printf / scanf
%d int printf / scanf
%f float or double printf
%f float scanf
%lf double scanf
%e float or double printf (for scientific notation)
 Examples of format specifiers used in printf():
 %5d: to display an integer in a width of 5, right justified
 %8.3f: to display a real number (float or double) in a width of 8, with 3
decimal places, right justified
 Note: For scanf(), just use the format specifier without indicating
width, decimal places, etc.

CeNCE Overview of C Programming Unit3 - 28

Preprocessor

Program Structure: Input/Output (3/3)


Input
Compute
Output

 \n is an example of escape sequence


 Escape sequences are used in printf() function for certain special
effects or to display certain characters properly
 See Table 1.4 (pages 32 – 33)
 These are the more commonly used escape sequences:
Escape Meaning Result
sequence
\n New line Subsequent output will appear on the next line
\t Horizontal tab Move to the next tab position on the current line
\" Double quote Display a double quote "
%% Percent Display a percent character %
CeNCE Overview of C Programming Unit3 - 29

Exercise #2: Testing scanf() and printf()


 We will do an exercise in class to explore scanf()
and printf() functions
 Unit3_TestIO.c
 You can find the above program in
Coursemology -> Material -> program codes

CeNCE Overview of C Programming Unit3 - 30

Exercise #3: Distance Conversion (1/2)


 Convert distance from miles to kilometres
 Unit3_MileToKm.c
 The program is given (which you can copy to your
directory as earlier instructed), but for this exercise we
want you to type in the program yourself as a practice
in using vim
 The program is shown in the next slide
CeNCE Overview of C Programming Unit3 - 31

Exercise #3: Distance Conversion (2/2)


Unit3_MileToKm.c
// Unit3_MileToKm.c
// Converts distance in miles to kilometers.
#include <stdio.h>
#define KMS_PER_MILE 1.609

int main(void) {
float miles, // input - distance in miles.
kms; // output - distance in kilometers

/* Get the distance in miles */


printf("Enter distance in miles: ");
scanf("%f", &miles);

// Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

// Display the distance in kilometres


printf("That equals %9.2f km.\n", kms);

return 0;
}

CeNCE Overview of C Programming Unit3 - 32

Preprocessor

Program Structure: Compute (1/9)


Input
Compute
Output

 Computation is through function


 So far, we have used one function: int main(void)
main() function: where execution of program begins

 A function body has two parts


 Declarations statements: tell compiler what type of memory cells
needed
 Executable statements: describe the processing on the memory
cells
int main(void) {
/* declaration statements */
/* executable statements */
return 0;
}
CeNCE Overview of C Programming Unit3 - 33

Preprocessor

Program Structure: Compute (2/9)


Input
Compute
Output

 Declaration Statements: To declare use of variables


int count, value;
Data type Names of variables

 User-defined Identifier
 Name of a variable or function
 May consist of letters (a-z, A-Z), digits (0-9) and underscores (_),
but MUST NOT begin with a digit
 Case sensitive, i.e. count and Count are two distinct identifiers
 Guideline: Usually should begin with lowercase letter
 Must not be reserved words (next slide)
 Should avoid standard identifiers (next slide)
 Eg: Valid identifiers: maxEntries, _X123, this_IS_a_long_name
Invalid: 1Letter, double, return, joe’s, ice cream, T*S

CeNCE Overview of C Programming Unit3 - 34

Preprocessor

Program Structure: Compute (3/9)


Input
Compute
Output

 Reserved words (or keywords)


 Have special meaning in C
 Eg: int, void, double, return
 Complete list: http://c.ihypress.ca/reserved.html
 Cannot be used for user-defined identifiers (names of variables or
functions)
 Standard identifiers
 Names of common functions, such as printf, scanf
 Avoid naming your variables/functions with the same name of
built-in functions you intend to use
CeNCE Overview of C Programming Unit3 - 35

Preprocessor

Program Structure: Compute (4/9)


Input
Compute
Output

 Executable statements
 I/O statements (eg: printf, scanf)
 Computational and assignment statements
 Assignment statements
 Store a value or a computational result in a variable
 (Note: ‘=’ means ‘assign value on its right to the variable on
its left’; it does NOT mean equality)
 Left side of ‘=’ is called lvalue

Eg: kms = KMS_PER_MILE * miles;

CeNCE Overview of C Programming Unit3 - 36

Preprocessor

Program Structure: Compute (5/9)


Input
Compute
Output

Eg: sum = sum + item;

 Note: lvalue must be


assignable

 Examples of invalid assignment (result in compilation error “lvalue


required as left operand of assignment”):
 32 = a; // ’32’ is not a variable
 a + b = c; // ‘a + b’ is an expression, not variable
 Assignment can be cascaded, with associativity from right to left:
 a = b = c = 3 + 6; // 9 assigned to variables c, b and a
 The above is equivalent to: a = (b = (c = 3 + 6));
which is also equivalent to:
c = 3 + 6;
b = c;
a = b;
CeNCE Overview of C Programming Unit3 - 37

Preprocessor

Program Structure: Compute (6/9)


Input
Compute
Output

 Side Effect:
 An assignment statement does not just assigns, it also has the
side effect of returning the value of its right-hand side
expression
 Hence a = 12; has the side effect of returning the value of 12,
besides assigning 12 to a
 Usually we don’t make use of its side effect, but sometimes we
do, eg:
z = a = 12; // or z = (a = 12);
 The above makes use of the side effect of the assignment
statement a = 12; (which returns 12) and assigns it to z
 Side effects have their use, but avoid convoluted codes:
a = 5 + (b = 10); // assign 10 to b, and 15 to a
 Side effects also apply to expressions involving other operators
(eg: logical operators). We will see more of this later.

CeNCE Overview of C Programming Unit3 - 38

Preprocessor

Program Structure: Compute (7/9)


Input
Compute
Output

 Arithmetic operations
 Binary Operators: +, –, *, /, % (modulo or remainder)
 Left Associative (from left to right)
 46 / 15 / 2  3 / 2  1
 19 % 7 % 3  5 % 3  2

 Unary operators: +, –
 Right Associative
 x = – 23 p = +4 * 10
 Execution from left to right, respecting parentheses rule, and then
precedence rule, and then associative rule (next page)
 addition, subtraction are lower in precedence than multiplication,
division, and remainder
 Truncated result if result can’t be stored (the page after next)
 int n; n = 9 * 0.5; results in 4 being stored in n.
Try out Unit3_ArithOps.c
CeNCE Overview of C Programming Unit3 - 39

Preprocessor

Program Structure: Compute (8/9)


Input
Compute
Output

 Arithmetic operators: Associativity & Precedence


Operator Type Operator Associativity
Primary expression ( ) expr++ expr-- Left to right
operators
Unary operators * & + - ++expr --expr (typecast) Right to left
Binary operators * / % Left to right
+ -
Assignment = += -= *= /= %= Right to left
operators

CeNCE Overview of C Programming Unit3 - 40

Preprocessor

Program Structure: Compute (9/9)


Input
Compute
Output

 Mixed-Type Arithmetic Operations


int m = 10/4; means m = 2;
float p = 10/4; means p = 2.0;
int n = 10/4.0; means n = 2;
float q = 10/4.0; means q = 2.5;
int r = -10/4.0; means r = -2;
Caution!
 Type Casting
 Use a cast operator to change the type of an expression

 syntax: (type) expression


int aa = 6; float ff = 15.8;
float pp = (float) aa / 4; means pp = 1.5;
int nn = (int) ff / aa; means nn = 2;
float qq = (float) (aa / 4); means qq = 1.0;

Try out Unit3_MixedTypes.c and Unit3_TypeCast.c


CeNCE Overview of C Programming Unit3 - 41

Exercise #5: Freezer (1/2)


 Write a program freezer.c that estimates the temperature in a
freezer (in oC) given the elapsed time (hours) since a power failure.
Assume this temperature (T) is given by
4t 2
T  20
t2
where t is the time since the power failure.
 Your program should prompt the user to enter how long it has been
since the start of the power failure in hours and minutes, both
values in integers.
 Note that you need to convert the elapsed time into hours in real
number (use type float)
 For example, if the user entered 2 30 (2 hours 30 minutes), you need
to convert this to 2.5 hours before applying the above formula.

CeNCE Overview of C Programming Unit3 - 42

Exercise #5: Freezer (2/2)


 Refer to the sample run below. Follow the output format.
Enter hours and minutes since power failure: 2 45
Temperature in freezer = -13.63

 How long does it take the freezer to get to zero degree?


Which of the following is the closest answer?
a) 3 hours
b) 4 hours 10 minutes
c) 6 hours 30 minutes
d) 8 hours
 This exercise is mounted on Coursemology as a
practice exercise.
 Please work on it on your own and discuss it on the
forum if you have any queries.
CeNCE Overview of C Programming Unit3 - 43

Math Functions (1/2)


 In C, there are many libraries offering functions for you
to use.
 Eg: scanf() and printf() – requires to include <stdio.h>
 In Exercise #5, for t2 you may use t*t, or the pow()
function in the math library: pow(t, 2)
 pow(x, y) // computes x raised to the power of y
 To use math functions, you need to
 Include <math.h> AND
 Compile your program with –lm option (i.e. gcc –lm …)

CeNCE Overview of C Programming Unit3 - 44

Math Functions (2/2)


 Some useful math functions
 Function abs(x) from <stdlib.h>; the rest from <math.h>
Function prototype:
double pow(double x, double y)

function return type

Q: Since the parameters x


and y in pow() function are of
double type, why can we call
the function with pow(t, 2)?

A: Integer value can be


assigned to a double
variable/parameter.
CeNCE Overview of C Programming Unit3 - 45

Math Functions: Example (1/2)


 Program Unit3_HypoteCeNCEe.c computes the
hypoteCeNCEe of a right-angled triangle given the
lengths of its two perpendicular sides

h
ℎ= (𝑎 + 𝑏 ) a

CeNCE Overview of C Programming Unit3 - 46

Math Functions: Example (2/2)


Unit3_HypoteCeNCEe.c
// Unit3_HypoteCeNCEe.c
// Compute the hypoteCeNCEe of a right-angled triangle.
#include <stdio.h>
#include <math.h> Remember to compile with –lm option!

int main(void) {
float hypot, side1, side2;

printf("Enter lengths of the 2 perpendicular sides: ");


scanf("%f %f", &side1, &side2);

hypot = sqrt(side1*side1 + side2*side2);


// or hypot = sqrt(pow(side1, 2) + pow(side2, 2));

printf("HypoteCeNCEe = %6.2f\n", hypot);

return 0;
}
CeNCE Overview of C Programming Unit3 - 47

Programming Style (1/2)


 Programming style is just as important as
writing a correct program
 Refer to some C Style Guides on the CS1010
website
http://www.comp.CeNCE.edu.sg/~cs1010/2_resources/online.htm
l

 In your lab assignments, marks will be awarded


to style besides program correctness
 Correctness: 60%
 Style: 20%
 Design: 20%

CeNCE Overview of C Programming Unit3 - 48

Programming Style (2/2)


 Identifier naming for variables and functions
 Use lower-case with underscore or capitalise first character
of every subsequent word (Eg: celsius, sum, second_max,
secondMax; NOT Celsius, SUM, SecondMax)
 Must be descriptive (Eg: numYears instead of ny, abc, xbrt)
 User-defined constants
 Use upper-case with underscore (Eg: KMS_PER_MILE,
DAYS_IN_YEAR)
 Consistent indentation
 Appropriate comments
 Spacing and blank lines
 And many others
CeNCE Overview of C Programming Unit3 - 49

Very Common Mistakes (1/2)


 Not initialising variables PAINFUL MISTAKE!
 Program may work on some machine but not on another!
Cannot assume that the
initial value of b is zero!
int a, b;
a = b + 3; // but what is the value of b?

 Unnecessary initialisation of variables


int x = 0; int x = 0;
x = 531; scanf("%d", &x);

 Forgetting & in a scanf() statement


int x; int x;
scanf("%d", x); scanf("%d", &x);

CeNCE Overview of C Programming Unit3 - 50

Very Common Mistakes (2/2)


 Forgetting to compile with –lm option when the program
uses math functions.
 Forgetting to recompile after modifying the source code.

Sometimes when your program crashes, a “core dump”


may happen. Remove the file “core” (UNIX command:
rm core) from your directory as it takes up a lot of
space.
CeNCE Overview of C Programming Unit3 - 51

FAQs
Why is there a ‘return 0;’ at the end of every program?
Our program is a function (the ‘main’ function), and it is defined as
‘int main(void)’ – it has no parameters and it returns an integer value.
Hence we add ‘return 0;’ at the end of the function to return 0. Return
to where? Return to the operation system in which the program is
run. Most systems take the return value of 0 to mean a successful
run.

There are so many ways to format outputs in printf(), do I


have to know them all?
You will use the basic ones like %d for integers, %f for float and double,
and %c for characters for now, and simple formatting such as the
number of decimal places to be displayed.
We will focus more on the problem solving aspects in this module than
on complex output formatting. Try to use cout!

CeNCE Overview of C Programming Unit3 - 52

Knowing the basic C constructs, interactive input,


output, and arithmetic operations

Knowing some data types and the


use of variables to hold data

Be aware of some basic common mistakes

Using some math functions

Understanding good programming style


CS1:
PROGRAMMING METHODOLOGY

UNIT 4
Top-Down Design & Functions

CeNCE Top-Down Design & Functions Unit4 - 2

Unit 4: Top-Down Design & Functions


Objectives:
 How to analyse, design, and implement a
program
 How to break a problem into sub-problems with
step-wise refinement
 How to create your own user-defined functions
CeNCE Top-Down Design & Functions Unit4 - 3

Unit 4: Top-Down Design & Functions (1/2)


1. Problem Solving
2. Case Study: Top-Down Design
 Computing the weight of a batch of flat washers
 Incremental Refinement (some hierarchical chart)
 Top-down design (of program) with structure charts
3. Function Prototypes
4. Default Return Type
5. ‘return’ statement in main()

CeNCE Top-Down Design & Functions Unit4 - 4

Unit 4: Top-Down Design & Functions (2/2)


6. Writing Functions
7. Exercise #1: A Simple “Drawing” Program
8. Pass-By-Value and Scope Rules
9. Global Variables
CeNCE Top-Down Design & Functions Unit4 - 5

Problem Solving (1/2)


Determine
problem Analysis
features

Write
Iterative
Design process
algorithm

Produce
code Implementation

Check for
correctness and Testing
efficiency

CeNCE Top-Down Design & Functions Unit4 - 6

Problem Solving (2/2)


Analysis and Design

stepwise
refinement
NO (hierarchy of)
sub-problems

Can sub-problems YES


be implemented? structure chart
Implementation
& Testing

Knowledge in C Knowledge in
Knowledge in data structures
and its libraries
algorithms (mostly CS2)
CeNCE Top-Down Design & Functions Unit4 - 7

Top-Down Design (1/13)


 We introduced some math functions in the previous unit.
 These math functions are provided in <math.h>.
 Such functions provide code reusability. Once the
function is defined, we can use it whenever we need it,
and as often as we need it.
 Can we create our own functions?
 In the following case study, we introduce top-down design
in approaching an algorithmic problem.
 In the process, we encounter certain tasks that are
similar, hence necessitating the creation of user-defined
function.
Decomposition!

CeNCE Top-Down Design & Functions Unit4 - 8

Top-Down Design (2/13)


Case Study: You work for a hardware company that
manufactures flat washers. To estimate shipping costs,
your company needs a program that computes the weight
of a specified quantity of flat washers.

rim area = (d2/2)2 – (d1/2)2


CeNCE Top-Down Design & Functions Unit4 - 9

Top-Down Design (3/13)


 Analysis:
 To get the weight of a specified qty of washers, we need to know
the weight of each washer
 To get the weight of a washer, we need its volume and density
(weight = volume  density)
 To get the volume, we need its rim area and thickness (volume =
rim area  thickness)
 To get the rim area, we need the diameters d2 and d1
Total weight rim area = (d2/2)2 – (d1/2)2

qty weight qty, density,


thickness, d2
volume density and d1 are given
as inputs
rim area thickness

d2 d1

CeNCE Top-Down Design & Functions Unit4 - 10

Top-Down Design (4/13)


 Design (pseudocode):
1. Read inputs (qty, density, thickness, d2, Total weight
d1)
2. Compute weight of one washer qty weight
2.1 Compute area of small circle (hole)
using d1 volume density
2.2 Compute area of big circle using d2
2.3 Subtract small area from big area to rim area thickness
get rim area
2.4 Compute volume = rim area  d2 d1
thickness
2.5 Compute weight = volume  density Step-wise
3. Compute total weight of specified refinement: Splitting
number of washer = weight  qty a complex task (step
2) into subtasks
4. Output the calculated total weight
(steps 2.1 – 2.5)
CeNCE Top-Down Design & Functions Unit4 - 11

Top-Down Design (5/13)


 Design (hierarchical chart):
Compute Total
Weight

Ask for all Compute Compute Output total


inputs Weight weight x qty weight

Compute hole
qty?
area (use d1)

Compute big
density? circle area Note that the computation
(use d2) of area (which employs
the same formula) is
Compute rim
thickness?
area performed twice.

Compute
d1? volume (use
thickness)

Compute
d2? weight (use
density)

CeNCE Top-Down Design & Functions Unit4 - 12

Top-Down Design (6/13)


 Design (structure chart):
 A documentation tool that shows the relationship among the sub-
tasks

Compute Total
Weight

Input : qty, Compute Weight


Compute total Output total
density, of a single
Weight weight
thickness, d1, d2 washer

Compute circle
area
This is called twice.
CeNCE Top-Down Design & Functions Unit4 - 13

Top-Down Design (7/13)


#include <stdio.h>
Unit4_Washers.c
#include <math.h>
#define PI 3.14159

int main(void) {
double d1, // hole circle diameter
d2, // big circle diameter
thickness,
density;
int qty;

double unit_weight, // single washer's weight


total_weight, // a batch of washers' total weight
outer_area, // area of big circle
inner_area, // area of small circle
rim_area; // single washer's rim area

// read input data


printf("Inner diameter in cm: "); scanf("%lf", &d1);
printf("Outer diameter in cm: "); scanf("%lf", &d2);
printf("Thickness in cm: "); scanf("%lf", &thickness);
printf("Density in grams per cubic cm: "); scanf("%lf", &density);
printf("Quantity: "); scanf("%d", &qty);

CeNCE Top-Down Design & Functions Unit4 - 14

Top-Down Design (8/13)


// compute weight of a single washer
Unit4_Washers.c
outer_area = pow(d2/2, 2) * PI;
inner_area = pow(d1/2, 2) * PI;
rim_area = outer_area - inner_area;
unit_weight = rim_area * thickness * density;

// compute weight of a batch of washers


total_weight = unit_weight * qty;

// output
printf("Total weight of the batch of %d washers is %.2f grams.\n",
qty, total_weight);

return 0;
}

gcc -Wall Unit4_Washers.c -lm


CeNCE Top-Down Design & Functions Unit4 - 15

Top-Down Design (9/13)


 Note that area of circle is computed twice. For code
reusability, it is better to define a function to compute
area of a circle.

double circle_area(double diameter) {


return pow(diameter/2, 2) * PI;
}

 We can then call/invoke this function whenever we need


it.
circle_area(d2)  to compute area of circle with diameter d2
circle_area(d1)  to compute area of circle with diameter d1

CeNCE Top-Down Design & Functions Unit4 - 16

Top-Down Design (10/13)


#include <stdio.h>
#include <math.h>
#define PI 3.14159

double circle_area(double diameter) {


Function
return pow(diameter/2, 2) * PI; definition
}

int main(void) {

// identical portion omitted for brevity


Calling circle_area()
// compute weight of a single washer
twice.
rim_area = circle_area(d2) - circle_area(d1);
unit_weight = rim_area * thickness * density;

// identical portion omitted for brevity


}
CeNCE Top-Down Design & Functions Unit4 - 17

Top-Down Design (11/13)


 Components of a function definition
 Header (or signature): consists of return type, function name, and
a list of parameters (with their types) separated by commas
 Function names follow identifier rules (just like variable names)
 May consist of letters, digit characters, or underscore, but cannot
begin with a digit character
 Return type is void if function does not need to return any value
 Function body: code to perform the task; contains a return
statement if return type is not void

Return type Function name Parameter

double circle_area(double diameter) {


return pow(diameter/2, 2) * PI;
}
Function body

CeNCE Top-Down Design & Functions Unit4 - 18

Top-Down Design (12/13)


double circle_area(double diameter)
{
return pow(diameter/2, 2) * PI;
}

 Values of arguments are copied into parameters


rim_area = circle_area(d2) - circle_area(d1);

Value of d2 copied to Value of d1 copied to


parameter diameter parameter diameter

 Arguments need not be variable names; they can be


constant values or expressions
circle_area(12.3)  To compute area of circle with diameter 12.3
circle_area((a+b)/2)  To compute area of circle with diameter
(a+b)/2, where a and b are variables
CeNCE Top-Down Design & Functions Unit4 - 19

Top-Down Design (13/13)


 Preferred practice: add function prototype
 Before main() function
 Parameter names may be omitted, but not their type
Unit4_WashersV2.c
#include <stdio.h>
#include <math.h>
#define PI 3.14159
Function prototype
double circle_area(double);

int main(void) {
// identical portion omitted for brevity

// compute weight of a single washer


rim_area = circle_area(d2) - circle_area(d1); Line 32 (see
unit_weight = rim_area * thickness * density; slide 21)
// identical portion omitted for brevity
} Line 45 (see slide 21)
double circle_area(double diameter) {
return pow(diameter/2, 2) * PI; Function definition
}

CeNCE Top-Down Design & Functions Unit4 - 20

Function Prototypes (1/2)


 It is a good practice to put function prototypes at the top
of the program, before the main() function, to inform the
compiler of the functions that your program may use and
their return types and parameter types.
 Function definitions to follow after the main() function.
 Without function prototypes, you will get error/warning
messages from the compiler.
CeNCE Top-Down Design & Functions Unit4 - 21

Function Prototypes (2/2)


 Let’s remove (or comment off) the function prototype for
circle_area() in Unit4_WashersV2.c
 Messages from compiler:
Unit4_WashersV2.c: In function ‘main’:
Unit4_WashersV2.c:32:5: warning: implicit declaration of
function ‘circle_area’
Unit4_WashersV2.c: At top level:
Unit4_WashersV2.c:45:8: error: conflicting types for
‘circle-area’
Unit4_WashersV2.c:32:16: previous implicit declaration of
‘circle_area’ was here

 Without function prototype, compiler assumes the default (implicit)


return type of int for circle_area() when the function is used in line
32, which conflicts with the function header of circle_area() when the
compiler encounters the function definition later in line 45.

CeNCE Top-Down Design & Functions Unit4 - 22

Default Return Type (1/3)


 A ‘type-less’ function has default return type of int
1 #include <stdio.h>
2
3 int main(void) {
4 printf("%d\n", f(100, 7));
5 return 0;
6 }
7
8 f(int a, int b) {
9 return a*b*b;
10 }

 Program can be compiled, but with warning:


warning: implicit declaration of function 'f'  line 4
(due to absence of function prototype)
warning: return type defaults to 'int'  line 8
CeNCE Top-Down Design & Functions Unit4 - 23

Default Return Type (2/3)


 Another example
1 #include <stdio.h> Without function prototype,
2 compiler assumes function f to
3 int main(void) { be an int function when it
4 f(100, 7); encounters this.
5 return 0;
6 } However, f is defined as a
7 void function here, so it
8 void f(int a, int b) { conflicts with above.
9 return a*b*b;
10 }

 Program can be compiled, but with warning:


warning: implicit declaration of function 'f'  line 4
(due to absence of function prototype)
warning: conflicting types for 'f'  line 8

CeNCE Top-Down Design & Functions Unit4 - 24

Default Return Type (3/3)


 Tips
 Provide function prototypes for all functions
 Explicitly specify the function return type for all functions

1 #include <stdio.h>
2
3 int f(int, int);
4
5 int main(void) {
6 printf("%d\n", f(100, 7));
7 return 0;
8 }
9
10 int f(int a, int b) {
11 return a*b*b;
12 }
CeNCE Top-Down Design & Functions Unit4 - 25

‘return’ statement in main()


 Q: Why do we write return 0; in our main() function?
 Answer:
 Our main() function has this header
int main(void)
 Hence it must return an integer (to the operating system)
 The value 0 is chosen to be returned to the operating system.
This is called the status code of the program.
 When a program terminates with a status code of 0, it means a
successful run.

CeNCE Top-Down Design & Functions Unit4 - 26

Writing Functions (1/5)


 A program is a collection of functions (modules) to transform inputs
to outputs
 In general, each box in a structure chart is a sub-problem which is
handled by a function
 In mathematics, a function maps some input values to a single
(possibly multiple dimensions) output
 In C/C++, a function maps some input values to zero or more output
values
 No output: void func(…) { … }
 One output, e.g., double func(…) { …; return value; }
 More outputs through changing input values (we’ll cover this later)
 Return value (if any) from function call can (but need not) be
assigned to a variable.
CeNCE Top-Down Design & Functions Unit4 - 27

Writing Functions (2/5)


Syntax: Unit4_FunctionEg.c
/*
function interface comment * Finds the square root of the
ftype fname (formal parameters list) * sum of the squares of the two parameters
* Precond: x and y are non-negative numbers
{ */
double sqrt_sum_square(double x, double y) {
local variable declarations // x and y above are the formal parameters
executable statements double sum_square; // local variable declaration
return statement (if appropriate) sum_square = pow(x,2) + pow(y,2);
return sqrt(sum_square);
} }

Notes:
Precondition: describes conditions that should be true before calling function.
Postcondition: describes conditions that should be true after executing function.
These are for documentation purpose.

CeNCE Top-Down Design & Functions Unit4 - 28

Writing Functions (3/5)


Actual parameters (also arguments) are values passed to function for computation
Formal parameters (or simply parameters) are placeholder when function is
defined.
 Matching of actual and formal parameters from left to right
 Scope of formal parameters, local variables are within the function only
// Function prototype at top of program
double sqrt_sum_square(double, double);
int main(void) {
double y = 1.23; // not the same as y double sqrt_sum_square(double x, double y)
// in sqrt_sum_square {
double z = 4.56; // x and y above are formal parameters

// x below not the same as x in sqrt_sum_square double sum_square; // local variable


double x = sqrt_sum_square(y, z);
sum_square = pow(x,2) + pow(y,2);
printf("The square root of the sum of square ");
printf("of %.2f and %.2f is %.2f\n", y, z, x); return sqrt(sum_square);
return 0; }
}

 Arrows indicate flow of control between main() and the function


 Add function prototype at top of program, before main() function
CeNCE Top-Down Design & Functions Unit4 - 29

Writing Functions (4/5)


#include <stdio.h> Unit4_FunctionEg.c
#include <math.h>
The complete /* Function prototype placed at top of program */
program double sqrt_sum_square(double, double);
int main(void) {
double y = 1.23; // not the same as y in sqrt_sum_square
double z = 4.56;

// x below has nothing to do with x in sqrt_sum_square


double x = sqrt_sum_square( y, z );
// in the previous statement, y and z are actual parameters
printf("The square root of the sum of squares ");
printf("of %.2f and %.2f is %.2f\n", y, z, x);

return 0;
}
/* Finds the square root of the
* sum of the squares of the two parameters
* Precond: x and y are non-negative numbers
*/
double sqrt_sum_square(double x, double y) {
// x and y above are the formal parameters

double sum_square; // local variable declaration


sum_square = pow(x,2) + pow(y,2);
return sqrt(sum_square);
}

CeNCE Top-Down Design & Functions Unit4 - 30

Writing Functions (5/5)


 Use of functions allow us to manage a complex (abstract) task with
a number of simple (specific) ones.
 This allows us to switch between abstract and go to specific at ease to
eventually solve the problem.
 Function allows a team of programmers working together on a large
program – each programmer will be responsible for a particular set
of functions.
 Function is good mechanism to allow re-use across different
programs. Programmers use functions like building blocks.
 Function allows incremental implementation and testing (with the
use of driver function to call the function and then to check the
output)
 Acronym NOT summarizes the requirements for argument list
correspondence. (N: number of arguments, O: order, and T: type).
CeNCE Top-Down Design & Functions Unit4 - 31

Ex #1: A Simple “Drawing” Program (1/3)


Problem:
 Write a program Unit4_DrawFigures.c to
draw a rocket ship (which is a triangle over a
rectangle over an inverted V), a male stick
figure (a circle over a rectangle over an
inverted V), and a female stick figure (a circle
over a triangle over an inverted V)
rocket male female
Analysis:
 No particular input needed, just draw the needed 3 figures
 There are common shapes shared by the 3 figures
Design:
 Algorithm (in words):
1. Draw Rocket ship
2. Draw Male stick figure (below Rocket ship)
3. Draw Female stick figure (below Male stick figure)

CeNCE Top-Down Design & Functions Unit4 - 32

Ex #1: A Simple “Drawing” Program (2/3)


Design (Structure Chart):

rocket male female


Draw 3
Figures

Draw Rocket Draw Male Draw Female


Ship Stick Figure Stick Figure

Draw Draw Draw Draw Draw Draw Draw


Draw Circle Draw Circle
Triangle Rectangle Inverted V Rectangle Inverted V Triangle Inverted V
CeNCE Top-Down Design & Functions Unit4 - 33

Ex #1: A Simple “Drawing” Program (3/3)


Implementation (partial program)
Unit4_DrawFiguresPartial.c
#include <stdio.h> void draw_rocket_ship() {
}
void draw_rocket_ship();
void draw_male_stick_figure(); void draw_male_stick_figure() {
void draw_circle(); }
void draw_rectangle();
void draw_circle() {
int main(void) { printf(" ** \n");
draw_rocket_ship(); printf(" * * \n");
printf("\n\n"); printf(" * * \n");
printf(" ** \n");
draw_male_stick_figure(); }
printf("\n\n");
void draw_rectangle() {
return 0; printf(" ****** \n");
} printf(" * * \n");
printf(" * * \n");
printf(" * * \n");
Write a complete program }
printf(" ****** \n");

Unit4_DrawFigures.c

CeNCE Top-Down Design & Functions Unit4 - 34

Pass-By-Value and Scope Rules (1/4)


 In C, the actual parameters are passed to the formal
parameters by a mechanism known as pass-by-value.
int main(void) {
a b
10.5 7.8
double a = 10.5, b = 7.8;
printf("%.2f\n", srqt_sum_square(3.2, 12/5); Actual parameters:
printf("%.2f\n", srqt_sum_square(a, a+b);
return 0; 10.5
3.2 and 18.3
2.0
}

double sqrt_sum_square(double x, double y) { Formal parameters:


double sum_square; x y
sum_square = pow(x,2) + pow(y,2); 10.5
3.2 18.3
2.0
return sqrt(sum_square);
}
CeNCE Top-Down Design & Functions Unit4 - 35

Pass-By-Value and Scope Rules (2/4)


 Formal parameters are local to the function they are declared in.
 Variables declared within the function are also local to the function.
 Local parameters and variables are only accessible in the function
they are declared – scope rule.
 When a function is called, an activation record is created in the call
stack, and memory is allocated for the local parameters and
variables of the function.
 Once the function is done, the activation record is removed, and
memory allocated for the local parameters and variables is released.
 Hence, local parameters and variables of a function exist in memory
only during the execution of the function. They are called automatic
variables.
 In contrast, static variables exist in the memory even after the
function is executed. (We will not use static variables in CS1.)

CeNCE Top-Down Design & Functions Unit4 - 36

Pass-By-Value and Scope Rules (3/4)


 Spot the error in this code:

int f(int);
int main(void) {
int a;
...
}
int f(int x) {
return a + x;
}


CeNCE Top-Down Design & Functions Unit4 - 37

Pass-By-Value and Scope Rules (4/4)


 Trace this code by hand and write out its output.

#include <stdio.h>
void g(int, int);
int main(void) {
int a = 2, b = 3;
a 2
printf("In main, before: a=%d, b=%d\n", a, b);
g(a, b);
printf("In main, after : a=%d, b=%d\n", a, b); b 3
return 0;
}
void g(int a, int b) {
printf("In g, before: a=%d, b=%d\n", a, b); a 2
a = 100 + a;
b = 200 + b;
printf("In g, after : a=%d, b=%d\n", a, b); b 3
}

CeNCE Top-Down Design & Functions Unit4 - 38

Pass-By-Value and Scope Rules (4/4)


 Trace this code by hand and write out its output.

#include <stdio.h>
void g(int, int);
int main(void) {
int a = 2, b = 3;
a 102
printf("In main, before: a=%d, b=%d\n", a, b);
g(a, b);
printf("In main, after : a=%d, b=%d\n", a, b); b 203
return 0;
}
void g(int a, int b) {
printf("In g, before: a=%d, b=%d\n", a, b); a 2
a = 100 + a;
b = 200 + b;
printf("In g, after : a=%d, b=%d\n", a, b); b 3
}


CeNCE Top-Down Design & Functions Unit4 - 39

Pass-By-Value and Scope Rules (4/4)


 Trace this code by hand and write out its output.

#include <stdio.h>
void g(int, int);
int main(void) {
int a = 2, b = 3;
printf("In main, before: a=%d, b=%d\n", a, b);
g(a, b);
printf("In main, after : a=%d, b=%d\n", a, b);
return 0;
}
void g(int a, int b) {
printf("In g, before: a=%d, b=%d\n", a, b); a 2
a = 100 + a;
b = 200 + b;
printf("In g, after : a=%d, b=%d\n", a, b); b 3
}

CeNCE Top-Down Design & Functions Unit4 - 40

Consequence of Pass-By-Value
 Can this code be used to swap the values in a and b?

#include <stdio.h>
void swap(int, int);
int main(void) {
int a = 2, b = 3;
printf("In main, before: a=%d, b=%d\n", a, b);
swap(a, b);
printf("In main, after : a=%d, b=%d\n", a, b);
return 0;
}
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}


CeNCE Top-Down Design & Functions Unit4 - 41

Writing Pre-Condition
 The function triangle_area() computes the area of a
right-angled triangle. The two parameters are the
lengths of the two perpendicular sides.
 How should you write the pre-condition?
// Compute the area of a right-angled triangle.
// side1 and side2 are the lengths of the
// two perpendicular sides.
// Pre-cond: side1 > 0, side2 > 0
double triangle_area(double side1, double side2) {
return side1 * side2 / 2.0;
}

CeNCE Top-Down Design & Functions Unit4 - 42

Function Cohesion
 Which of the two approaches is correct?
// Compute the area of a right-angled triangle.
// Pre-cond: side1 > 0, side2 > 0
double triangle_area(double side1, double side2) {
return side1 * side2 / 2.0;
}

// Compute the area of a right-angled triangle.


// Pre-cond: side1 > 0, side2 > 0
void triangle_area(double side1, double side2) {
printf("Area = %.2f\n", side1 * side2 / 2.0);
}

 In general, a function should perform either computation or I/O, not


both. triangle_area() is to compute the area, so it should return the
answer to the caller, which then decides whether to print the answer
or use it for further computation in a bigger task.
CeNCE Top-Down Design & Functions Unit4 - 43

Global Variables (1/2)


 Global variables are those that are declared outside all
functions.
int f1(int);
void f2(double);
int glob; // global variable
int main(void) {
...
glob = glob + 1;
}
int f1(int x) {
...
glob = glob + 1;
}
void f2(double x) {
...
glob = glob + 1;
}

CeNCE Top-Down Design & Functions Unit4 - 44

Global Variables (2/2)


 Global variables can be accessed and modified by any
function!
 Because of this, it is hard to trace when and where the
global variables are modified.
 Hence, we will NOT allow the use of global variables
CeNCE Top-Down Design & Functions Unit4 - 45

Summary
 In this unit, you have learned about
 Top-down design through stepwise refinement,
splitting a task into smaller sub-tasks
 How to write user-defined functions and use them
 Pass-by-value and scope rules of local parameters
and variables

CeNCE Top-Down Design & Functions Unit4 - 46

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 5
Problem Solving with
Selection and Repetition Statements

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 2

Unit 5: Problem Solving with Selection and


Repetition Statements
Objectives:
 Using relational and logical operators
 Using selection statements to choose between two or
more execution paths in a program
 Using repetition statements to repeat a segment of
code
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 3

Unit 5: Problem Solving with Selection and


Repetition Statements (1/2)
1. Sequential vs Non-Sequential Control Flow
2. Selection Structures
3. Nested if and if-else Statements
4. Style Issues
5. Common Errors
6. The switch Statement
7. Testing and Debugging

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 4

Unit 5: Problem Solving with Selection and


Repetition Statements (2/2)
8. The while Loop
9. The do-while Loop
10. The for Loop
11. Common Errors
12. Some Notes of Caution
13. Using break in Loop
14. Using continue in Loop
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 5

Recall: Control Structures

Sequence

Selection
Repetition

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 6

1. Sequential Control Flow


 Recall Simple “drawing” problem in Unit 4:
Write a program to draw a rocket ship, a male stick figure, rocket
and a female stick figure.

Draw
Triangle

Draw Rocket
Ship Draw
Rectangle male

Draw Circle
Draw
Inverted V
Draw 3
Figures Draw Male Draw
Stick Figure Rectangle

Draw Circle
Draw
Inverted V
female
Draw
Triangle

Draw Female
Stick Figure Draw
Inverted V
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 7

1. Non-Sequential Control Flow


 New requirement:
Write a program to allow user to select only ONE of the following
options: Draw a (1) rocket ship, (2) male stick figure, or (3) female
stick figure.
Draw
Triangle

Draw Rocket
Ship Draw
Select Rectangle
only one
Draw Circle
Draw
Inverted V
Draw 3
Figures Draw Male Draw
Stick Figure Rectangle

Draw Circle
Draw
Inverted V

Draw
Triangle

Draw Female
Stick Figure Draw
Inverted V

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 8

2. Selection Structures
 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 …
switch
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 9

2.1 if and if-else Statements


true
cond?

How are conditions specified false


 if statement and how are they evaluated?

if ( condition ) {
/* Execute these statements if TRUE */
}

Braces { } are optional only if there is one statement


true false
in the block. But for beginners, we recommended cond?
writing braces even if there is one statement.
 if-else statement
if ( condition ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 10

2.2 Condition
 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


< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 11

2.3 Truth Values


 Boolean values: true or false.
 Originally, 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:
Unit5_TruthValues.c
int a = (2 > 3);
int b = (3 > 2);

printf("a = %d; b = %d\n", a, b); a = 0; b = 1

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 12

2.3 Truth Values(II)


 Recent version of C allow bool data type which can take
two values: true or false
 Example:
#include <stdio.h>
#include <stdbool.h>
int main()
{bool a = (2 > 3);
bool b = false;
printf("a = %d; b = %d\n", a, b);
return 0;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 13

2.4 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
False False False False True
Note: There are bitwise
False True False True True operators such as & , |
True False False True False and ^, but we are not
True True True True False covering these in CS1.

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 14

2.5 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
+ -
< > <= >=
== !=
&&
||
Ternary operator ?: Right to Left
Assignment = += -= *= /= %= Right to Left
operators
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 15

2.5 Evaluation of Boolean Expressions (2/2)


See Unit5_EvalBoolean.c
 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)

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 16

2.6 Caution (1/2)


 Since the values 0 and 1 are the returned values for false
and true respectively, we can have codes like these:
int a = 12 + (5 >= 2); // 13 is assigned to a
( 5 >= 2) evaluates to 1; hence a = 12 + 1;

int b = (4 > 5) < (3 > 2) * 6; // 1 assigned to b


* has higher precedence than <.
(3 > 2) evaluates to 1, hence (3 > 2) * 6 evaluates to 6.
(4 > 5) evaluates to 0, hence 0 < 6 evaluates to 1.

int c = ((4 > 5) < (3 > 2)) * 6; // 6 assigned to c


(4 > 5) evaluates to 0, (3 > 2) evaluates to 1, hence
(4 > 5) < (3 > 2) is equivalent to (0 < 1) which evaluates to 1.
Hence 1 * 6 evaluates to 6.

 However, you are certainly not encouraged to write such


convoluted codes!
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 17

2.6 Caution (2/2)


 Very common mistake:

int num;
 What if user enters 7?
printf("Enter an integer: ");  Correct the error.
scanf("%d", &num);

if (num = 3) {
printf("The value is 3.\n");
}
printf("num = %d\n", num);

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 18

2.7 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.
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 19

2.8 if and if-else Statements: Examples (1/2)


if statement int a, b, t;
without else part . . .
if (a > b) {
// Swap a with b
t = a; a = b; b = t;
}
// After above, a is the smaller

if-else statement int a;


. . .
if (a % 2 == 0) {
printf("%d is even\n", a);
}
else {
printf("%d is odd\n", a);
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 20

2.8 if and if-else Statements: Examples (2/2)


 Move common statements out of the if-else construct.

if (cond) { statement-a;
statement-a; statement-b;
statement-b;
statement-j; if (cond) {
statement-x; statement-j;
statement-y; }
} else {
else { statement-k;
statement-a; }
statement-b;
statement-k; statement-x;
statement-x; statement-y;
statement-y;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 21

3. Nested if and if-else Statements (1/2)


 Nested if (if-else) structures refer to the containment of
an if (if-else) structure within another if (if-else) structure.
 For example:
 If it is a weekday, you will be in school from 8 am to 6 pm, do
revision from 6 pm to 12 midnight, and sleep from 12 midnight to
8 am.
 If it is a weekend, then you will sleep from 12 midnight to 10 am
and have fun from 10 am to 12 midnight.

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 22

3. Nested if and if-else Statements (2/2)


 Drawing task in Unit 4  Draw only 1 figure
int main(void) { int main(void) {
draw_rocket(); char resp;
printf("\n\n");
printf("(R)ocket, ");
draw_male();
printf("(M)ale, or ");
printf("\n\n");
printf("(F)emale? ");
draw_female();
scanf("%c", &resp);
printf("\n\n");
if (resp == 'R')
return 0;
draw_rocket();
}
else if (resp == 'M')
draw_male();
else if (resp == 'F')
draw_female();
return 0;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 23

4. Style Issues: Indentation (1/6)


 Once we write non-sequential control structures, we need
to pay attention to indentation.
Acceptable Non-acceptable
if (cond) { if (cond) if (cond)
statements; { {
} statements; statements;
else { } }
statements; else else No indentation!
} { {
statements; statements;
if (cond) { } }
statements;
} else { if (cond) { Closing braces
statements; statements; } not aligned with
} else { if/else keyword!
statements; }

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 24

4. Style Issues: Indentation (2/6)


 Note that appropriate indentation of comments is just as
important.
Correct Incorrect
// Comment on the whole if // Compute the fare
// construct should be aligned with if (cond) {
// the ‘if’ keyword // For peak hours
if (cond) { statements;
// Comment on the statements in }
// this block should be aligned else {
// with the statements below // For non-peak hours
statements; statements;
} }
else {
// Likewise, comment for this
// block should be indented
// like this
statements;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 25

4. Style Issues: Indentation (3/6)


 Sometimes we may have a deeply nested if-else-if
construct:
int marks;
char grade;  This follows the
. . .
if (marks >= 90) indentation guideline, but
grade = 'A'; in this case the code
else
if (marks >= 75) tends to be long and it
grade = 'B'; skews too much to the
else
if (marks >= 60) right.
grade = 'C';
else
if (marks >= 50)
grade = 'D';
else
grade = 'F';

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 26

4. Style Issues: Indentation (4/6)


 Alternative (and preferred) indentation style for deeply
nested if-else-if construct:
int marks; Alternative style
char grade; int marks;
. . . char grade;
if (marks >= 90) . . .
grade = 'A'; if (marks >= 90)
else grade = 'A';
if (marks >= 75) else if (marks >= 75)
grade = 'B'; grade = 'B';
else else if (marks >= 60)
if (marks >= 60) grade = 'C';
grade = 'C'; else if (marks >= 50)
else grade = 'D';
if (marks >= 50) else
grade = 'D'; grade = 'F';
else
grade = 'F';
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 27

4. Style Issues: Naming ‘boolean’ variables (5/6)


 Here, ‘boolean’ variables refer to int variables which are
used to hold 1 or 0 to represent true or false respectively.
 These are also known as boolean flags.
 To improve readability, boolean flags should be given
descriptive names just like any other variables.
 In general, add suffices such as “is” or “has” to names of
boolean flags (instead of just calling them “flag”!)
 Example: isEven, isPrime, hasError, hasDuplicates

int isEven, num; bool isEven, num;


. . . . . .
if (num % 2 == 0) if (num % 2 == 0)
isEven = 1; isEven = true;
else else
isEven = 0; isEven = false;

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 28

4. Style Issues: Removing ‘if’ (6/6)


 The following code pattern is commonly encountered:
int isEven, num;
. . .
if (num % 2 == 0)
isEven = 1;
else
isEven = 0;

 In this case, the if statement can be rewritten into a single


assignment statement, since (num % 2 == 0) evaluates to
either 0 or 1.
 Such coding style is common and the code is shorter.
int isEven, num;
. . .
isEven = (num % 2 == 0);
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 29

5. Common Errors (1/2)


 The code fragments below contain some very common
errors. One is caught by the compiler but the other is not
(which makes it very hard to detect). Spot the errors.
Unit5_CommonErrors1.c
int a = 3;
if (a > 10);
printf("a is larger than 10\n");
printf("Next line.\n");

Unit5_CommonErrors2.c
int a = 3;
if (a > 10);
printf("a is larger than 10\n");
else
printf("a is not larger than 10\n");
printf("Next line.\n");

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 30

5. Common Errors (2/2)


 Proper indentation is important. In the following code, the
indentation does not convey the intended purpose of the
code. Why? Which if is the else matched to?
Unit5_CommonErrors3.c int a, b;
int a, b; . . .
. . .
if (a > 10)
if (a > 10) Same as if (b < 9)
if (b < 9) printf("Hello\n");
printf("Hello\n"); else
else printf("Goodbye\n");
printf("Goodbye\n");
int a, b;
. . .

Use braces if you want to if (a > 10) {


make it more readable: if (b < 9)
printf("Hello\n");
else
printf("Goodbye\n");
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 31

6. The switch Statement (1/3)


 An alternative to if-else-if is to use the switch statement.
 Restriction: Value must be of discrete type (eg: int, char)
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;
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 32

6. The switch Statement (2/3)


 Write a program that reads in a 6-digit zip code and uses
its first digit to print the associated geographic area.

If zip code
Print this message
begins with
0, 2 or 3 <zip code> is on the East Coast.
4–6 <zip code> is in the Central Plains.
7 <zip code> is in the South.
8 or 9 <zip code> is in the West.
others <zip code> is invalid.
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 33

6. The switch Statement (3/3)


#include <stdio.h> Unit5_ZipCode.c
int main(void) {
int zip;
printf("Enter a 6-digit ZIP code: ");
scanf("%d", &zip);
switch (zip/100000) {
case 0: case 2: case 3:
printf("%06d is on the East Coast.\n", zip);
break;
case 4: case 5: case 6:
printf("%d is in the Central Plains.\n", zip);
break;
case 7:
printf("%d is in the South.\n", zip);
break;
case 8: case 9:
printf("%d is in the West.\n", zip);
break;
default:
printf("%d is invalid.\n", zip);
} // end switch
return 0;
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 34

7. Testing and Debugging (1/3)


 Finding the maximum value among 3 variables:
// Returns largest among num1, num2, num3
int getMax(int num1, int num2, int num3) {
int max = 0;
if ((num1 > num2) && (num1 > num3))
max = num1;
if ((num2 > num1) && (num2 > num3))
max = num2;
if ((num3 > num1) && (num3 > num2))
max = num3;
return max;
} Unit5_FindMax_v1.c
 What is wrong with the code? Did you test it with the correct test
data?
 What test data would expose the flaw of the code?
 How do you correct the code?
 After correcting the code, would replacing the 3 if statements with a
nested if-else statement work? If it works, which method is better?
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 35

7. Testing and Debugging (2/3)


 With selection structures (and next time, repetition structures), you
are now open to many alternative ways of solving a problem.
 Alternative approach to finding maximum among 3 values:
// Returns largest among num1, num2, num3
int getMax(int num1, int num2, int num3) {
int max = 0;
if (num1 > max)
max = num1;
else if (num2 > max)
max = num2;
else if (num3 > max)
max = num3;
return max;
} Unit5_FindMax_v2.c

 What is wrong with this code? (There are more than one error.)
 What test data should you use to expose its flaw?

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 36

7. Testing and Debugging (3/3)


 The preceding examples will be discussed in class.
 Remember: Test your programs thoroughly with your own
data.

Do NOT rely on
Coursemology to test your
programs!
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 37

8. The while Loop

false
while ( condition ) cond?

{ true
// loop body
Loop
} body
Braces { } are optional only if there is one statement
in the block. But for beginners, we recommended
writing braces even if there is one statement.
If condition is true,
execute loop body;
Each round of the
otherwise, terminate
loop is called an loop.
iteration.

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 38

8.1 The while Loop: Demo (1/3)


 Keep prompting the
user to input a non-
negative integer, and Enter a number: 12
print that integer. Enter a number: 0
 Halt the loop when Enter a number: 26
the input is negative. Enter a number: 5
 Print the maximum Enter a number: -1
integer input. The maximum number is 26
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 39

8.1 The while Loop: Demo (2/3)


maxi = 0;
read num; maxi = 0;
if (num >= 0) { read num;
if (maxi < num) while (num >= 0) {
maxi = num; if (maxi < num)
read num;
maxi = num;
}
else stop;
read num;
}
if (num >= 0) {
if (maxi < num)
maxi = num; print maxi;
read num;
}
else stop;
...
print maxi;

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 40

8.1 The while Loop: Demo (3/3)


Unit5_FindMax.c
#include <stdio.h>
int main(void) {
int num, maxi = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num >= 0) {
if (maxi < num) {
maxi = num;
}
printf("Enter a number: ");
scanf("%d", &num);
}
printf("The maximum number is %d\n", maxi);
return 0;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 41

8.2 Condition for while Loop


// pseudo-code
a = 2; Output: ?
b = 7;
while (a == b) {  When the loop condition is
print a;
always false, the loop body is
a = a + 2;
} not executed.

// pseudo-code
a = 2; Output: ? 2
b = 7; 4
while (a != b) { 6
print a; 8 Press ctrl-c
a = a + 2; 10
}
to interrupt
:

 When the loop condition is always true, the loop body is


executed forever – infinite loop.

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 42

8.3 Style: Indentation for while Loop


 Loop body must be indented.
 Comment in loop body must be aligned with statements in loop
body.
 Closing brace must be on a line by itself and aligned with the while
keyword.
while (cond) { while (cond)
// loop body or {
statement-1; // loop body
statement-2; statement-1;
... statement-2;
} ...
}
while (cond) {
// loop body while (cond) {
statement-1; No indentation! // loop body
... statement-1;
} statement-2; }
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 43

9. The do-while Loop (1/3)


do
{ Execute loop body
// loop body at least once.
} while ( condition );

Loop
body

cond?
true
false

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 44

9. The do-while Loop (2/3)


do
 Example: Count the number {
of digits in an integer. // loop body
} while ( condition );
Unit5_CountDigits.c
// Precond: n > 0
Assume that n is passed
int count_digits(int n) {
the value 395:
int count = 0;
do { n count
count++; 395 0
n = n/10; 39 1
} while (n > 0);
3 2
return count; 0 3
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 45

9. The do-while Loop (3/3)


 Style: similar to while loop
do { or do
// loop body {
statement-1; // loop body
statement-2; statement-1;
} while (cond); statement-2;
} while (cond);

do {
// loop body
statement-1; No indentation!
statement-2;
} while (cond);

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 46

9. The do-while Loop: Exercise


It’s time to practise Computational Thinking again!
 Add the digits in a positive integer.
 Eg: 395  17

// Precond: n > 0 Which concept in Computational


int count_digits(int n) { Thinking is employed here?
int count = 0;
do {
// Precond: n > 0
count++; int add_digits(int n) {
n = n/10; int sum = 0;
} while (n > 0);
return count; do {
} sum = sum + n%10;
n = n/10;
} while (n > 0);
return sum;
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 47

10. The for Loop (1/2)

for ( initialization; condition; update )


{
// loop body
}

Initialization:
initialize the Condition: repeat loop
loop variable while the condition on
loop variable is true Update: change
value of loop
variable

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 48

10. The for Loop (2/2)

 Example: Print numbers 1 to 10


int n; Steps:
for (n=1; n<=10; n++) { 1.n=1;
printf("%3d", n);
2.if (n<=10) {
}
printf(…);
n++;
Go to step 2
}
3. Exit the loop
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 49

10.1 The for Loop: Odd Integers (1/3)


Unit5_OddIntegers_v1.c
#include <stdio.h>
void print_odd_integers(int);
int main(void) {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
print_odd_integers(num);
return 0;
}
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i+=2) print_odd_integers(12)
printf("%d ", i); 1 3 5 7 9 11
printf("\n");
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 50

10.1 The for Loop: Odd Integers (2/3)


Unit5_OddIntegers_v2.c
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i++) print_odd_integers(12)
if (i%2 != 0) 1 3 5 7 9 11
printf("%d ", i);
printf("\n");
}
Unit5_OddIntegers_v3.c
// Precond: n > 0
void print_odd_integers(int n) {
for ( ; n > 0; n--)
if (n%2 != 0) Values printed from
Empty
printf("%d ", n); largest to smallest.
statement printf("\n");
} print_odd_integers(12)
11 9 7 5 3 1
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 51

10.1 The for Loop: Odd Integers (3/3)


Which is better?
Unit5_OddIntegers_v1.c
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i+=2)
printf("%d ", i);
printf("\n");
}

// Precond: n > 0 Unit5_OddIntegers_v2.c


void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i++)
if (i%2 != 0)
printf("%d ", i);
printf("\n");
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 52

11. Common Errors (1/2)

 What are the outputs for the following programs? (Do


not code and run them. Trace the programs manually.)

int i;
for (i=0; i<10; i++);
printf("%d\n", i);

Unit5_CommonErrors4.c
int i = 0;
while (i<10);
{
printf("%d\n", i);
i++;
} Unit5_CommonErrors5.c
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 53

11. Common Errors (2/2)


int z = 3;
while (z = 1) {
printf("z = %d\n", z);
z = 99;
}
Unit5_CommonErrors6.c

 Off-by-one error; make sure the loop repeats exactly


the correct number of iterations.
 Make sure the loop body contains a statement that
will eventually cause the loop to terminate.
 Common mistake: Using ‘=’ where it should be ‘==’
 Common mistake: Putting ‘;’ where it should not be
(just like for the ‘if’ statement)

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 54

12. Some Notes of Caution (1/2)


 Involving real numbers
 Trace the program manually without running it.

double one_seventh = 1.0/7.0; Expected output:


double f = 0.0;
0.000000
while (f != 1.0) { 0.142857
printf("%f\n", f);
0.285714
f += one_seventh;
} 0.428571
Unit5_Caution1.c 0.571429
0.714286
0.857143
1.000000
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 55

12. Some Notes of Caution (2/2)


 Involving ‘wrap-around’
 Trace the program manually without running it.

int a = 2147483646; Expected output:


int i; 2147483646
for (i=1; i<=5; i++) { 2147483647
printf("%d\n", a); 2147483648
a++; 2147483649
} 2147483650
Unit5_Caution2.c

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 56

Designing Loops
 To write a loop, we need to think about the
following five questions:
• What do we want to do repeatedly?
• What do we need to set up before repeating the above?
• What changes from one repetition to another?
• How to decide if we should stop repeating (or conversely,
to continue repeating?)
• What is the loop invariant?
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 57

Assertion and Loop Invariant


#include <stdio.h>
int main(void) { An assertion is a
int num, maxi = 0; logical expression
that must always be
printf("Enter a number: ");
true for the program
scanf("%d", &num);
to be correct. We can
while (num >= 0) {
write assertions either
// (num >=0)
as part of the
if (maxi < num) {
comment for the code,
// (num >=0) && (maxi<num)
or use
maxi = num;
the assert() macro in
}
C.
// (num>=0) && (maxi >= num)
printf("Enter a number: ");
scanf("%d", &num);
}
// (num<0) && (maxi>=num)
printf("The maximum number is %d\n", maxi);
return 0;
}

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 58

13. Using break in Loop (1/3)


 break is used in switch statement
 It can also be used in a loop Without 'break':
Unit5_BreakInLoop.c 1
Ya
// without 'break'
2
printf ("Without 'break':\n"); Ya
for (i=1; i<=5; i++) { 3
printf("%d\n", i); Ya
printf("Ya\n"); 4
} Ya
5
// with 'break' Ya
printf ("With 'break':\n");
for (i=1; i<=5; i++) { With 'break':
printf("%d\n", i); 1
if (i==3) Ya
break; 2
Ya
printf("Ya\n");
3
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 59

13. Using break in Loop (2/3)


Unit5_BreakInLoop.c With 'break’ in …
// with 'break' in a nested loop 1, 1
printf("With 'break' in a nested loop:\n"); Ya
for (i=1; i<=3; i++) { 1, 2
for (j=1; j<=5; j++) { Ya
printf("%d, %d\n", i, j); 1, 3
if (j==3) 2, 1
Ya
break;
2, 2
printf("Ya\n"); Ya
} 2, 3
} 3, 1
Ya
3, 2
 In a nested loop, break only breaks Ya
out of the inner-most loop that 3, 3
contains the break statement.

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 60

13. Using break in Loop (3/3)


 Use break sparingly, because it violates the one-entry-one-
exit control flow.
 A loop with break can be rewritten into one without break.
// with break // without break
int n, i = 1, sum = 0; int n, i = 1, sum = 0;
int isValid = 1;
while (i <= 5) { while ((i <= 5) && isValid){
scanf("%d", &n); scanf("%d", &n);
if (n < 0) if (n < 0)
break; isValid = 0;
sum += n; else {
i++; sum += n;
} i++;
}
}
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 61

14. Using continue in Loop (1/2) Without 'continue':


 continue is used even less often than break 1
Ya
 Test out Unit5_ContinueInLoop.c 2
// without 'continue' Ya
printf ("Without 'continue':\n"); 3
for (i=1; i<=5; i++) { Ya
4
printf("%d\n", i);
Ya
printf("Ya\n"); 5
} Ya

// with 'continue' With 'continue':


1
printf ("With 'continue':\n");
Ya
for (i=1; i<=5; i++) { 2
printf("%d\n", i); Ya
if (i==3) 3
continue; The rest of the loop 4
printf("Ya\n");body is skipped if Ya
(i==3), and it continues
} 5
to the next iteration.
Ya

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 62

14. Using continue in Loop (2/2) With ...


1, 1
// with 'continue' in a nested loop Ya
printf("With 'continue' in a nested loop:\n"); 1, 2
for (i=1; i<=3; i++) { Ya
for (j=1; j<=5; j++) { 1, 3
printf("%d, %d\n", i, j); 1, 4
if (j==3) Ya
continue; 1, 5
printf("Ya\n"); Ya
2, 1
}
Ya
} 3, 1
2, 2
Ya
Ya
3, 2
2, 3
 In a nested loop, continue only skips 2, 4
Ya
to the next iteration of the inner- 3, 3
Ya
3, 4
most loop that contains the continue 2, 5
Ya
statement. Ya
3, 5
Ya
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 63

Summary
 In this unit, you have learned about
 The use of if-else construct and switch construct to
alter program flow (selection statements)
 The use of relational and logical operators in the
condition
 The use of while, do-while and for loop constructs to
repeat a segment of code (repetition statements)
 The use of break and continue in a loop

CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 64

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 6
Pointers

© CeNCE CS1 (Nov 2023) Unit6 - 2

Unit 6: Pointers
Objective:
 Learning about pointers and how to use them to
access other variables
© CeNCE CS1 (Nov 2023) Unit6 - 3

Unit 6: Pointers
1. Variable and Its Address
2. Pointer Variable
3. Declaring a Pointer
4. Assigning Value to a Pointer
5. Accessing Variable Through Pointer
6. Examples
7. Common Mistake
8. Why Do We Use Pointers?

© CeNCE CS1 (Nov 2023) Unit6 - 4

HOW DO YOU TELL


OTHERS WHERE YOUR
HOME IS?
CS1 (Nov 2023) Unit6 - 5

Real Life Address Example


• Back in 2002, School of Computing is in another corner of
NUS

CS1 (Nov 2023) Unit6 - 6


CS1 (Nov 2023) Unit6 - 7

Real Life Address Example


• The address of SOC at that time Addresses
• 3 Science Drive 2, 117543
• 6 Science Drive 2, 117546
• But now, no more SOC but
• Quantum Tech
• Graphene Research Centre
• NUS Dept of Math

“Contents”

CS1 (Nov 2023) Unit6 - 8

Real Life Address Example


Addresses Contents

• In the past • In the past


• 3 Science Drive 2, 117543 • SOC
• 6 Science Drive 2, 117546 • SOC

• Now • Now
• 3 Science Drive 2, 117543 • Quantum Tech
• 6 Science Drive 2, 117546 • Graphene Research Centre
© CeNCE CS1 (Nov 2023) Unit6 - 9

1. Variable and Its Address (1/2)


Data type Name
 A variable has a unique name
(identifier) in the function it is int a;
declared in, it belongs to some data a = 123;
type, and it contains a value of that
type May only contain integer value

 A variable occupies some space in the


memory, and hence it has an address a

 The programmer usually does not need 123


to know the address of the variable (she
Where is
simply refers to the variable by its
variable a
name), but the system keeps track of the located in the
variable’s address memory?

© CeNCE CS1 (Nov 2023) Unit6 - 10

1. Variable and Its Address (2/2)


 You may refer to the address of a variable by using the
address operator: & (ampersand)
int a = 123; a = 123
printf("a = %d\n", a); &a = ffbff7dc
printf("&a = %p\n", &a);

 %p is used as the format specifier for addresses


 Addresses are printed out in hexadecimal (base 16)
format
 The address of a variable varies from run to run, as the
system allocates any free memory to the variable
 Test out Unit6_Address.c
© CeNCE CS1 (Nov 2023) Unit6 - 11

Computer Memory
Address Content

ffbff7d8
Some others
ffbff7d9 3.1415 maybe float,
double, etc.
ffbff7da

ffbff7db
The
The
address ffbff7dc 123 content is
of the
an integer
variable a ffbff7dd

ffbff7de

© CeNCE CS1 (Nov 2023) Unit6 - 12

How about?
Address Content

ffbff7d8

ffbff7d9 3.1415
The address
The content of the
of the variable ffbff7da ffbff7dc
address is an
a_ptr
address
ffbff7db

ffbff7dc 123

ffbff7dd

ffbff7de
© CeNCE CS1 (Nov 2023) Unit6 - 13

2. Pointer Variable
 A variable that contains the address of another variable
is called a pointer variable, or simply, a pointer.
 Example: a pointer variable a_ptr is shown as a blue
box below. It contains the address of variable a.
a_ptr a
Assuming that
ffbff7dc 123 variable a is located
at address ffbff7dc.

 Variable a_ptr is said to be pointing to variable a.


 If the address of a is immaterial, we simply draw an arrow
from the blue box to the variable it points to.
a_ptr a

123

© CeNCE CS1 (Nov 2023) Unit6 - 14

3. Declaring a Pointer
Syntax:
type *pointer_name;

 pointer_name is the name (identifier) of the pointer


 type is the data type of the variable this pointer may
point to
 Example: The following statement declares a pointer
variable a_ptr which may point to any int variable
 Good practice to name a pointer with suffix _ptr or _p

int *a_ptr;
© CeNCE CS1 (Nov 2023) Unit6 - 15

4. Assigning Value to a Pointer


 Since a pointer contains an address, only addresses
may be assigned to a pointer
 Example: Assigning address of a to a_ptr
int a = 123;
int *a_ptr; // declaring an int pointer
a_ptr = &a;
a_ptr a

123

 We may initialise a pointer during its declaration:


int a = 123;
int *a_ptr = &a; // initialising a_ptr

© CeNCE CS1 (Nov 2023) Unit6 - 16

5. Accessing Variable Through Pointer


a_ptr a

123

 Once we make a_ptr points to a (as shown above), we


can now access a directly as usual, or indirectly
through a_ptr by using the indirection operator (also
called dereferencing operator): *
printf("a = %d\n", *a_ptr);

= printf("a = %d\n", a);

*a_ptr = 456; = a = 456;

Hence, *a_ptr is synonymous with a


© CeNCE CS1 (Nov 2023) Unit6 - 17

6. Example #1
12 12
int i = 10, j = 20; i j
10 20
int *p; // p is a pointer to some int variable
p
p = &i; // p now stores the address of variable i
Important! Now *p is equivalent to i

printf("value of i is %d\n", *p); value of i is 10


// *p accesses the value of pointed/referred variable
*p = *p + 2; // increment *p (which is i) by 2
// same effect as: i = i + 2;
p = &j; // p now stores the address of variable j
Important! Now *p is equivalent to j
*p = i; // value of *p (which is j now) becomes 12
// same effect as: j = i;

© CeNCE CS1 (Nov 2023) Unit6 - 18

6. Example #2 (1/2) a
Unit6_Pointer.c
#include <stdio.h> b
Can you draw the picture?
int main(void) { What is the output?
12.340000
double a, *b;
What is the output if the printf()
b = &a; statement is changed to the following?
*b = 12.34; printf("%f\n", *b);
printf("%f\n", a); 12.340000

printf("%f\n", b); Compile with


return 0;
warning
} printf("%f\n", *a);
Error
Value in hexadecimal;
What is the proper way to print a pointer? varies from run to run.
(Seldom need to do this.)
printf("%p\n", b);
ffbff6a0
© CeNCE CS1 (Nov 2023) Unit6 - 19

6. Example #2 (2/2)
 How do we interpret the declaration?
double a, *b;
 The above is equivalent to
double a; // this is straight-forward: a is a double variable
double *b;
 We can read the second declaration as
 *b is a double variable, so this implies that ...
 b is a pointer to some double variable
 The following are equivalent:
double a; double a;
double *b; double *b = &a;
b = &a;

But this is not the same as double a;


above (and it is not legal): double b = &a;

© CeNCE CS1 (Nov 2023) Unit6 - 20

Exercise #1: Tracing Pointers (1/2)


 Trace the code below manually to obtain the outputs.
 Compare your outputs with your neighbours.
Unit6_TracePointers.c
int a = 8, b = 15, c = 23;
int *p1, *p2, *p3;
p1 = &b;
p2 = &c;
p3 = p2;
printf("1: %d %d %d\n", *p1, *p2, *p3);
*p1 *= a;
while (*p2 > 0) {
*p2 -= a;
(*p1)++;
}
printf("2: %d %d %d\n", *p1, *p2, *p3);
printf("3: %d %d %d\n", a, b, c);
© CeNCE CS1 (Nov 2023) Unit6 - 21

Exercise #2: Choose the Correct Codes


 Pick the correct codes to read a value into the float
variable var.

(A) (B)
float var; float var;
scanf("%f", var) scanf("%f", &var)

(C) (D)
float var; float var;
float *p; float *p;
p = &var; p = &var;
scanf("%f", p) scanf("%f", &p)

© CeNCE CS1 (Nov 2023) Unit6 - 22

Exercise #3: Incrementing a Pointer


 If p is a pointer variable, what does it mean by p = p + 1
(or p++)?
Unit 4 Exercise #1:
int a, *ap; int takes up 4 bytes Unit6_IncrementPointers.c
float b, *bp; float takes up 4 bytes
char c, *cp; char takes up 1 byte
double d, *dp; double takes up 8 bytes

ap = &a; bp = &b; cp = &c; dp = &d;


printf("%p %p %p %p\n", ap, bp, cp, dp);

ap++; bp++; cp++; dp++;


printf("%p %p %p %p\n", ap, bp, cp, dp);

ap += 3;
printf("%p\n", ap);
© CeNCE CS1 (Nov 2023) Unit6 - 23

7. Common Mistake
Unit6_Common_Mistake.c
#include <stdio.h>
int main(void) { What’s wrong with this?
int *n; Can you draw the picture?
*n = 123; ?
printf("%d\n", *n); n
return 0;
}

 Where is the pointer n pointing to?


 Where is the value 123 assigned to?
 Result: Segmentation Fault (core dumped)
 Remove the file “core” from your directory. It takes up a lot of space!

© CeNCE CS1 (Nov 2023) Unit6 - 24

8. Why Do We Use Pointers?


 It might appear that having a pointer to point to a
variable is redundant since we can access the variable
directly
 The purpose of pointers is apparent later when we pass
the address of a variable into a function, in the following
scenarios:
 To pass the address of the first element of an array to a
function so that the function can access all elements in the
array (Unit 7 Arrays, and Unit 8 Multidimensional Arrays)
 To pass the addresses of two or more variables to a function so
that the function can pass back to its caller new values for the
variables (Unit 12 Functions with Pointer Parameters)
© CeNCE CS1 (Nov 2023) Unit6 - 25

Summary
 In this unit, you have learned about
 Declaring a pointer variable
 Using a pointer variable to point to a variable
 Hence, assessing a variable through the pointer
variable that points to it

© CeNCE CS1 (Nov 2023) Unit6 - 26

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 7
Arrays

CeNCE Arrays Unit7 - 2

UNIT 7: Arrays
Objectives:
 Understand the concept and application of arrays
 Problem solving using arrays
CeNCE Arrays Unit7 - 3

UNIT 7: Arrays (1/2)


1. Motivation #1: Coin Change
2. Motivation #2: Vote Counting
3. Arrays
3.1 Array Declaration: Syntax
3.2 Array Variable
3.3 Array Declarations with Initializers
3.4 Demo #1: Using Array Initializer
3.5 Demo #2: Coin Change Revisit
3.6 Array Size

CeNCE Arrays Unit7 - 4

UNIT 7: Arrays (2/2)


4. Arrays and Pointers
5. Array Assignment
6. Array Parameters in Functions
7. Passing Array Arguments
8. Standard I/O Functions for Arrays
9. Modifying Array Arguments
10.Exercise: Up-slopes
CeNCE Arrays Unit7 - 5

1. Motivation #1: Coin Change (1/2)


 Some of the programs we have written are “long-
winded”, because we have not learned enough C
constructs to do it simpler.
 Consider the Coin Change problem (Unit 3 Task 2) with
6 denominations 1¢, 5¢, 10¢, 20¢, 50¢, and $1:
Algorithm 1:
input: amt (in cents); output: coins
coins  0
coins += amt/100; amt %=100;
coins += amt/50; amt %= 50;
coins += amt/20; amt %= 20;
coins += amt/10; amt %= 10;
coins += amt/5; amt %= 5;
coins += amt/1; amt %= 1;
print coins

CeNCE Arrays Unit7 - 6

1. Motivation #1: Coin Change (2/2)


int minimumCoins(int amt) { Unit7_CoinChange.c
int coins = 0;

coins += amt/100;
amt %= 100;  Can we do better?
coins += amt/50;
amt %= 50;
coins += amt/20;
amt %= 20;
coins += amt/10;
amt %= 10;
coins += amt/5;
amt %= 5;
coins += amt/1; // retained for regularity
amt %= 1; // retained for regularity

return coins;
}
CeNCE Arrays Unit7 - 7

2. Motivation #2: Vote Counting


 A student election has just completed with 1000 votes
cast for the three candidates: Tom, Dick and Harry.
 Write a program Unit7_VoteCount.c to read in all the
votes and display the total number of votes received by
each candidate. Each vote has one of three possible
values:
 1: for candidate Tom
 2: for candidate Dick
 3: for candidate Harry

CeNCE Arrays Unit7 - 8

2. Motivation #2: Votes for 3 candidates


#include <stdio.h> Unit7_VoteCount.c
#define NUM_VOTES 1000 // number of votes

int main(void) {
int i, vote, tom = 0, dick = 0, harry = 0;

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote);
switch (vote) { What if there were 30
case 1: tom++; break; instead of 3 candidates?
case 2: dick++; break;
case 3: harry++; break;
}
}
printf("Tom: %d; Dick: %d; Harry: %d\n",
tom, dick, harry);
return 0;
}
CeNCE Arrays Unit7 - 9

2. Motivation #2: Votes for 30 candidates


#include <stdio.h>
#define NUM_VOTES 1000 // number of votes

int main(void) {
int i, vote, c1 = 0, c2 = 0, ..., c30 = 0;

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote);
switch (vote) {
case 1: c1++; break;
case 2: c2++; break;
. . .
case 30: c30++; break;
}
}
. . .
}

CeNCE Arrays Unit7 - 10

3. Introducing Array (1/4)


“If a program manipulates a large amount of data,
it does so in a small number of ways.”
Alan J. Perlis
Yale University
The first recipient of ACM Turing Award
CeNCE Arrays Unit7 - 11

3. Introducing Array (2/4)


 In the vote counting problem, it’s inconvenient to define
and use a set of variables c1, c2, ..., c30, each for one
candidate.
 We handle this problem by indexing the candidates:
C0 , C1 , …, C29 (assuming that indexing begins at 0)

C0 C1 C2 … C28 C29
Votes for Candidates: 10 21 14 20 … 42 7

CeNCE Arrays Unit7 - 12

3. Introducing Array (3/4)


 The indexing facility is implemented as a programming
language feature called ARRAY.

int c[30];
Element type Array size
Array name

Array Indexing

C[0] C[1] C[2] … C[28] C[29]


10 21 14 20 … 42 7
CeNCE Arrays Unit7 - 13

3. Introducing Array (4/4)


Pseudo-code for Vote Counting:
Let C be an array such that Ci holds the vote count of
Candidate i

for each i such that 0 ≤ i < Number_of_candidates


Ci  0 ;

while there is a vote to be counted


vote  read a vote
if 1 ≤ vote ≤ Number_of_candidate then
j  vote – 1
Cj  Cj + 1

CeNCE Arrays Unit7 - 14

3.1 Array Declaration: Syntax


T arrname [ E ]
 arrname is name/identifier of array (same way you would name a
variable)
 T is a data type (e.g., int, double, char, …)
 E is an integer constant expression with a positive value
 Examples:
int arr[10]; // size of arr is 10

#define M 5 For problem using


#define N 10 arrays, we will
double foo[M*N+8]; // size of foo is 58 state the
maximum number
int i; of elements so
float bar[i]; // variable-length array there is no need
for variable-length
Not encouraged to use variable-length arrays.
arrays.
Not supported by ISO C90 standard.
gcc –pedantic will generate warning.
CeNCE Arrays Unit7 - 15

3.2 Array Variable (1/4)


 In an array of type T, each element is a type T variable.
Unit7_VoteCountArray.c
#define NUM_VOTES 1000
#define NUM_CANDIDATES 30
int main(void) {
int i, vote, cand[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) // initialize array
cand[i] = 0;

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote); What is
cand[vote-1]++; %%?
}
for (i = 0; i < NUM_CANDIDATES; i++) {
printf("candidate %d: total %d, %.2f%%\n",
i+1, cand[i], (cand[i] * 100.0)/NUM_VOTES);
}
return 0; Why 100.0 and
} not 100?

CeNCE Arrays Unit7 - 16

3.2 Array Variable (2/4)


 In an array of type T, each element is a type T variable.
Unit7_VoteCountArray.c
#define NUM_VOTES 1000
#define NUM_CANDIDATES 30
int main(void) {
0 ≤ index < array size
int i, vote, cand[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) { cand[i] = 0; }

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote);
cand[vote-1]++;
}
for (i = 0; i < NUM_CANDIDATES; i++) {
printf("candidate %d: total %d, %.2f%%\n",
i+1, cand[i], (cand[i] * 100.0)/NUM_VOTES);
}
return 0;
}
CeNCE Arrays Unit7 - 17

3.2 Array Variable (3/4)


 In an array of type T, each element is a type T variable.
Unit7_VoteCountArray.c
#define NUM_VOTES 1000
#define NUM_CANDIDATES 30
int main(void) {
int i, vote, cand[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) { cand[i] = 0; }

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) { Increment the value
scanf("%d", &vote); of an array element
cand[vote-1]++;
} Assume no invalid vote
for (i = 0; i < NUM_CANDIDATES; i++) {
printf("candidate %d: total %d, %.2f%%\n",
i+1, cand[i], (cand[i] * 100.0)/NUM_VOTES);
}
return 0;
}

CeNCE Arrays Unit7 - 18

3.2 Array Variable (4/4)


 In an array of type T, each element is a type T variable.
Unit7_VoteCountArray.c
#define NUM_VOTES 1000
#define NUM_CANDIDATES 30
int main(void) {
int i, vote, cand[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) { cand[i] = 0; }

printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote);
cand[vote-1]++; Print out all vote counts
}
for (i = 0; i < NUM_CANDIDATES; i++) {
printf("candidate %d: total %d, %.2f%%\n",
i+1, cand[i], (cand[i] * 100.0)/NUM_VOTES);
}
return 0;
}
CeNCE Arrays Unit7 - 19

3.3 Array Declarations with Initializers


 Array variables can be initialized at the time of
declaration.
// a[0]=54, a[1]=9, a[2]=10
int a[3] = {54, 9, 10};

// size of b is 3 with b[0]=1, b[1]=2, b[2]=3


int b[] = {1, 2, 3};

// c[0]=17, c[1]=3, c[2]=10, c[3]=0, c[4]=0


int c[5] = {17, 3, 10};

 The following initializations are incorrect:


int e[2] = {1, 2, 3}; // warning issued: excess elements

int f[5];
f[5] = {8, 23, 12, -3, 6}; // too late to do this;
// compilation error

CeNCE Arrays Unit7 - 20

3.4 Demo #1: Using Array Initializer


 Modify the program to use an array initializer.
Unit7_VoteCountArrayVer2.c
#define NUM_VOTES 1000
#define NUM_CANDIDATES 30
int main(void) {
int i, vote, cand[NUM_CANDIDATES];
for (i = 0; i < NUM_CANDIDATES; i++) { cand[i] = 0; }
int cand[NUM_CANDIDATES] = { 0 };
printf("Enter votes:\n");
for (i = 0; i < NUM_VOTES; i++) {
scanf("%d", &vote);
cand[vote-1]++;
}
for (i = 0; i < NUM_CANDIDATES; i++) {
printf("candidate %d: total %d, %.2f%%\n",
i+1, cand[i], (cand[i] * 100.0)/NUM_VOTES);
}
return 0;
}
CeNCE Arrays Unit7 - 21

3.5 Demo #2: Coin Change Revisit (1/2)


 Let’s “roll” the common steps in Algorithm 1 into a loop:
Algorithm 1:
input: amt (in cents); output: coins Algorithm 2:
coins  0 input: amt (in cents); output: coins
coins += amt/100; amt %=100; coins  0
coins += amt/50; amt %= 50; From the largest denomination to the smallest:
coins += amt/20; amt %= 20; coins += amt/denomination
coins += amt/10; amt %= 10;
amt %= denomination
coins += amt/5; amt %= 5;
coins += amt/1; amt %= 1;
go to next denomination
print coins print coins

Now, we may use a list Algorithm 3:


D to store the input: amt (in cents); output: coins
denominations – giving D is an array with 6 elements
rise to an array! coins  0
for i from 0 to 5 // there are 6 denominations
coins += amt/Di
amt %= Di
print coins

CeNCE Arrays Unit7 - 22

3.5 Demo #2: Coin Change Revisit (2/2)


 Compare:
int minimumCoins(int amt) { int minimumCoins(int amt) {
int coins = 0; int denoms[] = {100,50,20,10,5,1};
coins += amt/100; int i, coins = 0;
amt %= 100;
coins += amt/50; for (i=0; i<6; i++) {
amt %= 50; coins += amt/denoms[i];
coins += amt/20; amt %= denoms[i];
amt %= 20; }
coins += amt/10;
amt %= 10; return coins;
coins += amt/5; }
amt %= 5; Unit7_CoinChangeArray.c
coins += amt/1;
amt %= 1;
return coins;
}
Unit7_CoinChange.c
So much more elegant!
CeNCE Arrays Unit7 - 23

3.6 Array Size


 In ANSI C (which we are adopting), the array is of fixed
size, and is determined at compile time
 Hence, we need to specify the size of the array, eg:
int arr[8];

 The following is not allowed:


int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size]; // declare array arr with number of
// elements provided by user

 Hence, for problems on arrays, we will indicate the


largest possible size of each array.

CeNCE Arrays Unit7 - 24

4. Arrays and Pointers


 Example: int a[10]
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

 When the array name a appears in an expression, it


refers to the address of the first element (i.e. &a[0]) of
that array.
int a[3]; These 2
printf("%p\n", a); ffbff724 outputs will
printf("%p\n", &a[0]); ffbff724 always be
printf("%p\n", &a[1]); ffbff728 the same.

Output varies from one run to


another. Each element is of int type,
hence takes up 4 bytes (32 bits).
CeNCE Arrays Unit7 - 25

5. Array Assignment (1/2)


 The following is illegal in C:
Unit7_ArrayAssignment.c
#define N 10
int source[N] = { 10, 20, 30, 40, 50 };
int dest[N];
dest = source; // illegal!
source[0] source[9]
10 20 30 40 50 0 0 0 0 0
dest[0] dest[9]
? ? ? ? ? ? ? ? ? ?
 Reason:
 An array name is a fixed (constant) pointer; it points to the first
element of the array, and this cannot be altered.
 The code above attempts to alter dest to make it point
elsewhere.

CeNCE Arrays Unit7 - 26

5. Array Assignment (2/2)


 How to do it properly? Write a loop:
#define N 10 Unit7_ArrayCopy.c
int source[N] = { 10, 20, 30, 40, 50 };
int dest[N];
int i;
for (i = 0; i < N; i++) {
dest[i] = source[i];
}
source[0] source[9]
10 20 30 40 50 0 0 0 0 0

dest[0] dest[9]
10 20 30 40 50 0 0 0 0 0

 (There is another method – use the <string.h> library function


memcpy(), but this is outside the scope of CS1.)
CeNCE Arrays Unit7 - 27

6. Array Parameters in Functions (1/3)


#include <stdio.h> Unit7_SumArray.c
int sumArray(int [], int); // function prototype
int main(void) {
int foo[8] = {44, 9, 17, 1, -4, 22};
int bar[] = {2, 8, 6};
printf("sum is %d\n", sumArray(foo, 8));
printf("sum is %d\n", sumArray(foo, 3));
printf("sum is %d\n", sumArray(bar, 3));
return 0;
} sum is 89
sum is 70
// size of array arr can be unspecified
sum is 16
// need an array size parameter
int sumArray(int arr[], int size) {
int i, total=0;
for (i=0; i<size; i++)
total += arr[i];
return total;
}

CeNCE Arrays Unit7 - 28

6. Array Parameters in Functions (2/3)


 Function prototype:
 As mentioned before, name of parameters in a function
prototype are optional and ignored by the compiler. Hence,
both of the following are acceptable and equivalent:
int sumArray(int [], int);

int sumArray(int arr[], int size);


 Function header:
 No need to put array size inside [ ]; even if array size is
present, compiler just ignores it.
 Instead, provide the array size through another parameter.
int sumArray(int arr[], int size) { ... }

int sumArray(int arr[8], int size) { ... }


Ignored by compiler Actual number of elements
you want to process
CeNCE Arrays Unit7 - 29

6. Array Parameters in Functions (3/3)


 Alternative syntax
 The following shows the alternative syntax for array parameter
in function prototype and function header (using Pointers)

int sumArray(int *, int); // fn prototype

int sumArray(int *arr, int size) { ... }

 However, we recommend the [ ] notation


int sumArray(int [], int); // fn prototype

int sumArray(int arr[], int size) { ... }

CeNCE Arrays Unit7 - 30

7. Passing Array Arguments (1/3)


 Need to pass an array argument for arr as well as size, the
number of elements to be processed.
int main(void) {
...
printf("sum is %d\n", sumArray(foo, 8));
...
}
int sumArray(int arr[], int size) {
...
}

 Note that array argument is specified by array name without [ ]


int main(void) {
...
printf("sum is %d\n", sumArray(foo[], 8));
...
} Common mistake!
CeNCE Arrays Unit7 - 31

7. Passing Array Arguments (2/3)


 Caution!
 When passing the value into the parameter
representing the number of array elements to be
processed, the value must not exceed the actual
array size.
printf("sum is %d\n", sumArray(foo, 10));

Too big!
And compiler won’t be able to detect such “error”!
May get “Segmentation Fault (core dumped)”
when you run the program!

CeNCE Arrays Unit7 - 32

7. Passing Array Arguments (3/3)


 Recall that the array name is the address of its first
element. Hence foo means &foo[0].
int main(void) {
...
printf("sum is %d\n", sumArray(foo, 8));
...
}
int sumArray(int arr[], int size) {
...
}

In main():
foo[0] foo[1] foo[7]
44 9 17 1 -4 22 0 0

arr size
In sumArray():
8
CeNCE Arrays Unit7 - 33

8. Standard I/O Functions for Arrays (1/3)


 It might be advisable to write a function to read values
into an array, and a function to print values in an array.
 Especially so for the latter, as you probably want to use
it to check the values of your array elements at different
stages of your program.
 The following illustrates an array scores of type float.
Unit7_ArrayInputOutput.c
#define SIZE 6
int main(void) {
float scores[SIZE];
scanArray(scores, SIZE);
printArray(scores, SIZE);
return 0;
}

CeNCE Arrays Unit7 - 34

8. Standard I/O Functions for Arrays (2/3)


 Input function:
void scanArray(float arr[], int size) {
int i;
float value;
// You may add a prompt for user here
for (i=0; i<size; i++) {
scanf("%f", &value);
arr[i] = value;
}
}

or
void scanArray(float arr[], int size) {
int i;
// You may add a prompt for user here
for (i=0; i<size; i++) {
scanf("%f", &arr[i]);
}
}
CeNCE Arrays Unit7 - 35

8. Standard I/O Functions for Arrays (3/3)


 Output function:
void printArray(float arr[], int size) {
int i;
// To print all values on one line
for (i=0; i<size; i++)
printf("%f ", arr[i]);

printf("\n");
}

or
void printArray(float arr[], int size) {
int i;
// To print each value on one line
for (i=0; i<size; i++)
printf("%f\n", arr[i]);
}

CeNCE Arrays Unit7 - 36

9. Modifying Array Arguments (1/2)


 Study this program:
Unit7_ModifyArrayArg.c
int main(void) {
int foo[8] = {44, 9, 17, 1, -4, 22};
doubleArray(foo, 4);
printArray(foo, 8);
return 0;
}
// To double the values of array elements
void doubleArray(int arr[], int size) {
int i;
for (i=0; i<size; i++)
arr[i] *= 2;
}
// To print arr
void printArray(int arr[], int size) {
int i;
for (i=0; i<size; i++)
printf("%d ", arr[i]);
printf("\n");
}
CeNCE Arrays Unit7 - 37

9. Modifying Array Arguments (2/2)


int main(void) {
int foo[8] = {44, 9, 17, 1, -4, 22};
doubleArray(foo, 4);
. . .
}
// To double the values of array elements
void doubleArray(int arr[], int size) {
int i;
for (i=0; i<size; i++)
arr[i] *= 2;
}

In main():
foo[0] foo[1] foo[7]
44
88 9
18 17
34 12 -4 22 0 0

In doubleArray(): arr size i


4 ?
0
4
21
3

CeNCE Arrays Unit7 - 38

10. Exercise: Up-slopes (1/3)


You are an avid runner. Given a running route
consisting of heights of points at regular interval on
the route, you want to find the number of up-slopes
in the route. An up-slope is a contiguous group of
heights of increasing values.

Enter data:
3
3
4
:
2.9
3.65
-1
Number of up-slopes = 4
CeNCE Arrays Unit7 - 39

10. Exercise: Up-slopes (2/3) Unit7_UpSlopes.c


#include <stdio.h>
#define MAX 100 // maximum length of a route
// function prototypes omitted
int main(void) {
float route[MAX];
int route_length;
route_length = read_route(route);
printf("Number of up-slopes = %d\n", compute_upslopes(route, route_length));
return 0;
}
// This function reads a list of ...
int read_route(float route[]) {
float height;
int length = 0; // length of route; number of values read
printf("Enter data: ");
scanf("%f", &height);
while (height >= 0) {
route[length++] = height;
scanf("%f", &height);
}
return length;
}

CeNCE Arrays Unit7 - 40

10. Exercise: Up-slopes (3/3) Unit7_UpSlopes.c


// This function takes a route and computes the number of upslopes.
int compute_upslopes(float route[], int size) {
int upslopes = 0; // number of upslopes

return upslopes;
}
CeNCE Arrays Unit7 - 41

Summary
 In this unit, you have learned about
 Declaring array variables
 Using array initializers
 Relationship between array and pointer
 How to pass an array into a function

CeNCE Arrays Unit7 - 42

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 8
Multidimensional Arrays

CeNCE Multidimensional Arrays Unit8 - 2

Unit 8: Multidimensional Arrays


Objective:
 Understand the concept of multi-dimensional
arrays
 Problem solving using multidimensional arrays
CeNCE Multidimensional Arrays Unit8 - 3

Unit 8: Multidimensional Arrays (1/2)


1. One-dimensional Arrays (review)
1.1 Print Array
1.2 Find Maximum Value
1.3 Sum Elements
1.4 Sum Alternate Elements
1.5 Sum Odd Elements
1.6 Sum Last 3 Elements
1.7 Minimum Pair Difference
1.8 Accessing 1D Array Elements in Function

CeNCE Multidimensional Arrays Unit8 - 4

Unit 8: Multidimensional Arrays (2/2)


2. Multi-dimensional Arrays
2.1 Initializers
2.2 Example
2.3 Accessing 2D Array Elements in Function
2.4 Class Enrolment
2.5 Matrix Addition

3. Exercise: Pyramid
CeNCE Multidimensional Arrays Unit8 - 5

1. One-dimensional Arrays (1/2)


Array
Element type
A collection of data,
called elements, of Array name
homogeneous type
int a [6]
Array size

a[0] a[1] a[2] a[3] a[4] a[5]


20 12 25 8 36 9

CeNCE Multidimensional Arrays Unit8 - 6

1. One-dimensional Arrays (2/2)


 Preparing an array prior to processing:
Initialization (if values are known beforehand):
int main(void) {
int numbers[] = { 20, 12, 25, 8, 36, 9 };
...

some_fn(numbers, 6);
}
Or, read data into array:
int main(void) {
int numbers[6], i;
for (i = 0; i < 6; i++)
scanf("%d", &numbers[i]);
...
some_fn(numbers, 6);
}
CeNCE Multidimensional Arrays Unit8 - 7

1.1 Print Array


void printArray(int arr[], int size) {
int i;

for (i = 0; i < size; i++)


printf("%d ", arr[i]);
printf("\n");
}

Calling:
int main(void) { Value must not
int numbers[6]; exceed actual
... array size.

printArray(numbers, 6); Print first 6 elements (all)


printArray(numbers, 3); Print first 3 elements
}

CeNCE Multidimensional Arrays Unit8 - 8

1.2 Find Maximum Value


 findMax(int arr[], int size) to return the
maximum value in arr with size elements
 Precond: size > 0
int findMax(int arr[], int size) { i arr max
int i, max; 1
5
4
3
2
6 20 20
36
25
max = arr[0]; 12
for (i = 1; i < size; i++) 25
if (arr[i] > max)
8
max = arr[i];
36
return max; 9
}
CeNCE Multidimensional Arrays Unit8 - 9

Computational
1.3 Sum Elements Thinking time again!

 sum(int arr[], int size) to return the sum of


elements in arr with size elements
 Precond: size > 0
int sum(int arr[], int size) { i arr sum
int i, sum = 0; 3
2
1
0
4
5
6 20 101
110
57
32
20
65
0
for (i = 0; i < size; i++) 12
sum += arr[i]; 25
8
return sum;
} 36
9

CeNCE Multidimensional Arrays Unit8 - 10

Computational
1.4 Sum Alternate Elements Thinking time again!

 sumAlt(int arr[], int size) to return the


sum of alternate elements (1st, 3rd, 5th, etc.)
 Precond: size > 0
int sumAlt(int
sum(int arr[],
arr[],
intint
size)
size)
{ { i arr sum
int i, sum = 0; 6
4
2
0 20 81
45
20
0
for (i = 0; i < size; i+=2)
i++) 12
sum += arr[i]; 25
8
return sum;
} 36
9
CeNCE Multidimensional Arrays Unit8 - 11

Computational
1.5 Sum Odd Elements Thinking time again!

 sumOdd(int arr[], int size) to return the sum


of elements that are odd numbers
 Precond: size > 0
int sumOdd(int arr[],
sum(int arr[], intint size)
size) { { i arr sum
int i, sum = 0; 5
4
3
2
1
0
6 20 25
34
0
for (i = 0; i < size; i++) 12
if
sum(arr[i]%2 == 1)
+= arr[i]; 25
sum += arr[i];
8
return sum;
} return sum; 36
} 9

CeNCE Multidimensional Arrays Unit8 - 12

Computational
1.6 Sum Last 3 Elements (1/3) Thinking time again!

 sumLast3(int arr[], int size) to return the


sum of the last 3 elements among size elements
 Precond: size  0
 Examples:
numbers sumLast3(numbers, size)
{} 0
{5} 5
{ 12, -3 } 9
{ 20, 12, 25, 8, 36, 9 } 53
{ -1, 2, -3, 4, -5, 6, -7, 8, 9, 10 } 27
CeNCE Multidimensional Arrays Unit8 - 13

1.6 Sum Last 3 Elements (2/3)


Thinking…
 Last 3 elements of an array arr int i, count = 0;
 arr[size – 1]
 arr[size – 2] for (i = size - 1; count<3; i--) {
 arr[size – 3] . . .
count++;
 A loop to iterate 3 times }
(hence, need a counter) with
index starting at size – 1 and  But what if there are fewer than
decrementing it in each 3 elements in arr?
iteration

int i, count = 0;
for (i = size - 1; (i >= 0) && (count<3) ; i--) {
. . .
count++;
}

CeNCE Multidimensional Arrays Unit8 - 14

1.6 Sum Last 3 Elements (3/3)


 Complete function:

int sumLast3(int arr[], int size) {


int i, count = 0, sum = 0;

for (i = size - 1; (i>=0) && (count<3); i--) {


sum += arr[i];
count++;
}

return sum;
}
CeNCE Multidimensional Arrays Unit8 - 15

1.7 Minimum Pair Difference (1/3)


 Is it true that all problems on 1D arrays can be solved
by single loop? Of course not!
 Write a function minPairDiff(int arr[], int size)
that computes the minimum possible difference of any
pair of elements in arr.
 For simplicity, assume size > 1 (i.e. there are at least 2
elements in array).
numbers minPairDiff(numbers, size)
{ 20, 12, 25, 8, 36, 9 } 1
{ 431, 945, 64, 841, 43
783, 107, 598 }

CeNCE Multidimensional Arrays Unit8 - 16

1.7 Minimum Pair Difference (2/3)


Thinking… Eg: size = 5. Need to compute difference of
Outer loop index Inner loop index
i from 0 to size-2 arr[1] j from i+1 to size-1
arr[2]
arr[0] Inner loop index
arr[3] j from 1 to size-1
arr[4]

arr[2]
Inner loop index
arr[1] arr[3]
j from 2 to size-1
arr[4]

arr[3] Inner loop index


arr[2]
arr[4] j from 3 to size-1

Inner loop index


arr[3] arr[4] j from 4 to size-1
CeNCE Multidimensional Arrays Unit8 - 17

1.7 Minimum Pair Difference (3/3)


The code…
Outer loop index Inner loop index
i from 0 to size-2 j from i+1 to size-1
int minPairDiff(int arr[], int size) {
int i, j, diff, minDiff;

minDiff = abs(arr[0] – arr[1]); // init min diff.

for (i = 0; i < size-1; i++)


for (j = i+1; j < size; j++) {
diff = abs(arr[i] – arr[j]);
if (diff < minDiff)
minDiff = diff;  This kind of nested loop is found in many
} applications involving 1D array, for
example, sorting (to be covered later).
return minDiff;  In fact, this problem can be solved by
} first sorting the array, then scan through
the array once more to pick the pair of
neighbours with the smallest difference.

CeNCE Multidimensional Arrays Unit8 - 18

Code Provided
 Unit8_FindMax.c:
 Section 1.2 Find Maximum Element
 Unit8_SumElements.c:
 Section 1.3 Sum Elements
 Section 1.4 Sum Alternate Elements
 Section 1.5 Sum Odd Elements
 Section 1.6 Sum Last 3 Elements
 Unit8_MinPairDiff.c:
 Section 1.7 Minimum Pair Difference
CeNCE Multidimensional Arrays Unit8 - 19

1.8 Accessing 1D Array Elements in Function (1/2)


A function header with array parameter, Why is it not necessary to
int sum(int a[ ], int size) have a value in here to
indicate the “real” size?

 A value is not necessary (and is ignored by compiler if provided) as


accessing a particular array element requires only the following
information
 The address of the first element of the array
 The size of each element
 Both information are known
 For example, when the above function is called with
ans = sum(numbers, 6);
in the main(), the address of the first element, &numbers[0], is copied
into the parameter a
 The size of each element is determined since the element type (int) is
given (in sunfire, an integer takes up 4 bytes)

CeNCE Multidimensional Arrays Unit8 - 20

1.8 Accessing 1D Array Elements in Function (2/2)


A function header with array parameter, Why is it not necessary to
int sum(int a[ ], int size) have a value in here to
indicate the “real” size?

 With this, the system is able to calculate the effective address of


the required element, say a[2], by the following formula:
Address of a[2] = base address + (2  size of each element)
where base address is the address of the first element
 Hence, suppose the base address is 2400, then address of a[2] is
2400 + (2  4), or 2408.

a[0] a[1] a[2] a[3]


5 19 12 7 ...
CeNCE Multidimensional Arrays Unit8 - 21

2. Multi-dimensional Arrays (1/2)


 In general, an array can have any number of
dimensions
 Example of a 2-dimensional (2D) array:
// array with 3 rows, 5 columns 0 1 2 3 4
int a[3][5]; 0 2
a[0][0] = 2; 1 16
a[2][4] = 9;
2 9
a[1][0] = a[2][4] + 7;

 Arrays are stored in row-major order


 That is, elements in row 0 comes before row 1, etc.

a[0][0] … a[0][4] a[1][0] … a[1][4] a[2][0] … a[2][4]

row 0 row 1 row 2

CeNCE Multidimensional Arrays Unit8 - 22

2. Multi-dimensional Arrays (2/2)


 Examples of applications:
1 2 3  30 31
 3 8 2 Jan 32.1 31.8 31.9 32.3 32.4
 
  5 2 0 Feb 32.6 32.6 33.0

0 0
 1  4 9 :
 
matrix[3][3] Dec 31.8 32.3 30.9 31.6 32.2

Daily temperatures: temperatures[12][31]


Suise
Jerna
Zass Ex1 Ex2 Ex3
Ex1 Ex2 Ex3
Lab1 52 50 45
Emily Ex1 Ex2 Ex3
Lab1 79 75 66
Lab2 57 60 63
Ex1 Ex2 Ex3 Lab1 59 68 60
Lab2 90 83 77
Lab1 76 80 62 Lab2 0 0 0 Lab3 52 59 66
Lab3 81 73 79
Lab2 60 72 48 Lab3 67 71 75 Lab4 33 42 37
Lab4 58 64 52
Lab5 68 68 72
Lab3 76 80 62 Lab4 38 52 35
Lab5 93 80 85
Lab4 60 72 48 Lab5 78 86 82

Lab5 58 79 73
Students’ lab marks: marks[4][5][3]
CeNCE Multidimensional Arrays Unit8 - 23

2.1 Multi-dimensional Array Initializers


 Examples:
// nesting one-dimensional initializers
int a[3][5] = { {4, 2, 1, 0, 0},
{8, 3, 3, 1, 6},
{0, 0 ,0, 0, 0} };

// the first dimension can be unspecified


int b[][5] = { {4, 2, 1, 0, 0},
{8, 3, 3, 1, 6},
{0, 0, 0, 0, 0} };

// initializer with implicit zero values


int d[3][5] = { {4, 2, 1},
{8, 3, 3, 1, 6} };
What happens to
the uninitialized
elements?

CeNCE Multidimensional Arrays Unit8 - 24

2.2 Multi-dimensional Array: Example


#include <stdio.h> Unit8_2DArray.c
#define N 5 // number of columns in array
int sumArray(int [][N], int); // function prototype

int main(void) {
int foo[][N] = { {3,7,1}, {2,1}, {4,6,2} };
printf("Sum is %d\n", sumArray(foo, 3));
printf("Sum is %d\n", sumArray(foo, 2));
return 0;
}
Second dimension must be
specified; first dimension is
// To sum all elements in arr
not required.
int sumArray(int arr[][N], int rows) {
int i, j, total = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < N; j++) { Sum is 26
total += arr[i][j]; Sum is 13
}
}
return total;
}
CeNCE Multidimensional Arrays Unit8 - 25

2.3 Accessing 2D Array Elements in Function


A function header with 2D array parameter, Why second dimension
function(int a[][5], ...) must be specified, but not
the first dimension?
 To access an element in a 2D array, it must know the number of columns.
It needs not know the number of rows.
 For example, given the following two 2D-arrays:
A 3-column 2D array: A 5-column 2D array:

: :
 As elements are stored linearly in memory in row-major order, element a[1][0]
would be the 4th element in the 3-column array, whereas it would be the 6th
element in the 5-column array.
 Hence, to access a[1][0] correctly, we need to provide the number of columns
in the array.
 For multi-dimensional arrays, all but the first dimension must be specified in
the array parameter.

CeNCE Multidimensional Arrays Unit8 - 26

2.4 Class Enrolment (1/5)


 A class enrolment system can be represented by a 2D array enrol,
where the rows represent the classes, and columns the students. For
simplicity, classes and students are identified by non-negative
integers.
 A ‘1’ in enrol[c][s] indicates student s is enrolled in class c; a ‘0’ means
s is not enrolled in c.
 Assume at most 10 classes and 30 students.
 Example of an enrolment system with 3 classes and 8 students:
0 1 2 3 4 5 6 7  Queries:
0 1 0 1 0 1 1 1 0  Name any class with the most
1 1 0 1 1 1 0 1 1 number of students
2 0 1 1 1 0 0 1 0  Name all students who are
enrolled in all the classes
CeNCE Multidimensional Arrays Unit8 - 27

2.4 Class Enrolment (2/5)


 Inputs:
 Number of classes and students
 Number of data entries
 Each data entry consists of 2 integers s and c indicating that student s is
enrolled in class c.
 Sample input:
Number of classes and students: 3 8
Number of data entries: 15
Enter 15 entries (student class): 0 1 2 3 4 5 6 7
3 1
0 0 0 1 0 1 0 1 1 1 0
0 1
1 2 1 1 0 1 1 1 0 1 1
2 0
2 1 2 0 1 1 1 0 0 1 0
2 2
3 2
7 1
6 0
5 0
4 1
4 0
6 2
6 1

CeNCE Multidimensional Arrays Unit8 - 28

2.4 Class Enrolment (3/5)


#define MAX_CLASSES 10
#define MAX_STUDENTS 30
int main(void) {
int enrol[MAX_CLASSES][MAX_STUDENTS] = { {0} }, numClasses, numStudents;

printf("Number of classes and students: ");


scanf("%d %d", &numClasses, &numStudents);
readInputs(enrol, numClasses, numStudents);

return 0;
} // Read data into array enrol
3 8
void readInputs(int enrol[][MAX_STUDENTS],
15
3 1 int numClasses, int numStudents) {
0 0 int entries; // number of data entries
0 1 int i, class, student;
1 2
2 0 printf("Number of data entries: ");
2 1 scanf("%d", &entries);
2 2
3 2 printf("Enter %d data entries (student class): \n", entries);
7 1 // Read data into array enrol
6 0
for (i = 0; i < entries; i++) {
5 0
scanf("%d %d", &student, &class); 0 1 2 3 4 5 6 7
4 1
4 0 enrol[class][student] = 1; 0 1 0 1 0 1 1 1 0
6 2 } 1 1 0 1 1 1 0 1 1
6 1 } 2 0 1 1 1 0 0 1 0
CeNCE Multidimensional Arrays Unit8 - 29

2.4 Class Enrolment (4/5)


 Query 1: Name any class with the most number of students
Row sums
int classWithMostStudents 0 1 2 3 4 5 6 7
(int enrol[][MAX_STUDENTS], 0 1 0 1 0 1 1 1 0 5
int numClasses, int numStudents) { 1 1 0 1 1 1 0 1 1 6
int classSizes[MAX_CLASSES];
int r, c; // row and column indices
2 0 1 1 1 0 0 1 0 4
int maxClass, i;

for (r = 0; r < numClasses; r++)


classSizes[r] = 0;
for (c = 0; c < numStudents; c++) {
classSizes[r] += enrol[r][c];
}

// find the one with most students


maxClass = 0; // assume class 0 has most students
for (i = 1; i < numClasses; i++)
if (classSizes[i] > classSizes[maxClass])
maxClass = i;

return maxClass;
}

CeNCE Multidimensional Arrays Unit8 - 30

2.4 Class Enrolment (5/5)


 Query 2: Name all students who are enrolled in all classes
0 1 2 3 4 5 6 7
// Find students who are enrolled in all classes 0 1 0 1 0 1 1 1 0
void busiestStudents(int enrol[][MAX_STUDENTS],
1 1 0 1 1 1 0 1 1
int numClasses, int numStudents) {
2 0 1 1 1 0 0 1 0
int sum;
int r, c; 2 1 3 2 2 1 3 1

printf("Students who take all classes: "); Column sums


for (c = 0; c < numStudents; c++) {
sum = 0;
for (r = 0; r < numClasses; r++) {
sum += enrol[r][c];
}
if (sum == numClasses)
printf("%d ", c);
}
printf("\n");
} Refer to Unit8_ClassEnrolment.c
for complete program.
CeNCE Multidimensional Arrays Unit8 - 31

2.5 Matrix Addition (1/2)


 To add two matrices, both must have the same size
(same number of rows and columns).
 To compute C = A + B, where A, B, C are matrices
ci,j = ai,j + bi,j
 Examples:
1 2 0  1 0 0   0 2 0
     
0 1 1   2 1 0    2 2 1
1 0 1  0 2  1  1 2 0
     

10 21 7 9   3 7 18 20  13 28 25 29 
       
 4 6 14 5   6 5 8 15   10 11 22 20 

CeNCE Multidimensional Arrays Unit8 - 32

2.5 Matrix Addition (2/2)


Unit8_MatrixOps.c
// To sum mtxA and mtxB to obtain mtxC
void sumMatrix(float mtxA[][MAX_COL], float mtxB[][MAX_COL],
float mtxC[][MAX_COL], int row_size, int col_size) {
int row, col;
for (row=0; row<row_size; row++)
for (col=0; col<col_size; col++)
mtxC[row][col] = mtxA[row][col] + mtxB[row][col];
}

10 21 7 9 3 7 18 20 13
? 28
? 25
? 29
?
+ =
4 6 14 5 6 5 8 15 10
? 11
? 22
? 20
?
CeNCE Multidimensional Arrays Unit8 - 33

3. Exercise: Pyramid (1/4)


Given a pyramid of integers, you can trace a path from
top to bottom, moving from a number to either the
number on its left or right in the next row below.
Find the largest sum possible.

5 5 5

3 1 3 1 3 1

2 3 8 2 3 8 2 3 8

5 2 4 3 5 2 4 3 5 2 4 3

Figure 1. (a) A pyramid of integers. (b) A path with sum of 13. (c) A path with sum of 18.

CeNCE Multidimensional Arrays Unit8 - 34

3. Exercise: Pyramid (2/4)


Unit8_Pyramid.c
#include <stdio.h>
#define MAX_ROWS 10

int maxPathValue(int [][MAX_ROWS], int);


int scanTriangularArray(int [][MAX_ROWS]);
void printTriangularArray(int [][MAX_ROWS], int);

int main(void) {
int size; // number of rows in the pyramid
int table[MAX_ROWS][MAX_ROWS];

size = scanTriangularArray(table);
// printTriangularArray(table, size); // for checking

printf("Maximum path value = %d\n", maxPathValue(table, size));

return 0;
}
CeNCE Multidimensional Arrays Unit8 - 35

3. Exercise: Pyramid (3/4)


Unit8_Pyramid.c
// Read data into the 2-dimensional triangular array arr,
// and return the number of rows in the array.
int scanTriangularArray(int arr[][MAX_ROWS]) {
int num_rows, r, c;
printf("Enter number of rows: "); scanf("%d", &num_rows);
printf("Enter values for array: \n");
for (r = 0; r < num_rows; r++)
for (c = 0; c <= r; c++)
scanf("%d", &arr[r][c]);

return num_rows;
}

// Print elements in the 2-dimensional triangular array arr.


void printTriangularArray(int arr[][MAX_ROWS], int size) {
int r, c;
for (r = 0; r < size; r++) {
for (c = 0; c <= r; c++)
printf("%d\t", arr[r][c]);
printf("\n");
}
}

CeNCE Multidimensional Arrays Unit8 - 36

3. Exercise: Pyramid (4/4)


Unit8_Pyramid.c
// Compute the maximum path sum.
int maxPathValue(int arr[][MAX_ROWS], int size) {

return 123;
}
CeNCE Multidimensional Arrays Unit8 - 37

Summary
 In this unit, you have learned about
 Declaring 2D arrays
 Using 2D arrays in problem solving

CeNCE Multidimensional Arrays Unit8 - 38

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 9
Characters and Strings

CeNCE CS1 Problem Solving Methodology Unit9 - 2

Unit 9: Characters and Strings


Objectives:
 Declare and manipulate data of char data type
 Learn fundamental operations on strings
 Write string processing programs
© CeNCE CS1 Problem Solving Methodology Unit9 - 3

Unit 9: Characters and Strings (1/2)


1. Motivation
2. Characters
2.1 ASCII Table
2.2 Demo #1: Using Characters
2.3 Demo #2: Character I/O
2.4 Demo #3: Character Functions
2.5 Exercise 1
2.6 Common Error
3. Strings
3.1 Basics
3.2 String I/O
3.3 Demo #4: String I/O
3.4 Demo #5: Remove Vowels
3.5 Demo #6: Character Array without terminating ‘\0’

© CeNCE CS1 Problem Solving Methodology Unit9 - 4

Unit 9: Characters and Strings (2/2)


4. String Functions
5. Pointer to String
6. Array of Strings
7. Demo #7: Using String Functions
8. Strings and Pointers
9. String Function – strtok( )
© CeNCE CS1 Problem Solving Methodology Unit9 - 5

1. Motivation
 Why study characters and strings?
 Hangman game – Player tries to guess a word by filling
in the blanks. Each incorrect guess brings the player
closer to being “hanged”
 Let’s play! http://www.hangman.no/

© CeNCE CS1 Problem Solving Methodology Unit9 - 6

2. Characters
 In C, single characters are represented using the data
type char
 Character constants are written as symbols enclosed in
single quotes
 Examples: 'g', '8', '*', ' ', '\n', '\0'
 Take note that “g”, “8”, etc have totally different meaning.
 Characters are stored in one byte, and are encoded as
numbers using the ASCII scheme
 ASCII (American Standard Code for Information
Interchange), is one of the document coding schemes
widely used today
 Unicode is another commonly used standard for multi-
language texts
© CeNCE CS1 Problem Solving Methodology Unit9 - 7

2.1 Characters: ASCII Table


9

For example,
character 'O' is
70 O 79 (row value
70 + col value 9
= 79).

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

© CeNCE CS1 Problem Solving Methodology Unit9 - 8

2.2 Demo #1: Using Characters (1/2)


// Unit9_CharacterDemo1.c Unit9_CharacterDemo1.c
#include <stdio.h>

int main(void) { Declaring and initialising


char variables.
char grade = 'A', newgrade, ch;
int value; Using %c
grade = A
printf("grade = %c\n", grade); newgrade = C
newgrade = grade + 2;
printf("newgrade = %c\n", newgrade);
newgrade = 67
printf("newgrade = %d\n", newgrade);

value = 65; value = 65


printf("value = %d\n", value); value = A
printf("value = %c\n", value);
Relationship between
character and integer.
© CeNCE CS1 Problem Solving Methodology Unit9 - 9

2.2 Demo #1: Using Characters (2/2)


Comparing characters.

if ('A' < 'c')


printf("'A' is less than 'c'\n");
else
printf("'A' is not less than 'c'\n");
Using character variable
for (ch = 'p'; ch <= 't'; ch++)
as a loop variable.
printf("ch = %c\n", ch);

return 0; 'A' is less than 'c'


}
ch = p ASCII value of 'A'
ch = q is 65. ASCII
ch = r value of 'c' is 99.
ch = s
ch = t

© CeNCE CS1 Problem Solving Methodology Unit9 - 10

2.3 Demo #2: Character I/O


 Besides scanf() and printf(), we can also use getchar()
and putchar(). Note how they are used below:
// Unit9_CharacterDemo2.c Unit9_CharacterDemo2.c
#include <stdio.h>

int main(void) { Read a character


from stdin.
char ch;

printf("Enter a character: "); Enter a character: W


ch = getchar(); Character entered is W
printf("The character entered is ");
putchar(ch);
putchar('\n');

return 0; Print a character


} to stdout.
© CeNCE CS1 Problem Solving Methodology Unit9 - 11

2.4 Demo #3: Character Functions


 Must include <ctype.h> to use these functions.
// Unit9_CharacterDemo3.c Unit9_CharacterDemo3.c
#include <stdio.h>
#include <ctype.h> Download this program and test it out.
int main(void) {
char ch;
For a complete list of character functions,
refer to the Internet (eg:
printf("Enter a character: ");
ch = getchar();
https://www.tutorialspoint.com/c_standard
if (isalpha(ch)) { _library/ctype_h.htm )
if (isupper(ch)) {
printf("'%c' is a uppercase-letter.\n", ch); Note that
printf("Converted to lowercase: %c\n", tolower(ch));
tolower(ch) and
} toupper(ch) do
if (islower(ch)) {
NOT change ch!
printf("'%c' is a lowercase-letter.\n", ch);
printf("Converted to uppercase: %c\n", toupper(ch));
}
}
if (isdigit(ch)) printf("'%c' is a digit character.\n", ch);
if (isalnum(ch)) printf("'%c' is an alphanumeric character.\n", ch);
if (isspace(ch)) printf("'%c' is a whitespace character.\n", ch);
if (ispunct(ch)) printf("'%c' is a punctuation character.\n", ch);
return 0;
}

© CeNCE CS1 Problem Solving Methodology Unit9 - 12

2.5 Ex #1: Summing Digit Characters (1/4)


 Write a program Unit9_SumDigits.c to read
characters on a line, and sum the digit characters,
ignoring the non-digit ones and everything after the
first white space.
 Use the appropriate functions introduced in Demos
#2 and #3.
 Two sample runs:
Enter input: v7o/K3-968+?.2 +
Sum = 35

Enter input: ^71()-2%:46" 9W35j


Sum = 20
© CeNCE CS1 Problem Solving Methodology Unit9 - 13

2.5 Ex #1: Summing Digit Characters (2/4)


 Refer to this web page:
 https://www.tutorialspoint.com/c_standard_library/ctype_h.
htm
 What is the input function needed if we do not want to
use scanf())? getchar()
 What are the character functions needed?
isdigit()
isspace()
 What header file to include besides <stdio.h>?
<ctype.h>

© CeNCE CS1 Problem Solving Methodology Unit9 - 14

2.5 Ex #1: Summing Digit Characters (3/4)


 How do we obtain an integer value from a digit
character (let ch be the character variable)?
 i.e.: ‘0’  0. ‘1’  1, …, ‘9’  9

Hint: ASCII value


 What is the ASCII value of character ‘0’? 48
 What is the ASCII value of character ‘1’? 49
 …
 What is the ASCII value of character ‘9’? 57

ch – 48 or ch – ‘0’
© CeNCE CS1 Problem Solving Methodology Unit9 - 15

2.5 Ex #1: Summing Digit Characters (4/4)

#include <stdio.h>
#include <ctype.h>
int main(void) {
char ch;
int sum = 0;
printf("Enter input: ");
while (!isspace(ch = getchar()))
if (isdigit(ch))
sum += ch - '0';
printf("Sum = %d\n", sum);
return 0;
}

© CeNCE CS1 Problem Solving Methodology Unit9 - 16

2.6 Characters: Common Error


 A character variable named z does not means it is
equivalent to 'z' or it contains 'z'!
char A, B, C, D, F; if (marks >= 80)
return 'A';
if (marks >= 80) else if (marks >= 70)
return A; return 'B';
else if (marks >= 70) else if (marks >= 60)
return B; return 'C';
else if (marks >= 60) . . .
return C;
. . .
char grade;
if (marks >= 80)
grade = 'A';
else if (marks >= 70)
grade = 'B';
else if (marks >= 60)
grade = 'C';
. . .
return grade;
© CeNCE CS1 Problem Solving Methodology Unit9 - 17

Quick Quiz
1. Are 'A' and "A" the same thing? No

2. Can you do this?


No
 char ch = 'at';
3. Can char be used in a switch statement?
How about a string?
char – yes
string – no

© CeNCE CS1 Problem Solving Methodology Unit9 - 18

3. Strings
 We have seen arrays of numeric values (types
int, float, double)
 We have seen string constants
 printf("Average = %.2f", avg);
 #define ERROR "*****Error –"
 A string is an array of characters, terminated by
a null character '\0' (which has ASCII value of
zero)
c s 1 0 1 0 \0
© CeNCE CS1 Problem Solving Methodology Unit9 - 19

3.1 Strings: Basics


 Declaration of an array of characters
• char str[6];

 Assigning character to an element of an array of


characters
• str[0] = 'e'; e g g \0 ? ?
• str[1] = 'g';
• str[2] = 'g'; Without ‘\0’, it is just an array
• str[3] = '\0'; of character, not a string.

 Initializer for string Do not need ‘\0’ as it is


automatically added.
 Two ways:
• char fruit_name[] = "apple";
• char fruit_name[] = {'a','p','p','l','e','\0'};

© CeNCE CS1 Problem Solving Methodology Unit9 - 20

3.2 Strings: I/O (1/2)


 Read string from stdin
fgets(str, size, stdin) // reads size – 1 char,
// or until newline
scanf("%s", str); // reads until white space

 Print string to stdout


puts(str); // terminates with newline
printf("%s\n", str);

Note: There is another function gets(str) to read a string


interactively. However, due to security reason, we avoid it
and use fgets() function instead.
© CeNCE CS1 Problem Solving Methodology Unit9 - 21

3.2 Strings: I/O (2/2)


 fgets()
 On interactive input, fgets() also reads in the newline
character
User input: eat e a t \n \0 ? ?

 Hence, we may need to replace it with '\0' if


necessary
fgets(str, size, stdin);
len = strlen(str);
if (str[len – 1] == '\n')
str[len – 1] = '\0';

© CeNCE CS1 Problem Solving Methodology Unit9 - 22

3.3 Demo #4: String I/O


Unit9_StringIO1.c
#include <stdio.h>
#define LENGTH 10
Test out the programs with this input:
int main(void) { My book
char str[LENGTH];
printf("Enter string (at most %d characters): ", LENGTH-1);
scanf("%s", str);
printf("str = %s\n", str); Output:
return 0; str = My
}
#include <stdio.h>
Output: Unit9_StringIO2.c
#define LENGTH 10
str = My book
int main(void) {
char str[LENGTH];
printf("Enter string (at most %d characters): ", LENGTH-1);
fgets(str, LENGTH, stdin);
printf("str = "); Note that puts(str) adds
puts(str); a newline automatically.
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 23

3.4 Demo #5: Remove Vowels (1/2)


 Write a program Unit9_RemoveVowels.c to
remove all vowels in a given input string.
 Assume the input string has at most 100
characters.
 Sample run:
Enter a string: How HAVE you been, James?
Changed string: Hw HV y bn, Jms?

© CeNCE CS1 Problem Solving Methodology Unit9 - 24

3.4 Demo #5: Remove Vowels (2/2)


#include <stdio.h> Unit9_RemoveVowels.c
#include <string.h>
#include <ctype.h>
int main(void) { Need to include <string.h>
int i, len, count = 0; to use string functions such
char str[101], newstr[101]; as strlen().
printf("Enter a string (at most 100 characters): ");
fgets(str, 101, stdin); //what happens if you use scanf() here?
len = strlen(str); // strlen() returns number of char in string
if (str[len – 1] == '\n')
str[len – 1] = '\0';
len = strlen(str); // check length again
for (i=0; i<len; i++) {
switch (toupper(str[i])) {
case 'A': case 'E':
case 'I': case 'O': case 'U': break;
default: newstr[count++] = str[i];
}
}
newstr[count] = '\0';
printf("New string: %s\n", newstr);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 25

3.5 Demo #6: Character Array without terminating ‘\0’


 What is the output of this code?
Unit9_without_null_char.c
#include <stdio.h>
#include <string.h> printf() will print
One possible output: %s from the
int main(void) { Length = 8 starting
char str[10]; str = apple¿ø< address of str
until it
str[0] = 'a'; Compare the output if you add:
encounters the
str[1] = 'p'; str[5] = '\0';
str[2] = 'p'; ‘\0’ character.
str[3] = 'l'; or, you have:
str[4] = 'e'; char str[10] = "apple";

printf("Length = %d\n", strlen(str));


printf("str = %s\n", str);

return 0; %s and string functions work only on “true” strings.


} Without the terminating null character ‘\0’, string
functions will not work properly.

© CeNCE CS1 Problem Solving Methodology Unit9 - 26

4. String Functions (1/3)


 C provides a library of string functions
 Must include <string.h>
 http://faculty.edcc.edu/paul.bladek/c_string_functions.htm
 http://www.cs.cf.ac.uk/Dave/C/node19.html
 and other links you can find on the Internet
 strcmp(s1, s2)
 Compare the ASCII values of the corresponding characters in
strings s1 and s2.
 Return
 a negative integer if s1 is lexicographically less than s2, or
 a positive integer if s1 is lexicographically greater than s2, or
 0 if s1 and s2 are equal.
 strncmp(s1, s2, n)
 Compare first n characters of s1 and s2.
© CeNCE CS1 Problem Solving Methodology Unit9 - 27

4. String Functions (2/3)


 strcpy(s1, s2)
 Copy the string pointed to by s2 into array pointed to by s1.
 Function returns s1.
 Example:
char name[10]; M a t t h e w \0 ? ?
strcpy(name, "Matthew");
 The following assignment statement does not work:
name = "Matthew";
 What happens when string to be copied is too long?
strcpy(name, "A very long name");
A v e r y l o n g n a m e \0

 strncpy(s1, s2, n)
 Copy first n characters of string pointed to by s2 to s1.

© CeNCE CS1 Problem Solving Methodology Unit9 - 28

4. String Functions (3/3)


 strstr(s1, s2)
 Returns a pointer to the first instance of string s2 in s1
 Returns a NULL pointer if s2 is not found in s1

 We will use the functions above in Demo #7


 Read up on the above functions
 Other functions (atoi, strcat, strchr, strtok, etc.)
 We will explore these in your discussion session
© CeNCE CS1 Problem Solving Methodology Unit9 - 29

5. Pointer to String (1/2)


#include <stdio.h> name is a character array of 12 elements.
#include <string.h> namePtr is a pointer to a character.
int main(void) { Both have strings assigned.
char name[12] = "Chan Tan"; Difference is name sets aside space for 12
char *namePtr = "Chan Tan"; characters, but namePtr is a char pointer
variable that is initialized to point to a string
printf("name = %s\n", name); constant of 9 characters.
printf("namePtr = %s\n", namePtr);
printf("Address of 1st array element for name = %p\n", name);
printf("Address of 1st array element for namePtr = %p\n",namePtr);

strcpy(name, "Lee Hsu"); name updated using strcpy().


namePtr = "Lee Hsu"; namePtr assigned to another string using =.

printf("name = %s\n", name);


printf("namePtr = %s\n", namePtr);
printf("Address of 1st array element for name = %p\n", name);
printf("Address of 1st array element for namePtr = %p\n",namePtr);
} Address of first array element for name
remains constant, string assigned to
Unit9_StringPointer.c namePtr changes on new assignment.

© CeNCE CS1 Problem Solving Methodology Unit9 - 30

5. Pointer to String (2/2)


 Comparison
char name[12] = "Chan Tan";
name[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

C h a n T a n \0 \0 \0 \0

namePtr char *namePtr = "Chan Tan";

C h a n T a n \0
© CeNCE CS1 Problem Solving Methodology Unit9 - 31

6. Array of Strings Unit9_ArrayOfStrings.c

 Declaration
char fruits[MAXNUM][STRSIZE];
// where MAXNUM is the maximum number of names
// and STRSIZE is the size of each name

 Initialization
char fruits[][6] = {"apple", "mango", "pear"};
or
char fruits[3][6] = {"apple", "mango", "pear"};
 Output
printf("fruits: %s %s\n", fruits[0], fruits[1]);
printf("character: %c\n", fruits[2][1]);
fruits: apple mango
character: e

© CeNCE CS1 Problem Solving Methodology Unit9 - 32

7. Demo #7: Using String Functions


#include <stdio.h>
#include <string.h> Unit9_StringFunctions.c
#define MAX_LEN 10
int main(void) {
char s1[MAX_LEN + 1], s2[MAX_LEN + 1], *p;
int len;
printf("Enter string (at most %d characters) for s1: ", MAX_LEN);
fgets(s1, MAX_LEN+1, stdin);
len = strlen(s1);
if (s1[len – 1] == '\n') s1[len – 1] = '\0';
printf("Enter string (at most %d characters) for s2: ", MAX_LEN);
fgets(s2, MAX_LEN+1, stdin);
len = strlen(s2);
if (s2[len – 1] == '\n') s2[len – 1] = '\0';

printf("strcmp(s1,s2) = %d\n", strcmp(s1,s2));


p = strstr(s1,s2);
if (p != NULL) printf("strstr(s1,s2) returns %s\n", p);
else printf("strstr(s1,s2) returns NULL\n");

strcpy(s1,s2);
printf("After strcpy(s1,s2), s1 = %s\n", s1);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 33

8. Strings and Pointers (1/4)


 We discussed in Unit #7 Section 4 that an array name is
a pointer (that points to the first array element)
 Likewise, since a string is physically an array of
characters, the name of a string is also a pointer (that
points to the first character of the string)
Unit9_String_vs_Pointer.c
char str[] = "apple";
1st character: a
printf("1st character: %c\n", str[0]);
1st character: a
printf("1st character: %c\n", *str);
5th character: e
printf("5th character: %c\n", str[4]); 5th character: e
printf("5th character: %c\n", *(str+4));

© CeNCE CS1 Problem Solving Methodology Unit9 - 34

8. Strings and Pointers (2/4)


 Unit9_strlen.c shows how we could compute the length of
a string if we are not using strlen()
 See full program on CS1 coursemology

Unit9_strlen.c
int mystrlen(char *p) {
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 35

8. Strings and Pointers (3/4)


 Since ASCII value of null character '\0' is zero, the
condition in the while loop is equivalent to (*p != 0)
and that can be further simplified to just (*p) (see left
box)
 We can combine *p with p++ (see right box) (why?)
int mystrlen(char *p) { int mystrlen(char *p) {
int count = 0; int count = 0;
while (*p) { while (*p++) {
count++; count++;
p++; }
}
return count;
return count; }
Unit9_strlen_v2.c
}

© CeNCE CS1 Problem Solving Methodology Unit9 - 36

8. Strings and Pointers (4/4)


 How to interpret the following?
while (*p++)

Then, increment p by 1
Check whether *p is 0 (so that p points to the
(that is, whether *p is the next character).
null character ‘\0’)… Not increment *p by 1!

(*p++) is not the same as (*p)++


(*p)++ is to increment *p (the
character that p points to) by 1. (Hence, if
p is pointing to character ‘a’, that character
becomes ‘b’.)
© CeNCE CS1 Problem Solving Methodology Unit9 - 37

9. String function: strtok() (1/2)


 To break a string into a series of tokens using some
specified delimiter(s).
char *strtok(char *str, const char *delim)

 Read the following site:


 http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

 The first time you call strtok() you pass it: (1) the string
you want to tokenise, and (2) a delimiter string.
 For subsequent calls, you pass it: (1) NULL as the first
paramater to tokenise the same string, and (2) a
delimiter string.

© CeNCE CS1 Problem Solving Methodology Unit9 - 38

9. String function: strtok() (2/2)


Unit9_strtok.c
#include <string.h>
#include <stdio.h>
int main(void) {
char str[80] = "This is - www.tutorialspoint.com - website";
char s[2] = "-";
char *token; Output:
/* get the first token */ This is
token = strtok(str, s); www.tutorialspoint.com
website
/* walk through other tokens */
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, s);
}
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 39

Example: Hangman Game


 http://www.hangman.no/

Let’s play!

© CeNCE CS1 Problem Solving Methodology Unit9 - 40

Hangman Game version 1 (1/5)


 Unit9_Hangman_v1.c
 Assume that a player is given 5 lives.
 Each incorrect guess  reduce the number of lives.
 Each correct guess  display the letter in the word.
© CeNCE CS1 Problem Solving Methodology Unit9 - 41

Hangman Game version 1 (2/5)


 Sample run #1:  Sample run #2:
Number of lives: 5
Guess a letter in the word _ _ _ _ _ Number of lives: 5
h Guess a letter in the word _ _ _ _ _
Number of lives: 4 p
Guess a letter in the word _ _ _ _ _ Number of lives: 5
p Guess a letter in the word _ p p _ _
Number of lives: 4 e
Guess a letter in the word _ p p _ _ Number of lives: 5
b Guess a letter in the word _ p p _ e
Number of lives: 3 o
Guess a letter in the word _ p p _ _ Number of lives: 4
m Guess a letter in the word _ p p _ e
Number of lives: 2 a
Guess a letter in the word _ p p _ _ Number of lives: 4
x Guess a letter in the word a p p _ e
Number of lives: 1 l
Guess a letter in the word _ p p _ _ Congratulations! The word is "apple".
i
Sorry, you’re hanged! The word is "apple".

© CeNCE CS1 Problem Solving Methodology Unit9 - 42

Hangman Game version 1 (3/5)


#include <stdio.h>
#include <string.h> Unit9_Hangman_v1.c

int has_letter(char [], char);

int main(void) {
char input;
char word[] = "apple";
char temp[] = "_____";
int i, count = 0;
int num_lives = 5;
int length = strlen(word);
© CeNCE CS1 Problem Solving Methodology Unit9 - 43

Hangman Game version 1 (4/5)


do {
Unit9_Hangman_v1.c
printf("Number of lives: %d\n", num_lives);
printf("Guess a letter in the word ");
puts(temp);
scanf(" %c", &input);

if (has_letter(word, input)) {
for (i=0; i<length; i++)
if ((input == word[i]) && (temp[i] == '_')) {
temp[i] = input;
count++;
}
}
else num_lives--;
} while ((num_lives != 0) && (count != length));
if (num_lives == 0)
printf("Sorry, you're hanged! The word is \"%s\"\n", word);
else
printf("Congratulations! The word is \"%s\"\n", word);
return 0;
}

© CeNCE CS1 Problem Solving Methodology Unit9 - 44

Hangman Game version 1 (5/5)


Unit9_Hangman_v1.c
// Check whether word contains ch
int has_letter(char word[], char ch) {
int j;
int length = strlen(word);
Note: It is better to call
strlen(word) just once and save
for (j=0; j<length; j++) {
the length in a variable, instead
if (ch == word[j])
of calling strlen(word) multiple
return 1;
times as a condition in the ‘for’
}
loop.
return 0; // ch does not occur in word
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 45

Summary
 In this unit, you have learned about
 Characters
 Declaring and using characters
 Characters I/O
 Character functions

 Strings
 Declaring and initialising strings
 String I/O
 String functions
 Array of strings

© CeNCE CS1 Problem Solving Methodology Unit9 - 46

End of File
CS1:
PROGRAMMING METHODOLOGY

Unit 10
Structures

© CeNCE CS1 Problem Solving Methodology Unit10 - 2

Unit 10: Structures


Objectives:
 Learn how to create and use structures
 Learn how to return 2 or more values from a function
using structures
 Learn how to create and use structures with strings
 Learn how to pass structures to functions
 Learn how to use an array of structures
© CeNCE CS1 Problem Solving Methodology Unit10 - 3

Unit 10: Structures


1. Organizing Data
2. Structure Types
3. Structure Variables
3.1 Initializing Structure Variables
3.2 Accessing Members of a Structure Variable
3.3 Demo #1: Initializing and Accessing Structure Members
4. Structures with Strings
5. The Arrow Operator (->)
6. Reading a Structure Member

© CeNCE CS1 Problem Solving Methodology Unit10 - 4

Unit 10: Structures


7. Assigning Structures
8. Exercise 1: Points
9. Exercise 2: Perimeter
10. Passing Structures to Function.
11. Returning Structure from Functions
12. Array of Structures
13. Case Study: Nearby Stores
14. Exercise 3: Health Screening
© CeNCE CS1 Problem Solving Methodology Unit10 - 5

1. Organizing Data (1/4)


 Write a program to compute the volume of 2 boxes.
int length1, width1, height1; // for 1st box
int length2, width2, height2; // for 2nd box

length1 width1 height1 length2 width2 height2

 More logical to organize related data as a “box” group,


with length, width and height as its components
(members). Then declare two variables box1 and box2
of such a group.
box1 box2
length width height length width height

© CeNCE CS1 Problem Solving Methodology Unit10 - 6

1. Organizing Data (2/4)


 The members of a group may be heterogeneous (of
different types) (as opposed to an array whose
elements must be homogeneous)
 Examples:
account
acctNum balance

contains an integer contains a real number

result
stuNum score grade

contains an integer contains a real number contains a character


© CeNCE CS1 Problem Solving Methodology Unit10 - 7

1. Organizing Data (3/4)


 A group can be a member of another group.
 Example: the expiry date of a membership card is of
“date” group
date
day month year

card

cardNum expiryDate
day month year

© CeNCE CS1 Problem Solving Methodology Unit10 - 8

1. Organizing Data (4/4)


 We can also create array of groups
 Example: enrolment data for modules
 Using two parallel arrays codes enrolments
o codes[i] and enrolments[i] are CS1010 292
related to the same module i CS1234 178
CS1010E 358
: :

 Using an array of “module” group modules


 Which is more logical? CS1010 292

CS1234 178

CS1010E 358

:
© CeNCE CS1 Problem Solving Methodology Unit10 - 9

2. Structure Types (1/2)


 Such a group is called structure type
 Examples of structure types:
This semi-colon ; is
very important and is
typedef struct {
often forgotten!
int length, width, height;
} box_t;

Create a new type called box_t

typedef struct { typedef struct {


int acctNum; int stuNum;
float balance; float score;
} account_t; char grade;
} result_t;
Create a new type called account_t
Create a new type called result_t

© CeNCE CS1 Problem Solving Methodology Unit10 - 10

2. Structure Types (2/2)


 A type is NOT a variable!
 what are the differences between a type and a variable?
 The following is a definition of a type, NOT a
declaration of a variable
 A type needs to be defined before we can declare variable of
that type
 No memory is allocated to a type

typedef struct {
int acctNum;
float balance;
} account_t;
© CeNCE CS1 Problem Solving Methodology Unit10 - 11

3. Structure Variables
 Declaration
 The syntax is similar to declaring ordinary variables.

typedef struct {
int stuNum;
float score; Before function prototypes
(but after preprocessor directives)
char grade;
} result_t;

result_t result1, result2; Inside any function

© CeNCE CS1 Problem Solving Methodology Unit10 - 12

3.1 Initializing Structure Variables


 The syntax is like array initialization
 Examples: typedef struct {
int day, month, year;
} date_t;

typedef struct {
int cardNum;
date_t birthday;
typedef struct {
} card_t;
int stuNum;
float score;
card_t card1 = {888888, {31, 12, 2020}};
char grade;
} result_t;

result_t result1 = { 123321, 93.5, 'A' };


© CeNCE CS1 Problem Solving Methodology Unit10 - 13

3.2 Accessing Members of a Structure Variable

 Use the dot (.) operator

result_t result2;

result2.stuNum = 456654;
result2.score = 62.0;
result2.grade = 'D';

card_t card2 = { 666666, {30, 6} };

card2.expiryDate.year = 2021;

© CeNCE CS1 Problem Solving Methodology Unit10 - 14

3.3 Demo #1: Initializing and Accessing Members


#include <stdio.h> Unit10_Demo1.c

typedef struct { result1: stuNum = 123321; score = 93.5; grade = A


int stuNum; result2: stuNum = 456654; score = 62.0; grade = D
float score; Type definition
char grade;
} result_t;
Initialization
int main(void) {
result_t result1 = { 123321, 93.5, 'A' },
result2;
result2.stuNum = 456654;
result2.score = 62.0; Accessing
result2.grade = 'D'; members
printf("result1: stuNum = %d; score = %.1f; grade = %c\n",
result1.stuNum, result1.score, result1.grade);
printf("result2: stuNum = %d; score = %.1f; grade = %c\n",
result2.stuNum, result2.score, result2.grade);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 15

4. Structures with Strings


 Besides the primitive data types, structures may include
Strings (Unit #9) as well.
 Examples of structure types:
typedef struct { typedef struct {
char code[8]; char name[12];
int enrolment; int age;
} module_t; char gender;
} player_t;

© CeNCE CS1 Problem Solving Methodology Unit10 - 16

4.1 Initializing Structures with Strings (1/2)


typedef struct {
char name[12];
int age;
char gender;
} player_t;

 Using initializers:
player_t player1 = { "Brusco", 23, 'M' };

 Using string functions:


player_t player2;
strcpy(player2.name, "July");
player2.age = 21;
player2.gender = 'F';
© CeNCE CS1 Problem Solving Methodology Unit10 - 17

4.1 Initializing Structures with Strings (2/2)


typedef struct {
char name[12];
int age;
char gender;
} player_t;

 Using scanf():
player_t player3;
Why is there no need
printf("Enter name, age and gender: ");
scanf("%s %d %c", player3.name,
for & to read in name?
&player3.age, &player3.gender);

 Using assignment:
player_t player4 = player3; = strcpy(player4.name, player3.name);
player4.age = player3.age;
player4.gender = player3.gender;

© CeNCE CS1 Problem Solving Methodology Unit10 - 18

5. The Arrow Operator (->) (1/2)


 Expressions like (*player_ptr).name appear very
often. Hence an alternative “shortcut” syntax is
created for it.
 The arrow operator (->)
(*player_ptr).name is equivalent to player_ptr->name

(*player_ptr).age is equivalent to player_ptr->age

 Can we write *player_ptr.name instead of


(*player_ptr).name?
 No, because . (dot) has higher precedence than *, so
*player_ptr.name means *(player_ptr.name)!
© CeNCE CS1 Problem Solving Methodology Unit10 - 19

5. The Arrow Operator (->) (2/2)


 Function change_name_and_age() in
Unit10_Demo4.c modified to use the -> operator.
Unit10_Demo2.c
// To change a player’s name and age
void change_name_and_age(player_t *player_ptr) {
strcpy(player_ptr->name, "Alexandra");
player_ptr->age = 25;
}

Unit10_Demo2.c is Unit18_Demo4.c

© CeNCE CS1 Problem Solving Methodology Unit10 - 20

6. Reading a Structure Member


 The structure members are read in individually the
same way as we do for ordinary variables
 Example:
result_t result1;

printf("Enter student number, score and grade: ");

scanf("%d %f %c", &result1.stuNum, &result1.score,


&result1.grade);
© CeNCE CS1 Problem Solving Methodology Unit10 - 21

7. Assigning Structures
 We use the dot operator (.) to access individual
member of a structure variable.
 If we use the structure variable’s name, we are
referring to the entire structure.
 Unlike arrays, we may do assignments with structures
result2.stuNum = result1.stuNum;
result2 = result1; = result2.score = result1.score;
result2.grade = result1.grade;
Before: After:
result1 result1
stuNum score grade stuNum score grade
123321 93.5 'A' 123321 93.5 'A'
result2 result2
stuNum score grade stuNum score grade
456654 62.0 'D' 123321 93.5 'A'

© CeNCE CS1 Problem Solving Methodology Unit10 - 22

8. Exercise #1: Points (1/5)


 Write a program Unit_Points.c that includes
1. a structure type point_t whose members are the x- and y-
coordinates of a point. The coordinates are integers.
2. a function read_points() to read the number of points and points’
data into an array of points, and return the number of points
read. Each point is represented by its x- and y-coordinates.

 You may assume that the input data contain at least 1 point and at
most 10 points.
5
34
 An example of input data of 5 points is as shown here -1 4
5 -2
(points.in) -6 -2
03
© CeNCE CS1 Problem Solving Methodology Unit10 - 23

8. Exercise #1: Points (2/5)


Unit10_Points.c
#include <stdio.h>
#define MAX_POINTS 10
typedef struct {
int x, y; // x- and y-coordinates of a point
} point_t;
// Function prototypes omitted for brevity

int main(void) {
point_t points[MAX_POINTS];
int size; // number of points

size = read_points(points);

return 0;
}

© CeNCE CS1 Problem Solving Methodology Unit10 - 24

8. Exercise #1: Points (3/5)


// Read input data
// Return the number of points read
int read_points(point_t points[]) {
int size, i;

printf("Enter number of points: ");


scanf("%d", &size);

printf("Enter data for %d points:\n", size);


for (i=0; i<size; i++)
scanf("%d %d", &points[i].x, &points[i].y);

return size;

}
Unit10_Points.c
© CeNCE CS1 Problem Solving Methodology Unit10 - 25

8. Exercise #1: Points (4/5)


 After reading the points, imagine that you draw the smallest circle
with centre at the origin (0, 0) that encloses all the given points.
Complete the function float circle_area() to return the area (of type
float) of this smallest circle.
 You may assume that π is 3.14159.
 For the example input data, the area is 125.66.
 Hint: It may be useful to add a function for computing the square of
distance of a point from the origin.

5
34
-1 4
5 -2
-6 -2
03

© CeNCE CS1 Problem Solving Methodology Unit10 - 26

8. Exercise #1: Points (5/5)


Unit10_Points.c
// Compute the area of the smallest circle that
// encloses all the points.
float circle_area(point_t points[], int size) {
int i, max_dist, dist;

max_dist = dist_sq(points[0]);

for (i=1; i<size; i++) {


dist = dist_sq(points[i]);
if (dist > max_dist)
max_dist = dist;
}
return PI * max_dist;
}
// Square of distance of a point from the origin
int dist_sq(point_t pt) {
return (pt.x * pt.x) + (pt.y * pt.y);
}
© CeNCE CS1 Problem Solving Methodology Week8 - 27

9. Exercise #2: Perimeter (1/2)


 Write a program Unit10_Perimeter.c to do the
following:
1. Define a structure type rectangle_t with 2 integer members:
side1 and side2, which are the lengths of its 2 sides.
2. Declare a variable of type rectangle_t and read values into its
members.
3. Compute the minimum perimeter if we fold the rectangle into
halves once, either along the x-axis or the y-axis.
 Note
 Do not use any additional variables besides the two given
variables.
 You may write the code in the main() function. You may
modularise the program later.

© CeNCE CS1 Problem Solving Methodology Week8 - 28

9. Exercise #2: Perimeter (2/2)


#include <stdio.h> Unit10_Perimeter.c

typedef struct {
int side1, side2;
} rectangle_t;
int main(void) {
rectangle_t rect;
int perimeter;
printf("Enter lengths: ");
scanf("%d %d", &rect.side1, &rect.side2);
if (rect.side1 > rect.side2)
perimeter = rect.side1 + 2*rect.side2;
else
perimeter = rect.side2 + 2*rect.side1;
printf("Perimeter = %d\n", perimeter);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 29

10. Passing Address of Structure to Functions (1/5)


 Given this code, what is the output?
Unit10_Demo2.c
// #include statements, definition of player_t,
// and function prototypes are omitted here for brevity
int main(void) {
player_t player1 = { "Brusco", 23, 'M' };
change_name_and_age(player1);
print_player("player1", player1);
return 0;
player1: name = Brusco; age = 23; gender = M
}
// To change a player’s name and age
void change_name_and_age(player_t player) {
strcpy(player.name, "Alexandra");
player.age = 25;
}
// Print player’s information
void print_player(char header[], player_t player) {
printf("%s: name = %s; age = %d; gender = %c\n", header,
player.name, player.age, player.gender);
}

© CeNCE CS1 Problem Solving Methodology Unit10 - 30

10. Passing Address of Structure to Functions (2/5)

player1
main()
name age gender
"Brusco" 23 'M'
change_name_and_age(player1);

change_name_and_age(player_t player)

player
name age gender
"Alexandra"
"Brusco" 23
25 'M'

strcpy(player.name, "Alexandra");
player.age = 25;
© CeNCE CS1 Problem Solving Methodology Unit10 - 31

10. Passing Address of Structure to Functions (3/5)

 Like an ordinary variable (eg: of type int, char), when a


structure variable is passed to a function, a separate copy
of it is made in the called function.
 Hence, the original structure variable will not be modified
by the function.
 To allow the function to modify the content of the original
structure variable, you need to pass in the address
(pointer) of the structure variable to the function.
 (Note that passing an array of structures to a function is a
different matter. As the array name is a pointer, the
function is able to modify the array elements.)

© CeNCE CS1 Problem Solving Methodology Unit10 - 32

10. Passing Address of Structure to Functions (4/5)


 Need to pass address of the structure variable
Unit10_Demo3.c
// #include statements, definition of player_t,
// and function prototypes are omitted here for brevity
int main(void) {
player_t player1 = { "Brusco", 23, 'M' };
change_name_and_age(&player1);
print_player("player1", player1);
return 0;
player1: name = Alexandra; age = 25; gender = M
}
// To change a player’s name and age
void change_name_and_age(player_t *player_ptr) {
strcpy((*player_ptr).name, "Alexandra");
(*player_ptr).age = 25;
}
// Print player’s information
void print_player(char header[], player_t player) {
printf("%s: name = %s; age = %d; gender = %c\n", header,
player.name, player.age, player.gender);
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 33

10. Passing Address of Structure to Functions (5/5)

player1
main()
name age gender
"Brusco"
"Alexandra" 23
25 'M'
change_name_and_age(&player1);

change_name_and_age(player_t *player_ptr)

player_ptr

strcpy((*player_ptr).name, "Alexandra");
(*player_ptr).age = 25;

© CeNCE CS1 Problem Solving Methodology Unit10 - 34

11. Returning Structure from Functions (1/4)


 When combined with arrays and functions, structures
give us a lot of flexibility in organizing and passing
around data.

 One such example is that a function may return more


than one outputs using structure.
© CeNCE CS1 Problem Solving Methodology Unit10 - 35

11. Returning Structure from Functions (2/4)


 Example: typedef struct {
int max;
 Given this structure type float ave;
result_t, } result_t;

 Define a function func() that returns a


structure of this type: result_t func( ... ) {
...
}

 To call this function: result_t result;

result = func( ... );

© CeNCE CS1 Problem Solving Methodology Unit10 - 36

11. Returning Structure from Functions (3/4)


#include <stdio.h> Unit10_Demo2.c

typedef struct {
int max;
float ave;
} result_t;

result_t max_and_average(int, int, int);

int main(void) {
int num1, num2, num3; // inputs
result_t result;
returned structure is
printf("Enter 3 integers: "); copied to result
scanf("%d %d %d", &num1, &num2, &num3);
result = max_and_average(num1, num2, num3);

printf("Maximum = %d\n", result.max);


printf("Average = %.2f\n", result.ave);
return 0; max and average
} are printed
...
© CeNCE CS1 Problem Solving Methodology Unit10 - 37

11. Returning Structure from Functions (4/4)


Unit10_Demo2.c
// Computes the maximum and average of 3 integers
result_t max_and_average(int n1, int n2, int n3) {
result_t result;

result.max = n1;
if (n2 > result.max) the answers are stored in the
result.max = n2; structure variable result.
if (n3 > result.max)
result.max = n3;

result.ave = (n1+n2+n3)/3.0;

return result;
} result is returned here

© CeNCE CS1 Problem Solving Methodology Unit10 - 38

12. Array of Structures


 Combining structures and arrays gives us a lot of flexibility in
organizing data.
 For example, we may have a structure comprising 2 members: student’s
name and an array of 5 test scores he obtained.
 Or, we may have an array whose elements are structures.
 Or, even more complex combinations such as an array whose elements
are structures which comprises array as one of the members.
 Case study:
 A startup company decides to provide location-based services. Its
customers are a list of stores.
 Each store has a name, a location given by (x, y) coordinates, a radius
that defines a circle of influence.
 We can define a structure type store_t for the stores, and have a store_t
array store_t variables. We call this array storeList and it represents the
list of stores.
© CeNCE CS1 Problem Solving Methodology Unit10 - 39

12. Case Study: Nearby Stores (1/4)


 Given a user’s current location (x, y) and a list of stores, write a
program that prints the names of stores where the user’s current
location is within their circles of influence.
 The diagram on the left shows the circle of influence
of a store S. User u1 is within S’s circle of influence
while u2 is not.
 Sample run:
Enter number of stores: 5 The nearby stores are:
Enter store information: ABC_Store
ABC_Store 3 4 5.0 Old_Papa
Cheerful 1 1 3.0 Lowson
Old_Papa 5 6 10.0
Seven_11 2 2 2.0
Lowson 4 1 2.5
Enter user location: 5 2

© CeNCE CS1 Problem Solving Methodology Unit10 - 40

12. Case Study: Nearby Stores (2/4)


Unit10_NearbyStores.c
// Preprocessor directives and
// function prototypes omitted for brevity
typedef struct {
char sname[13];
int x, y;
float radius;
} store_t;
int main(void){
store_t storeList[MAX_STORES];
int numStore, userX, userY;

numStore = readStores(storeList);

printf("Enter user location: ");


scanf("%d %d", &userX, &userY);

printNearbyStores(userX, userY, storeList, numStore);

return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 41

12. Case Study: Nearby Stores (3/4)


Unit10_NearbyStores.c
int readStores(store_t storeList[]) {
int i, numStore;

printf("Enter number of stores: ");


scanf("%d", &numStore);

printf("Enter store information:\n");

for (i=0; i<numStore; i++)


scanf("%s %d %d %f", storeList[i].sname,
&storeList[i].x, &storeList[i].y,
&storeList[i].radius);

return numStore;
}

© CeNCE CS1 Problem Solving Methodology Unit10 - 42

12. Case Study: Nearby Stores (4/4)


Unit10_NearbyStores.c
int withinRadius(int x, int y, store_t store) {
float distance = sqrt((store.x - x)*(store.x - x) +
(store.y - y)*(store.y - y));

return (distance < store.radius);


}

void printNearbyStores(int x, int y,


store_t storeList[], int numStore) {
int i;

printf("The nearby stores are:\n");

for (i=0; i<numStore; i++)


if (withinRadius(x, y, storeList[i]))
printf("%s\n", storeList[i].sname);
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 43

13. Exercise 32: Health Screening (1/2)


 Write a program Unit10_Health_Screen.c to read in a list
of health screen readings
 Each input line represents a reading consisting of 2 numbers: a
float value indicating the health score, and an int value indicating
the number of people with that score.
 You may assume that there are at most 50 readings.
 The input should end with the reading 0 0, or when 50 readings
have been read. (see health.in)
 As the readings are gathered from various clinics, there
might be duplicate scores in the input. You are to
determine how many unique scores there are.
 A skeleton program Unit10_Health_Screen.c is given.
 This exercise is mounted on Coursemology.

© CeNCE CS1 Problem Solving Methodology Unit10 - 44

13. Exercise #3 Health Screening (2/2)


 A sample run is shown below
Enter score and frequency (end with 0 0):
5.2135 3
3.123 4
2.9 3
0.87 2
2.9 2
8.123 6
3.123 2
7.6 3
2.9 4
0.111 5
0 0
Number of unique readings = 7

 Possible extension: Which is the score that has the


highest combined frequency? (Do this on your own.)
© CeNCE CS1 Problem Solving Methodology Unit10 - 45

Summary
 In this unit, you have learned about
 How to create and use structures
 How to return 2 or more values from a function using
structures
 How to create and use structures with strings
 How to pass structures to functions
 How to use an array of structures

© CeNCE CS1 Problem Solving Methodology Unit10 - 46

End of File
CS1:
PROGRAMMING METHODOLOGY

UNIT 11
Recursion

©CeNCE CS1 Problem Solving Methodology Unit11 - 2

Unit 11: Recursion


Objectives:
 Understand the nature of recursion
 Learn to write recursive functions
 Comparing recursive codes with iterative codes
 Understand that many problems are more naturally
solved with recursion, which can provide elegant
solutions.
 Taste the classic example of recursion: Towers of
Hanoi.
©CeNCE CS1 Problem Solving Methodology Unit11 - 3

Unit 11: Recursion


1. Introduction
2. Two Simple Classic Examples
2.1 Demo #1: Factorial
2.2 Demo #2: Fibonacci
3. Gist of Recursion
4. Exercises
5. Thinking Recursively
5.1 Think: Sum of Squares
5.2 Demo #3: Counting Occurrences
6. Auxiliary Function
7. Exercises
8. Types of Recursion
9. Tracing Recursive Codes
10. Recursion versus Iteration
11. Towers of Hanoi

©CeNCE CS1 Problem Solving Methodology Unit11 - 4

1. Introduction (1/3)

Some examples of recursion (inside and outside CS):

Garfield dreaming
recursively.

Sierpinski triangle

Droste effect
Recursive tree
©CeNCE CS1 Problem Solving Methodology Unit11 - 5

1. Introduction (2/3)

Definitions based on recursion:


Dictionary entry:
Recursive definitions: Recursion: See recursion.
1. A person is a descendant of another if
 the former is the latter’s child, or
 the former is one of the descendants of the latter’s child.
2. A list of numbers is
 a number, or
 a number followed by a list of numbers.

Recursive acronyms:
1. GNU = GNU’s Not Unix
2. PHP = PHP: Hypertext Preprocessor

©CeNCE CS1 Problem Solving Methodology Unit11 - 6

1. Introduction (3/3)
 There is NO new syntax needed for recursion.
 Recursion is a form of (algorithm) design; it is a problem-
solving technique for divide-and-conquer paradigm
 Very important paradigm – many CS problems solved using it
 Recursion is:
©CeNCE CS1 Problem Solving Methodology Unit11 - 7

2. Two Simple Classic Examples


 From these two examples, you will see how a recursive
algorithm works

Winding phase
Invoking/calling ‘itself’ to solve
smaller or simpler instance(s) of
a problem …
… and then building up the
answer(s) of the simpler
instance(s).
Unwinding phase

©CeNCE CS1 Problem Solving Methodology Unit11 - 8

2.1 Demo #1: Factorial (1/3)

n! = n  (n – 1)  (n – 2)  …  2  1

Iterative code (version 1):


// Pre-cond: n >= 0
int factorial_iter1(int n) {
int ans = 1, i; Iterative code (version 2):
for (i=2; i<=n; i++) { // Pre-cond: n >= 0
ans *= i; int factorial_iter2(int n) {
} int ans = 1;
return ans; while (n > 1) {
} ans *= n;
n--;
}
return ans;
Unit11_Factorial.c
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 9

2.1 Demo #1: Factorial (2/3)


Recurrence relation:
n! = n  (n – 1)  (n – 2)  …  2  1 n! = n  (n – 1)!
Doing it the recursive way? 0! = 1

// Pre-cond: n >= 0
int factorial(int n) { No loop!
if (n == 0) But calling itself
return 1;
else (recursively) brings
return n * factorial(n-1); out repetition.
}

Note: All the three versions work only for n < 13, due to the range of values
permissible for type int. This is the limitation of the data type, not a limitation
of the problem-solving model.

©CeNCE CS1 Problem Solving Methodology Unit11 - 10

2.1 Demo #1: Factorial (3/3)


int f(int n) {
 Trace factorial(3). For simplicity, we if (n == 0)
return 1;
write f(3). else
return n * f(n-1);
Winding: Trace tree: }

f(3): Since 3 ≠ 0, call 3 * f(2)


f(3) 6
f(2): Since 2 ≠ 0, call 2 * f(1)
f(1): Since 1 ≠ 0, call 1 * f(0)
3 * f(2) 2
f(0): Since 0 == 0, …

Unwinding: 2 * f(1) 1
f(0): Return 1
1 * f(0) 1
f(1): Return 1 * f(0) = 1 * 1 = 1
f(2): Return 2 * f(1) = 2 * 1 = 2
f(3): Return 3 * f(2) = 3 * 2 = 6
©CeNCE CS1 Problem Solving Methodology Unit11 - 11

2.2 Demo #2: Fibonacci (1/4)


 The Fibonacci series models the rabbit
population each time they mate:
1, 1, 2, 3, 5, 8, 13, 21, …

 The modern version is:


0, 1, 1, 2, 3, 5, 8, 13, 21, …

 Fibonacci numbers are found


in nature (sea-shells,
sunflowers, etc)
 http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibnat.html

©CeNCE CS1 Problem Solving Methodology Unit11 - 12

2.2 Demo #2: Fibonacci (2/4)


 Fibonacci numbers are found in nature (sea-shells,
sunflowers, etc)
 http://www.maths.surrey.ac.uk/hosted-
sites/R.Knott/Fibonacci/fibnat.html
©CeNCE CS1 Problem Solving Methodology Unit11 - 13

2.2 Demo #2: Fibonacci (3/4)


0, 1, 1, 2, 3, 5, 8, 13, 21, … Unit11_Fibonacci.c

Iterative code: Recursive code:


// Pre-cond: n >= 0 // Pre-cond: n >= 0
int fib_iter(int n) { int fib(int n) {
int prev1 = 1, if (n < 2)
prev2 = 0, sum; return n;
else
if (n < 2) return fib(n-1) + fib(n-2);
return n; }
for (; n>1; n--) {
sum = prev1 + prev2; Recurrence relation:
prev2 = prev1; fn = fn-1 + fn-2 n ≥ 2
prev1 = sum; f0 = 0
} f1 = 1
return sum;
}

©CeNCE CS1 Problem Solving Methodology Unit11 - 14


int fib(int n) {
if (n < 2)

2.2 Fibonacci (4/4)


return n;
else
return fib(n-1) + fib(n-2);
}

 fib(n) makes 2 recursive calls: fib(n-1) and fib(n-2)


Winding
 Trace tree (or call tree) for fib(5)
5 Unwinding

fib(5)
3 2

fib(4) fib(3)
2 1 1 1
fib(3) fib(2) fib(2) fib(1)

1 1 1 0 1 0

fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)

1 0

fib(1) fib(0)
©CeNCE CS1 Problem Solving Methodology Unit11 - 15

3. Gist of Recursion (1/6)


Iteration vs Recursion: How to compute factorial(3)?

You, do f(2) for me.


Recursion man
I’ll return 3 * your
answer to my boss.
You, do f(1) for me.
Iteration man I’ll return 2 * your
answer to my boss.
I do f(3) all by f(3) You, do f(0) for me.
myself…return I’ll return 1 * your
6 to my boss. answer to my boss.
f(2)
I will do f(0) all by
myself, and return
1 to my boss.
f(3) f(1)

f(0)

©CeNCE CS1 Problem Solving Methodology Unit11 - 16

3. Gist of Recursion (2/6)


 Problems that lend themselves to a recursive solution
have the following characteristics:
 One or more simple cases (also called base cases or anchor
cases) of the problem have a straightforward, non-recursive
solution
 The other cases can be redefined in terms of problems that are
smaller, i.e. closer to the simple cases
 By applying this redefinition process every time the recursive
function is called, eventually the problem is reduced entirely to
simple cases, which are relatively easy to solve
 The solutions of the smaller problems are combined to obtain the
solution of the original problem
©CeNCE CS1 Problem Solving Methodology Unit11 - 17

3. Gist of Recursion (3/6)


 To write a recursive function:
 Identify the base case(s) of the relation
 Identify the recurrence relation
// Pre-cond: n >= 0 // Pre-cond: n >= 0
int factorial(int n) { int fib(int n) {
if (n == 0) if (n < 2)
return 1; return n;

else else
return n * factorial(n-1); return fib(n-1) + fib(n-2);
} }

©CeNCE CS1 Problem Solving Methodology Unit11 - 18

3. Gist of Recursion (4/6)


 Always check for base case(s) first
 What if you omit base case(s)?
 Do not write redundant base cases
int factorial(int n) {
if (n == 0)
return 1;
else if (n == 1)
return 1;
else if (n == 2) redundant
return 2;
else if (n == 3)
return 6;
else
return n * factorial(n-1);
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 19

3. Gist of Recursion (5/6)


 When a function is called, an activation record (or frame)
is created by the system.
 Each activation record stores the local parameters and
variables of the function and its return address.
 Such records reside in the memory called stack.
 Stack is also known as LIFO (last-in-first-out) structure
 A recursive function can potentially create many
activation records
 Winding: each recursive call creates a separate record
 Unwinding: each return to the caller erases its associated record

©CeNCE CS1 Problem Solving Methodology Unit11 - 20


int f(int n) {
if (n == 0) return 1;
3. Gist of Recursion (6/6) }
else return n * f(n-1);

 Example: factorial(3) n
0
n n 1 n
1 1 1
n n n n 1
2 2 2 2
n n n n n
3 3 3 3 3

f(3) f(2) f(1) f(0) n


2
2
n n
3 3
6
©CeNCE CS1 Problem Solving Methodology Week10 - 21

4. Exercise #1: Greatest Common Divisor


 The recurrence relation for Greatest Common Divisor
(GCD) of two non-negative integers a and b, not both
zero, is given below:

 Write a function int gcd(int a, int b) to compute the


GCD of a and b. Skeleton program Unit11_GCD.c is
given.

©CeNCE CS1 Problem Solving Methodology Week10 - 22

4. Exercise #2: Tracing


 Given the following 2 recursive functions, trace
mystery1(3902) and mystery2(3902) using the trace
tree method.

void mystery1(int n) { void mystery2(int n) {


if (n>0) { if (n>0) {
printf("%d", n%10); mystery2(n/10);
mystery1(n/10); printf("%d", n%10);
} }
} }

The order of statements does matter!


©CeNCE CS1 Problem Solving Methodology Unit11 - 23

5. Thinking Recursively
 It is apparent that to do recursion
you need to think “recursively”:
 Breaking a problem into simpler
problems that have identical form
 Is there only one way of breaking
a problem into simpler problems?

©CeNCE CS1 Problem Solving Methodology Unit11 - 24

5.1 Think: Sum of Squares (1/5)


 Given 2 positive integers x and y, where x  y,
compute
sumSq(x,y) = x2 + (x+1) 2 + … + (y-1) 2 + y2
• For example
sumSq(5,10) = 52 + 62 + 72 + 82 + 92 + 102 = 355
 How do you break this problem into smaller
problems?
 How many ways can it be done?
 We are going to show 3 versions
 See Unit11_SumSquares.c
©CeNCE CS1 Problem Solving Methodology Unit11 - 25

5.1 Think: Sum of Squares (2/5)


 Version 1: ‘going up’
int sumSq1(int x, int y) {
if (x == y) return x * x;
else return x * x + sumSq1(x+1, y);
}

 Version 2: ‘going down’


int sumSq2(int x, int y) {
if (x == y) return y * y;
else return y * y + sumSq2(x, y-1);
}

©CeNCE CS1 Problem Solving Methodology Unit11 - 26

5.1 Think: Sum of Squares (3/5)


 Version 3: ‘combining two half-solutions’
int sumSq3(int x, int y) {
int mid; // middle value

if (x == y)
return x * x;
else {
mid = (x + y)/2;
return sumSq3(x, mid) + sumSq3(mid+1, y);
}
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 27

5.1 Think: Sum of Squares (4/5)


 Trace trees
355 355
sumSq1(5,10) sumSq2(5,10)
25 + 330 100 + 255
sumSq1(6,10) sumSq2(5,9)
36 + 294 81 + 174
sumSq1(7,10) sumSq2(5,8)
49 + 245 64 + 110
sumSq1(8,10) sumSq2(5,7)
64 + 181 49 + 61
sumSq1(9,10) sumSq2(5,6)
81 + 100 36 + 25
sumSq1(10,10) sumSq2(5,5)

100 25

©CeNCE CS1 Problem Solving Methodology Unit11 - 28

5.1 Think: Sum of Squares (5/5)


 Trace tree
355
sumSq3(5,10)

110 245
sumSq3(5,7) sumSq3(8,10)

61 49 145 100
sumSq3(5,6) sumSq3(7,7) sumSq3(8,9) sumSq3(10,10)

25 36 49 64 81 100
sumSq3(5,5) sumSq3(6,6) sumSq3(8,8) sumSq3(9,9)

25 36 64 81
©CeNCE CS1 Problem Solving Methodology Unit11 - 29

5.2 Demo #3: Counting Occurrences (1/4)

 Given an array
int list[ ] = { 9, -2, 1, 7, 3, 9, -5, 7, 2, 1, 7, -2, 0, 8, -3 }
 We want
countValue(7, list, 15)
to return 3 (the number of times 7 appears in the 15
elements of list.

©CeNCE CS1 Problem Solving Methodology Unit11 - 30

5.2 Demo #3: Counting Occurrences (2/4)


Unit11_CountValue.c
Iterative code:
int countValue_iter(int value, int arr[], int size)
{
int count = 0, i;

for (i=0; i<size; i++)


if (value == arr[i])
count++;

return count;
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 31

5.2 Demo #3: Counting Occurrences (3/4)


 To get countValue(7, list, 15) to return 3.
 Recursive thinking goes…
9 -2 1 7 3 9 -5 7 2 1 7 -2 0 8 -3

… and get someone to If I handle the last


count the 7 in this smaller element myself, …
problem, …

… then, depending on whether the last element


is 7 or not, my answer is either his answer or
his answer plus 1!

©CeNCE CS1 Problem Solving Methodology Unit11 - 32

5.2 Demo #3: Counting Occurrences (4/4)


Recursive code: Unit11_CountValue.c

int countValue(int value, int arr[], int size) {


if (size == 0)
return 0;
else
return (value == arr[size-1]) +
countValue(value, arr, size-1);
}

Note: The second return statement is equivalent to the following (why?):


if (value == arr[size-1])
return 1 + countValue(value, arr, size-1);
else
return countValue(value, arr, size-1);
©CeNCE CS1 Problem Solving Methodology Unit11 - 33

6. Auxiliary Function (1/3)


 Sometimes, auxiliary functions are needed to implement
recursion. Eg: Refer to Demo #3 Counting Occurrences.
 If the function handles the first element instead of the
last, it could be re-written as follows:

int countValue(int value, int arr[],


int start, int size) {
if (start == size)
return 0;
else
return (value == arr[start]) +
countValue(value, arr, start+1, size);
}

©CeNCE CS1 Problem Solving Methodology Unit11 - 34

6. Auxiliary Function (2/3)


 However, doing so means that the calling function has to
change the call from:
countValue(value, list, ARRAY_SIZE)

to:
countValue(value, list, 0, ARRAY_SIZE)

 The additional parameter 0 seems like a redundant data


from the caller’s point of view.
©CeNCE CS1 Problem Solving Methodology Unit11 - 35

6. Auxiliary Function (3/3)


 Solution: Keep the calling part as:
countValue(value, list, ARRAY_SIZE)

 Rename the original countValue() function to countValue_recur().


The recursive call inside should also be similarly renamed.
 Add a new function countValue() to act as a driver function, as
follows:
int countValue(int value, int arr[], int size) {
return countValue_recur(value, arr, 0, size);
}

 See program Unit11_CountValue_Auxiliary.c

©CeNCE CS1 Problem Solving Methodology Week10 - 36

7. Exercise #3: Sum Digits


 Write a recursive function int sum_digits(int n) that
sums up the digits in n, assuming that n is a non-
negative integer.
 Skeleton program Unit11_SumDigits.c is given.
 This exercise is mounted on Coursemology.
 Sample runs:
Enter a non-negative integer: 6543
Sum of its digits = 18

Enter a non-negative integer: 3708329


Sum of its digits = 32
©CeNCE CS1 Problem Solving Methodology Week10 - 37

7. Exercise #4: Sum Array


 Write a program Unit11_SumArray.c to read data into an
integer array with at most 10 elements, and sum up all
values in the array, using a recursive function.
 This exercise is mounted on
 Sample runs:
Enter number of elements: 6
Enter 6 values: 4 3 -2 0 1 3
Array read: 4 3 -2 0 1 3
Sum = 9
Enter number of elements: 8
Enter 8 values: 11 25 56 8 12 7 31 16
Array read: 11 25 56 8 12 7 31 16
Sum = 166

©CeNCE CS1 Problem Solving Methodology Unit11 - 38

8. Types of Recursion
 Besides direct recursion (function A calls itself),
there could be mutual or indirect recursion (we
do not cover these in CS1)
 Examples: Function A calls function B, which calls
function A; or function X calls function Y, which calls
function Z, which calls function X.
 Note that it is not typical to write a recursive
main() function.
 One type of recursion is known as tail recursion.
©CeNCE CS1 Problem Solving Methodology Unit11 - 39

9. Tracing Recursive Codes


 Beginners usually rely on tracing to understand the
sequence of recursive calls and the passing back of results.
 However, tracing a recursive code is tedious, especially for
non-tail-recursive codes. The trace tree could be huge
(example: fibonacci).
 If you find that tracing is needed to aid your understanding,
start tracing with small problem sizes, then gradually see
the relationship between the successive calls.
 Students should grow out of tracing habit and understand
recursion by examining the relationship between the
problem and its immediate subproblem(s).

©CeNCE CS1 Problem Solving Methodology Unit11 - 40

10. Recursion versus Iteration (1/2)


 Iteration can be more efficient
 Replaces function calls with looping
 Less memory is used (no activation record for each call)
 Some good compilers are able to transform a tail-recursion
code into an iterative code.
 General guideline: If a problem can be done easily with
iteration, then do it with iteration.
 For example, Fibonacci can be coded with iteration or recursion, but
the recursive version is very inefficient (large call tree due to
duplicate computations), so use iteration instead.
©CeNCE CS1 Problem Solving Methodology Unit11 - 41

10. Recursion versus Iteration (2/2)


 Many problems are more naturally solved with recursion,
which can provide elegant solution.
 Towers of Hanoi
 Mergesort (to be covered in next unit)
 The N Queens problem
 Conclusion: choice depends on problem and the solution
context. In general, use recursion if …
 A recursive solution is natural and easy to understand.
 A recursive solution does not result in excessive duplicate
computation.
 The equivalent iterative solution is too complex.

©CeNCE CS1 Problem Solving Methodology Unit11 - 42

Tower Of Hanoi (1/17)


 This classical “Towers of Hanoi” puzzle has attracted the
attention of computer scientists more than any other
puzzles.
 There are 3 pegs (A, B and C) and a tower of n disks on
the first peg A, with the smallest disk on the top and the
biggest at the bottom. The purpose of the puzzle is to
move the whole tower from peg A to peg C, with the
following simple rules:
 Only one disk (the one at the top) can be moved at a time.
 A bigger disk must not rest on a smaller disk.
©CeNCE CS1 Problem Solving Methodology Unit11 - 43

Tower Of Hanoi (2/17)


 Demo: Tower of Hanoi
 We attempt to write a program to produce instructions on
how to move the disks from peg A to peg C to complete
the puzzle.
 Example: A tower with 3 disks.
 Output produced by program:
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

©CeNCE CS1 Problem Solving Methodology Unit11 - 44

Tower Of Hanoi (3/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 45

Tower Of Hanoi (4/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C

©CeNCE CS1 Problem Solving Methodology Unit11 - 46

Tower Of Hanoi (5/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 47

Tower Of Hanoi (6/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C

©CeNCE CS1 Problem Solving Methodology Unit11 - 48

Tower Of Hanoi (7/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 49

Tower Of Hanoi (8/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C

©CeNCE CS1 Problem Solving Methodology Unit11 - 50

Tower Of Hanoi (9/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 51

Tower Of Hanoi (10/17)


 Example: A tower with 3 disks.
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Voilà!
Move disk from A to C

A B C

©CeNCE CS1 Problem Solving Methodology Unit11 - 52

Tower Of Hanoi (11/17)

Can be interpreted as:


1. move four disks from peg A to peg B
2. move disk 5 from peg A to peg C
3. move four disks from peg B to peg C
©CeNCE CS1 Problem Solving Methodology Unit11 - 53

Tower Of Hanoi (12/17)


Towers after steps 1 and 2:

But how do we execute step 1? Or step 3?


Step 3 can be interpreted as:
3.1 move three disks from peg B to peg A
3.2 move disk 4 from peg B to peg C
3.3 move three disks from peg A to peg C

©CeNCE CS1 Problem Solving Methodology Unit11 - 54

Tower Of Hanoi (13/17)


Towers after steps 1, 2, 3.1 and 3.2:

Can you start to visualise how to solve


this using recursion?
©CeNCE CS1 Problem Solving Methodology Unit11 - 55

Tower Of Hanoi (14/17)


 Algorithm:

if (n > 0)
move n – 1 disks from the source peg to the
temp peg using the dest peg
move disk n from the source peg to the dest peg
move n – 1 disks from the temp peg to the dest
peg using the source peg

©CeNCE CS1 Problem Solving Methodology Unit11 - 56

Tower Of Hanoi (15/17)


#include <stdio.h> Unit11_TowersOfHanoi.c
void tower(char, char, char, int);
int main(void) {
int disks;
printf("Number of disks: ");
scanf("%d", &disks);
tower('A','B','C', disks);
return 0;
}
// Display instructions for moving n disk from source to dest
// using temp as an auxiliary. Disks are numbered 1 to n
// (smallest to largest).
void tower(char source, char temp, char dest, int n) {
if (n > 0) {
tower(source, dest, temp, n-1);
printf("Move disk %d from peg %c to peg %c\n",
n, source, dest);
tower(temp, source, dest, n-1);
}
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 57

Tower Of Hanoi (16/17) source is 'A'


temp is 'B'
dest is 'C'
 Tracing tower('A', 'B', 'C', 3); n is 1
tower ('A', 'C', 'B', 0)
tower('A', 'B', 'C', 3); move 1 from A to C
source is 'A' tower ('B', 'A', 'C', 0)
temp is 'C' source is 'C'
dest is 'B' temp is 'A'
n is 2 dest is 'B'
source is 'A' n is 1
temp is 'B' tower ('A', 'B', 'C', 1)
tower ('C', 'B', 'A', 0)
dest is 'C' move 2 from A to B
move 1 from C to B
n is 3 tower ('C', 'A', 'B', 1) tower ('A', 'C', 'B', 0)
tower ('A', 'C', 'B', 2)
move 3 from A to C source is 'B'
temp is 'C'
tower ('B', 'A', 'C', 2)
source is 'B' dest is 'A'
temp is 'A' n is 1
dest is 'C' tower ('B', 'A', 'C', 0)
n is 2 move 1 from B to A
tower ('C', 'B', 'A', 0)
tower ('B', 'C', 'A', 1)
move 2 from B to C source is 'A'
tower ('A', 'B', 'C', 1) temp is 'B'
dest is 'C'
n is 1
tower ('A', 'C', 'B', 0)
move 1 from A to C
tower ('B', 'A', 'C', 0)

©CeNCE CS1 Problem Solving Methodology Unit11 - 58

Tower Of Hanoi (17/17)


 Output generated by tower('A', 'B', 'C', 3);

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
©CeNCE CS1 Problem Solving Methodology Unit11 - 59

Summary
 In this unit, you have learned about
 Recursion as a design strategy
 The components of a recursive code
 Differences between Recursion and Iteration

©CeNCE CS1 Problem Solving Methodology Unit11 - 60

End of File
CS1:
PROGRAMMING METHODOLOGY

Unit 12
Searching and Sorting

CeNCE Searching and Sorting Unit12 - 2

Unit 20: Searching and Sorting


Objectives:
 Understand the basic searching algorithms and
sorting algorithms
 Implement the searching and sorting algorithms
using arrays
CeNCE Searching and Sorting Unit12 - 3

Unit 12: Searching and Sorting (1/2)


1. Overall Introduction
2. Introduction to Searching
3. Linear Search
 Demo #1
 Performance
4. Binary Search

CeNCE Searching and Sorting Unit12 - 4

Unit 12: Searching and Sorting (2/2)


5. Introduction to Sorting
6. Selection Sort
 Demo #2
 Performance
7. Bubble Sort
 Demo #3
 Performance
8. More Sorting Algorithms
9. Animated Sorting Algorithms
CeNCE Searching and Sorting Unit12 - 5

1. Overall Introduction
 You have accumulated quite a bit of basic programming
experience by now.
 Today, we will study some simple yet useful classical
algorithms which find their place in many CS applications
 Searching for some data amid very large collection of data
 Sorting very large collection of data according to some order
 We will begin with an algorithm (idea), and show how the
algorithm is transformed into a C program
(implementation).
 This brings back (reminds you) our very first lecture: the
importance of beginning with an algorithm.

CeNCE Searching and Sorting Unit12 - 6

2. Introduction to Searching (1/2)


 Searching is a common task that we carry out without
much thought everyday.
 Searching for a location in a map
 Searching for the contact of a particular person
 Searching for a nice picture for your project report
 Searching for a research paper required in your course
 In this lecture, you will learn how to search for an item
(sometimes called a search key) in an array.
CeNCE Searching and Sorting Unit12 - 7

2. Introduction to Searching (2/2)


 Problem statement:
Given a list (collection of data) and a search key X, return the
position of X in the list if it exists.
For simplicity, we shall assume there are no duplicate values
in the list.
 We will count the number of comparisons the algorithms
make to analyze their performance.
 The ideal searching algorithm will make the least possible
number of comparisons to locate the desired data.
 We will introduce worst-case scenario.
 (This topic is called analysis of algorithms, which will be formally
introduced in CS2. Here, we will give an informal introduction
just for an appreciation.)

CeNCE Searching and Sorting Unit12 - 8

3. Linear Search (1/3)


 Also known as Sequential Search
 Idea: Search the list from one end to the other end in
linear progression.
 Algorithm: Example: Search for 24 in this list

// Search for key in list A with n items 87 12 51 9 24 63


linear_search(A, n, key)
{
for i = 0 to n-1
if Ai is key then report i
no no no no yes!
}
Return 4
 Question: What to report if key is not found?
 Aim for a clean design
CeNCE Searching and Sorting Unit12 - 9

3. Linear Search: Demo #1 (2/3)


 If the list is an array, how would you implement the
Linear Search algorithm?
// To search for key in arr using linear search
// Return index if found; otherwise return -1
int linearSearch(int arr[], int size, int key) {
int i;
See linear_search.c for full program
for (i=0; i<size; i++)
if (key == arr[i])
return i;
return -1;
} Useful and common technique

 Question: What if array contains duplicate values of the


key? Index of the first element found will be returned.

CeNCE Searching and Sorting Unit12 - 10

3. Linear Search: Performance (3/3)


 We use the number of comparisons here as a
rough basis for measurement.
 Analysis is done for best case, average case,
and worst case. We will focus on the worst case.
 For an array with n elements, in the worst case,
 What is the number of comparisons in linear search
algorithm? n comparisons
This is called linear time algorithm: O(n)
 Under what circumstances does the worst case
happen? (a) Not found
(b) Found at the last element

CeNCE Searching and Sorting Unit12 - 11

4. Binary Search (1/6)


 You are going to witness a radically different approach,
one that has become the basis of many well-known
algorithms in Computer Science!
 The idea is simple and fantastic, but when applied on the
searching problem, it has this pre-condition that the list
must be sorted before-hand.
 How the data is organized (in this case, sorted) usually
affects how we choose/design an algorithm to access
them.
 In other words, sometimes (actually, very often) we seek
out new way to organize the data so that we can process
them more efficiency.  More of this in CS2 Data
Structures and Algorithms.

CeNCE Searching and Sorting Unit12 - 12

4. Binary Search (2/6)


 The Binary Search algorithm
 Look for the key in the middle position of the list.
Either of the following 2 cases happens:
 If the key is smaller than the middle element,
“discard” the right half of the list and repeat the
process.
 If the key is greater than the middle element,
“discard” the left half of the list and repeat the
process.
 Terminating condition: when the key is found, or
when all elements have been “discarded”.
CeNCE Searching and Sorting Unit12 - 13

Binary Search
• Given a sorted array: A with n elements
• Goal: Search for x
• x may or may not be in the array A

A[0] A[n-1]

CeNCE Searching and Sorting Unit12 - 14

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[0] A[M] A[n-1]


CeNCE Searching and Sorting Unit12 - 15

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[0] A[M] A[n-1]

• If A[M] == x
• Yeah.. we are done. x is found!

CeNCE Searching and Sorting Unit12 - 16

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[0] A[M] A[n-1]

• If A[M] > x
• Then all of the right side with indice M+1 to n-1 will be all larger
than x
• No need to search
CeNCE Searching and Sorting Unit12 - 17

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[0] A[M-1]

• If A[M] > x
• Repeat the process with this smaller array with indices from 0 to M-
1

CeNCE Searching and Sorting Unit12 - 18

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[0] A[M] A[n-1]

• If A[M] < x
• Then all of the left side with indices 0 to M-1 will be all smaller than
x
• No need to search
CeNCE Searching and Sorting Unit12 - 19

Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2

A[M+1] A[n-1]

• If A[M] < x
• Repeat the process with this smaller array with indices from M+1 to
n-1

CeNCE Searching and Sorting Unit12 - 20

Pseudocode for Array Size = N


• Let it be L = 0, R = N-1
• L and R are the two indices of the left and right bound
• Repeat
• The middle index M = (L + R) / 2
• If A[M] == x
• Return the index M
A[0] A[M-1]
• If A[M] > x
• R = M -1
• Else A[M+1] A[n-1]
• L = M +1

• Repeat until the gap is closed


• x is not found in the array
CeNCE Searching and Sorting Unit12 - 21

4. Binary Search (3/6)


 Example: Search key = 23
arr [0] [1] [2] [3] [4] [5] [6] [7] [8]

5 12 17 23 38 44 77 84 90

Found!
Return 3
1. low = 0, high = 8, mid = (0+8)/2 = 4 arr[4] = 38 > 23
2. low = 0, high = 3, mid = (0+3)/2 = 1 arr[1] = 12 < 23
3. low = 2, high = 3, mid = (2+3)/2 = 2 arr[2] = 17 < 23
4. low = 3, high = 3, mid = (3+3)/2 = 3 arr[3] = 23 == 23

CeNCE Searching and Sorting Unit12 - 22

4. Binary Search (4/6)


 In binary search, each step eliminates the problem size
(array size) by half!
 The problem size gets reduced to 1 very quickly! (see slide after
next.)
 This is a simple yet powerful strategy, of halving the
solution space in each step
 This is a BIG DEAL in problem solving
 Such strategy, a special case of divide-and-conquer paradigm,
can be naturally implemented using recursion.
CeNCE Searching and Sorting Unit12 - 23

4. Binary Search (5/6)


binary_search.c
// To search for key in sorted arr using binary search
// Return index if found; otherwise return -1
int binarySearch(int arr[], int size, int key) {

int low = 0, high = size – 1, mid = (low + high)/2;

while ((low <= high) && (arr[mid] != key)) {


if (key < arr[mid])
high = mid - 1;
else
low = mid + 1;
mid = (low + high)/2;
}
if (low > high) return -1;
else return mid;
}

CeNCE Searching and Sorting Unit12 - 24

4. Binary Search (6/6)


 Worst-case analysis

Array size Linear Search Binary search


n (n comparisons) (log2 n comparisons)
100 100 7
1,000 1,000 10
10,000 10,000 14
100,000 100,000 17
?
1,000,000 1,000,000 20
?
109 109 30
?

This is called log2n algorithm, or O(log2n)


CeNCE Searching and Sorting Unit12 - 25

Why log N?
• If you have N items, and each time you reduce the search
space by half
• How many steps do you need to half until the search
space is only 1?
• Let S be the number of steps
 𝑁×( ) =1
 𝑁=2
 log 𝑁 = 𝑆 log 2
 𝑆 = log 𝑁/ log 2

CeNCE Searching and Sorting Unit12 - 26

Order of Growth
Linear
Worst case: N
Binary Search
Log2 N
y=x

y = log2 x
CeNCE Searching and Sorting Unit12 - 27

Ok, now I know how to search a number


quickly

CeNCE Searching and Sorting Unit12 - 28

Computation
• Usually we rely on the computer to do tasks that are
• repetitive
• e.g. computing a function with series like cosine

• involving a large volume of data


• Searching for a NRIC in the many millions of Singaporeans
CeNCE Searching and Sorting Unit12 - 29

Search?
• Simple problem
• Let’s say we have a file containing all the names of
Singaporeans
• 3.4millions in 2015
• You want to check
• Is “Alan Cheng Ho Lun” a Singaporean?

CeNCE Searching and Sorting Unit12 - 30

Google?
CeNCE Searching and Sorting Unit12 - 31

How much data does Google handle?


• About 10 to 15 Exabyte of data
• 1 Exabyte(EB)= 1024 Petabyte(PB)
• 1 Petabyte(PB) = 1024 Terabytes(TB)
• 1 Terabyte(PB) = 1024 Gigabytes(TB)
• = 4 X 256GB iPhone

• So Google is handling about 60 millions of iPhones

CeNCE Searching and Sorting Unit12 - 32

Let’s calculate
• Let’s say 400Mb of data needs 6 seconds
• I did an “anyhow” program to generate a lot of numbers worth
400Mb of data
• 15 Exabyte of data needs how long?
• 15 EB = 15 x 1024 x 1024 x 1024 x 1024 MB
• To search through 15EB of data…..
• 7845 years…..

• If we do it with Binary Search


• log2 (15EB) = 43 steps!!!!!
CeNCE Searching and Sorting Unit12 - 33

Speed Improvement
• If the number of data N is even larger, the improvement in
speed is even greater

y=x

y = log2 x

CeNCE Searching and Sorting Unit12 - 34

The Magic?
• Binary search vs Linear search
• However, one step back
• The data has to be sorted
• The time needed for sorting is 𝑛 log 𝑛
• Slower than linear search
• But we only have to do it once
• Is it?
• Can we assume that we can sort it once for all?
CeNCE Searching and Sorting Unit12 - 35

Data Structure and Algorithm


• But what if the data is dynamic?
• Even after sorted, there will be new items added or old
items removed from the list?
• How do we maintain a dynamic list that is sorted all the
time?
• This is the study of Data Structure
• Basically, how fast we can compute if the data size N is very large

CeNCE Searching and Sorting Unit12 - 36

Data Structure
• How do you organize your data to improve your
performance
• Sorted list, trees, graphs, heaps, hash tables, etc.

• British Library
• 170m+
• Library of Congress
• 164m+
CeNCE Searching and Sorting Unit12 - 37

5. Introduction to Sorting (1/2)


 Sorting is any process of arranging items in some
sequence and/or in different sets – Wikipedia.
 Sorting is important because once a set of items is sorted,
many problems (such as searching) become easy.
 Searching can be speeded up. (From linear search to binary
search)
 Determining whether the items in a set are all unique.
 Finding the median item in a list.
 Many others…

CeNCE Searching and Sorting Unit12 - 38

5. Introduction to Sorting (2/2)


 Problem statement:
Given a list of n items, arrange the items
into ascending order.
 We will implement the list as an integer array.
 We will introduce two basic sort algorithms.
 We will count the number of comparisons the algorithms
make to analyze their performance.
 The ideal sorting algorithm will make the least possible number of
comparisons to arrange data in a designated order.
 We will compare the algorithms by analyzing their worst-
case performance.
CeNCE Searching and Sorting Unit12 - 39

6. Selection Sort (1/6)


 Selection Sort algorithm
Step 1: Find the smallest element in the list (find_min)
Step 2: Swap this smallest element with the element in
the first position. (Now, the smallest element is
in the right place.)
Step 3: Repeat steps 1 and 2 with the list having one
fewer element (i.e. the smallest element just
found and its place is “discarded” from further
processing).

CeNCE Searching and Sorting Unit12 - 40

6. Selection Sort (2/6)


n=9 first min

array [0] [1] [2] [3] [4] [5] [6] [7] [8]
1st pass: 23 17 5 90 12 44 38 84 77

first min

2nd pass: 5 17 23 90 12 44 38 84 77
first min

3rd pass: 5 12 23 90 17 44 38 84 77
first min

4th pass: 5 12 17 90 23 44 38 84 77
CeNCE Searching and Sorting Unit12 - 41

6. Selection Sort (3/6) Q: How many passes for


an array with n elements?
n=9 first min n – 1 passes

5th pass: 5 12 17 23 90 44 38 84 77
first min

6th pass: 5 12 17 23 38 44 90 84 77
first min

7th pass: 5 12 17 23 38 44 90 84 77
first min

8th pass: 5 12 17 23 38 44 77 84 90

Final array: 5 12 17 23 38 44 77 84 90

CeNCE Searching and Sorting Unit12 - 42

6. Selection Sort: Demo #2 (4/6)


// To sort arr in increasing order See selection_sort.c for full program
void selectionSort(int arr[], int size) {
int i, start, min_index, temp;

for (start = 0; start < size-1; start++) {


// each iteration of the for loop is one pass

// find the index of minimum element


min_index = start;
for (i = start+1; i < size; i++)
if (arr[i] < arr[min_index])
min_index = i;

// swap minimum element with element at start index


temp = arr[start];
arr[start] = arr[min_index];
arr[min_index] = temp;
}
}
CeNCE Searching and Sorting Unit12 - 43

6. Selection Sort: Performance (5/6)


 We choose the number of comparisons as our basis of analysis.
 Comparisons of array elements occur in the inner loop, where the
minimum element is determined.
 Assuming an array with n elements. Table below shows the number
of comparisons for each pass.
 The total number of comparisons is calculated in the formula below.
 Such an algorithm is called an O(n2) algorithm, or quadratic
algorithm, in terms of running time complexity.
Pass #comparisons
1 n–1
2 n–2
3 n–3
… …
n–1 1

CeNCE Searching and Sorting Unit12 - 44

6. Selection Sort (6/6)


 Selection sort is classified under exchange sort, where
elements are exchanged in the process.
 We could search for the minimum element as described
earlier, or search for the maximum element and exchange
it with the last element of the working array (assuming we
sort in ascending order).
CeNCE Searching and Sorting Unit12 - 45

7. Bubble Sort (1/5)


 Selection sort makes one exchange at the end of each
pass.
 What if we make more than one exchange during each
pass?
 The key idea Bubble sort is to make pairwise
comparisons and exchange the positions of the pair if
they are in the wrong order.

CeNCE Searching and Sorting Unit12 - 46

Idea: Like Bubbles


CeNCE Searching and Sorting Unit12 - 47

7. Bubble Sort: One Pass of Bubble Sort (2/5)


0 1 2 3 4 5 6 7 8
23 17 5 90 12 44 38 84 77 17 5 23 12 44 90 38 84 77

exchange exchange

17 23 5 90 12 44 38 84 77 17 5 23 12 44 38 90 84 77

exchange exchange

17 5 23 90 12 44 38 84 77
17 5 23 12 44 38 84 90 77
exchange
ok exchange

17 5 23 12 90 44 38 84 77 17 5 23 12 44 38 84 77 90

exchange
Q: Is the array sorted? Done!
Q: What have we achieved?

CeNCE Searching and Sorting Unit12 - 48

7. Bubble Sort: Demo #3 (3/5)


// To sort arr in increasing order See bubble_sort.c for full program
void bubbleSort(int arr[], int size) {
int i, limit, temp;

for (limit = size-2; limit >= 0; limit--) {


// limit is where the inner loop variable i should end

for (i=0; i<=limit; i++) {


if (arr[i] > arr[i+1]) { // swap arr[i] with arr[i+1]
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
}
CeNCE Searching and Sorting Unit12 - 49

7. Bubble Sort: Performance (4/5)


 Bubble sort, like selection sort, requires n – 1 passes for an array
with n elements.
 The comparisons occur in the inner loop. The number of comparisons
in each pass is given in the table below.
 The total number of comparisons is calculated in the formula below.
 Like Selection sort, Bubble sort is also an O(n2) algorithm, or
quadratic algorithm, in terms of running time complexity.

Pass #comparisons
1 n–1
2 n–2
3 n–3
… …
n–1 1

CeNCE Searching and Sorting Unit12 - 50

7. Bubble Sort: Enhanced version (5/5)


 It is possible to enhance Bubble sort algorithm to reduce
the number of passes.
 Suppose that in a certain pass, no swap is needed. This
implies that the array is already sorted, and hence the
algorithm may terminate without going on to the next
pass.
 You will implement this enhanced version in your
discussion session.
CeNCE Searching and Sorting Unit12 - 51

8. More Sorting Algorithms


 We have introduced 2 basic sort algorithms: Selection
Sort and Bubble Sort. Together with Insertion Sort
algorithm, these 3 are the simplest sorting algorithms.
 However, they are very slow, as their running time
complexity is quadratic, or O(n2), where n is the array
size.
 Faster sorting algorithms exist and are covered in more
advanced modules.
 In CS2, you will learn more advanced sorting algorithms
with better running-time efficiency: Quick Sort, Merge
Sort, Radix Sort, etc.

CeNCE Searching and Sorting Unit12 - 52

9. Animated Sorting Algorithms


 There are a number of animated sorting algorithms on the
Internet.
 Here are just a few sites:
 Visualgo (http://visualgo.net): Project under A/Prof Steven Halim
 http://www.sorting-algorithms.com/
 http://www.cs.ubc.ca/~harrison/Java/sorting-demo.html
 There are also folk dances based on sorting!
 Selection sort with Gypsy folk dance
http://www.youtube.com/watch?v=Ns4TPTC8whw
 Bubble sort with Hungarian folk dance
http://www.youtube.com/watch?v=lyZQPjUT5B4
CeNCE Searching and Sorting Unit12 - 53

Summary
 In this unit, you have learned about
 2 search algorithms: Linear (sequential) Search and
Binary Search
 2 basic sort algorithms: Selection Sort and Bubble
Sort.
7/28/24, 5:03 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:03 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:02 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:04 PM Coursemology

1 2 3 4 5 6 7 8 9

one = 2
two = 3
three = 1
ans = one * (three-two)

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:04 PM Coursemology

1 2 3 4 5 6 7 8 9

x = 15

y = x

x = 22

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:04 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:05 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:05 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>

int main() {
int a = 5, b = 3, c = 7, d = 2;
int result;

result = a * b + c / d - a;

cout << "Result: " << result;

return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:05 PM Coursemology

1 2 3 4 5 6 7 8 9

1 #include <iostream>
2
3 using namespace std;
4
5 void solution() {
6 int a = 1, b = 2;
7
8 // Fix this part to swap the variables a and b correctly
9 int temp = a;
10 a = b;
11 b = temp;
12
13 cout << "a = " << a << ", b = " << b;
14 }

Swap Test Case a = 2, b = 1

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71487/submissions/2180573/edit 1/1
7/28/24, 5:49 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;
int main () {

char grade = 'D';


switch(grade)
{
case 'A' :
cout << "Excellent!";
break;
case 'B' :
case 'C' :
cout << "Well done";
break;
case 'D' :
cout << "You passed";
break;
case 'F' :
cout << "Better try again";
break;
default :
cout << "Invalid grade";
}
cout << "Your grade is " << grade;
return 0;

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:49 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;
int main () {

char grade = 'C';


switch(grade)
{
case 'A' :
cout << "Excellent!";
break;
case 'B' :
case 'C' :
cout << "Well done";
case 'D' :
cout << "You passed";
break;
case 'F' :
cout << "Better try again";
break;
default :
cout << "Invalid grade";
}
cout << "Your grade is " << grade;
return 0;

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:50 PM Coursemology

1 2 3 4 5 6 7 8 9

1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 string triangle(int a, int b, int c) {
6 // Check if it's not a triangle
7 if (a + b <= c || a + c <= b || b + c <= a) {
8 return "Not a triangle";
9 }
10 // Check if all sides are equal
11 if (a == b && b == c) {
12 return "Equilateral";
13 }
14 // Check if two sides are equal
15 if (a == b || b == c || a == c) {
16 return "Isosceles";
17 }
18 // If it's a valid triangle and all sides are unequal
19 return "Scalene";
20 }
21
22

Not a triangle

Equilateral

Isosceles

Scalene

Not a triangle

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:50 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main()
{
int a = 10;
int b = 2;
int c = 6;

if (a < b) {
if (c < b) {
cout << b;
}
else {
cout << c;
}
}
else {
if (c < a) {
cout << a;
}
else {
cout<< c;
}
}

return 0;
}

Choose heading

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:50 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main() {
int n=8, t1 = 0, t2 = 1, t3 = 0,sum = 0;
for (int i = 1; i <= n; ++i) {
if(i == 1) {
sum = sum + t1;
continue;
}
if(i == 2) {
sum = sum + t2;
continue;
};
t3 = t1 + t2;
sum = sum + t3;
t1 = t2;
t2 = t3;
}
cout << sum;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:51 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main() {
int i=0,j = 0;
while(i<10){
if(i >= 9)
break;
if(j == 8){
j = j + 2;
continue;
}
j = j + 1;
i = i + 1;
}
cout << i << " " << j;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:51 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 6; i++) {
if (i % 2 == 0) {
continue;
}
cout << i << endl;
if (i % 3 == 0) {
break;
}
}
return 0;
}

0
1
3

1
3

1
3
5

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:51 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 3; i++) {
for (int j = 2; j < 5; j++) {
cout << i << " " << j << endl;
}
}
return 0;
}

2 4

0 2
0 3
0 4
1 2
1 3
1 4
2 2
2 3
2 4

0 2
1 3
2 4

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71490/submissions/2181043/edit 1/1
7/28/24, 5:08 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:08 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:08 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

int foo() {
return 5;
}

int main() {
bar = foo() + foo()
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:09 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:09 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

int add(int a, int b) {


return a + b;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:09 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int square(int n) {
return n*n;
}

int dble(int n) {
return n+n;
}
int main() {
int c = dble(square(2)) - square(dble(2));
cout<<c;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:09 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int square(int n) {
return n*n;
}

int dble(int n) {
return n+n;
}
int main()
{
int d = dble(square(dble(square(2))));
cout<<d;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:09 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
int z = 10;
int addNum(int x){
return x+z;
}
int multNum(int y) {
return y*y;
}
int main()
{
int z = 5;
int d = addNum(5) + multNum(z);
cout<<d;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:10 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int z = 10;
int multNum(int y) {
return y*y;
}
int addNum(int x){
int z = multNum(x);
return x+z;
}

int main()
{
int z = 5;
int d = addNum(z);
cout<<d;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:10 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

void f3() {
cout << "f3 1" << endl;
}

void f2() {
cout << "f2 1" << endl;
f3();
}

void f1() {
cout << "f1 1" << endl;
f2();
cout << "f1 2" << endl;
f3();
}

int main() {
f1();
return 0;
}

f1 1
f2 1
f3 1
f1 2

f1 1
f2 1
f3 1
f1 2
f3 1

f1 1
f2 1
f3 1
f1 1
f3 1

None of the above

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:10 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
cout << x << " " << y << endl;
}

int main() {
int x = 1, y = 2;
cout << x << " " << y << endl;
swap(x, y);
cout << x << " " << y << endl;
return 0;
}

1 2
1 2
1 2

2 1
1 2
1 2

1 2
2 1
1 2

1 2
2 1
2 1

None of the above

https://coursemology.org/courses/2806/assessments/71488/submissions/2181150/edit 1/1
7/28/24, 5:16 PM Coursemology

1 2 3 4 5 6 7 8

#include <iostream>

void fun(int x)
{
x = 30;
}

int main()
{
int y = 20;
fun(y);
cout << y;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:16 PM Coursemology

1 2 3 4 5 6 7 8

# include <iostream>
void fun(int *x)
{
*x = 30;
}

int main()
{
int y = 20;
fun(&y);
cout << y;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:16 PM Coursemology

1 2 3 4 5 6 7 8

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:16 PM Coursemology

1 2 3 4 5 6 7 8

int main()
{
int *ptr;
int x;

ptr = &x;
*ptr = 0;

cout<< x <<" ";


cout<< *ptr<<" ";

*ptr += 5;
cout<< x <<" ";
cout<< *ptr<<" ";

(*ptr)++;
cout<< x <<" ";
cout<< *ptr<<" ";
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:17 PM Coursemology

1 2 3 4 5 6 7 8

#include <iostream>
using namespace std;

int main()
{
int num1=1, num2=2, num3=3;
int *p1, *p2;
p1 = &num1;
p2 = &num2;
for (int i = 0; i < 5; i++){
num1 += *p2 + num3;
*p2 = *p2 + num2;
}

cout << *p1 << " " << *p2 <<" "<<num1<<" "<<num2 ;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:17 PM Coursemology

1 2 3 4 5 6 7 8

int a, *b=&a, **c=&b;

a=4;
**c=10;

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:17 PM Coursemology

1 2 3 4 5 6 7 8

1 #include <iostream>
2
3 using namespace std;
4
5 // Define swap here. It should take in 2 parameters and return nothing (void return type).
6
7 void solution() {
8 int x, y;
9 cin >> x;
10 cin >> y;
11
12 // Call swap here
13 int temp;
14
15 temp = x;
16 x = y;
17 y = temp;
18
19 cout << x;
20 cout << y;
21 }
22

121233

-1230

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:17 PM Coursemology

1 2 3 4 5 6 7 8

https://coursemology.org/courses/2806/assessments/71492/submissions/2183145/edit 1/1
7/28/24, 5:20 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:21 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
int main(){
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1);
printf("%d", *(ptr-1) );
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:21 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main()
{

int arr[] = { 1, 2, 3, 4, 5 };
cout << arr << ", " << &arr << ", " << &arr[0] << endl;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:21 PM Coursemology

1 2 3 4 5 6 7 8 9

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:21 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>

int main()
{
int a = 5, b = 0, c = 15;
int* arr[3] = {&a, &b, &c};
cout << *arr[*arr[1] – 4];
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:21 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>

int main()
{
int a = 5, b = 0, c = 15;
int* arr[3] = {&a, &b, &c};
cout << *arr[*arr[1]]-4;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:22 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>
using namespace std;

int main() {
int lst[4] = {1, 1, 1, 1};
while (true) {
lst[0] += 1;
if (lst[0] == 3) {
break;
}
lst[2] += 3;
}

cout << lst[2] << endl;


return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:23 PM Coursemology

1 2 3 4 5 6 7 8 9

float route1[] = {1.0, 2.0, 3.0, 2.5, 4.0, 5.0, 6.0, 3.0, 1.0};
compute_upslopes(route1, sizeof(route1) / sizeof(route1[0]));
// Expected Output: 2

float route2[] = {5.0, 4.0, 3.0, 2.0, 1.0};


compute_upslopes(route2, sizeof(route2) / sizeof(route2[0]));
// Expected Output: 0

float route3[] = {3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 2.0, 3.0, 4.0, 5.0};
compute_upslopes(route3, sizeof(route3) / sizeof(route3[0]));
// Expected Output: 2

float route4[] = {2.0, 2.0, 2.0, 2.0, 2.0};


compute_upslopes(route4, sizeof(route4) / sizeof(route4[0]));
// Expected Output: 0

1 #include <iostream>
2 using namespace std;
3
4 int compute_upslopes(float route[], int size) {
5 if (size == 0) return 0;
6
7 int count = 0;
8 bool in_upslope = false;
9
10 for (int i = 1; i < size; ++i) {
11 if (route[i] > route[i - 1]) {
12 if (!in_upslope) {
13 in_upslope = true;
14 ++count;
15 }
16 } else {
17 in_upslope = false;
18 }
19 }
20
21 return count;
22 }
23
24 void solution() {
25 int N;
26 cin >> N;
27 float route[N];
28 for (int i = 0; i < N; ++i) {
29 cin >> route[i];
30 }
31 cout << compute_upslopes(route, N);
32 }
33

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:24 PM Coursemology

1 2 3 4 5 6 7 8 9

#include <iostream>

int minPairDiff(const int arr[], int size);

int main() {
// Test Case 1: Basic Test Case
int test1[] = {4, 2, 9, 7, 5};
std::cout << "Test Case 1: " << minPairDiff(test1, sizeof(test1) / sizeof(test1[0])) << " (Expected: 1)\n";

// Test Case 2: Array with only one element


int test2[] = {8};
std::cout << "Test Case 2: " << minPairDiff(test2, sizeof(test2) / sizeof(test2[0])) << " (Expected: 0)\n";

// Test Case 3: Array with negative numbers


int test3[] = {-3, -8, 2, 10, -5};
std::cout << "Test Case 3: " << minPairDiff(test3, sizeof(test3) / sizeof(test3[0])) << " (Expected: 2)\n";

// Test Case 4: Array with duplicate elements


int test4[] = {5, 2, 5, 8, 1};
std::cout << "Test Case 4: " << minPairDiff(test4, sizeof(test4) / sizeof(test4[0])) << " (Expected: 0)\n";

return 0;
}

1 #include <iostream>
2 using namespace std;
3
4 int minPairDiff(const int arr[], int size) {
5 int min = 1000000;
6 int x = 0;
7
8 if (size == 1){
9 return 0;
10 }
11
12
13 for (int i = 0; i < size; i++){
14 for(int j = i+1; j < size; j++){
15 x = abs(arr[i] - arr[j]);
16 if (x < min){
17 min = x;
18 }
19 }
20
21 }
22
23 return min;
24 }
25
26
27 void solution() {
28 int N;
29 cin >> N;
30 int route[N];
31 for(int i = 0; i < N; ++i) {
32 cin >> route[i];
33 }
34 cout << minPairDiff(route, N);
35 }
36
37

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71493/submissions/2183821/edit 1/1
7/28/24, 5:27 PM Coursemology

1 2 3 4 5 6 7 8

M[1][2]

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:27 PM Coursemology

1 2 3 4 5 6 7 8

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:27 PM Coursemology

1 2 3 4 5 6 7 8

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:28 PM Coursemology

1 2 3 4 5 6 7 8

a = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, -9, 3, 5}, {5, 1, 4, 9} }
};

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:28 PM Coursemology

1 2 3 4 5 6 7 8

int a[100][100];

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:28 PM Coursemology

1 2 3 4 5 6 7 8

#include <iostream>
int main() {
int test[3][4] = { {3, -4, 2, 3}, {0, -3, 9, -11}, {23, 12, -23, 2} };

int i,j,sum=0;
for(i=0;i<3;i++)
{
sum=0;
for(j=0;j<4;j++)
{
if(test[i][j] < 0)
{
sum = sum + i + test[i][j];
}
}
}
cout<<sum;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:29 PM Coursemology

1 2 3 4 5 6 7 8

void matrixMultiply(const int A[][MAX_SIZE], const int B[][MAX_SIZE], int C[][MAX_SIZE], int rowsA, int colsA, int rowsB, int colsB);

const int MAX_SIZE = 100;


int A[MAX_SIZE][MAX_SIZE] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int B[MAX_SIZE][MAX_SIZE] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int C[MAX_SIZE][MAX_SIZE];

matrixMultiply(A, B, C, 3, 3, 3, 3);

// Resulting matrix C:
// 30 24 18
// 84 69 54
// 138 114 90

1 #include <iostream>
2 using namespace std;
3
4 const int MAX_SIZE = 100;
5
6 int matrixMultiply(const int A[][MAX_SIZE], const int B[][MAX_SIZE], int C[][MAX_SIZE], int rowsA, int colsA, int rowsB, int colsB) {
7 // Check for incorrect dimensions
8 if (colsA != rowsB) {
9 return -1;
10 }
11
12 // Initialize matrix C to zero
13 for (int i = 0; i < rowsA; ++i) {
14 for (int j = 0; j < colsB; ++j) {
15 C[i][j] = 0;
16 }
17 }
18
19 // Perform matrix multiplication
20 for (int i = 0; i < rowsA; ++i) {
21 for (int j = 0; j < colsB; ++j) {
22 for (int k = 0; k < colsA; ++k) {
23 C[i][j] += A[i][k] * B[k][j];
24 }
25 }
26 }
27
28 return 0;
29 }
30
31 void solution() {
32 int rowsA, colsA, rowsB, colsB;
33 cin >> rowsA >> colsA >> rowsB >> colsB;
34 int A[MAX_SIZE][MAX_SIZE];
35 int B[MAX_SIZE][MAX_SIZE];
36 int C[MAX_SIZE][MAX_SIZE];
37 for (int i = 0; i < rowsA; ++i) {
38 for(int j = 0; j < colsA; ++j) {
39 cin >> A[i][j];
40 }
41 }
42 for (int i = 0; i < rowsB; ++i) {
43 for(int j = 0; j < colsB; ++j) {
44 cin >> B[i][j];
45 }
46 }
47
48 if(matrixMultiply(A, B, C, rowsA, colsA, rowsB, colsB) == -1) {
49 cout << "Invalid matrix dimensions!";
50 return;
51 }
52 for (int i = 0; i < rowsA; ++i) {
53 for (int j = 0; j < colsB; ++j) {
54 cout << C[i][j] << " ";
55 }
56 cout << endl;
57 }
58 }
59

Invalid matrix dimensions!

2 0
0 2

Choo h di
https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:30 PM Coursemology

1 2 3 4 5 6 7 8

int maxPathValue ( int arr[][MAX_ROWS], int size);

int pyramid[4][MAX_ROWS] = {
{5},
{9, 8},
{3, 6, 2},
{8, 5, 9, 3}
};
int rows = 4;

int result = maxPathValue(pyramid, rows);


// Result: 29 (5 + 9 + 6 + 9)

1 #include <iostream>
2 #include <climits>
3
4 #define MAX_ROWS 10
5 using namespace std;
6
7 int maxPathValue(int arr[][MAX_ROWS], int size) {
8 // Start from the second to last row and move upwards
9 for (int i = size - 2; i >= 0; --i) {
10 for (int j = 0; j <= i; ++j) {
11 // Update the arr array with the maximum path sum for each element
12 arr[i][j] += max(arr[i + 1][j], arr[i + 1][j + 1]);
13 }
14 }
15
16 // The top element now contains the maximum path sum
17 return arr[0][0];
18 }
19
20 void solution() {
21 int N;
22 cin >> N;
23 int pyramid[N][MAX_ROWS];
24 for(int i = 0; i < N; ++i) {
25 for (int j = 0; j < N; ++j) {
26 if (j <= i)
27 cin >> pyramid[i][j];
28 else
29 pyramid[i][j] = INT_MIN;
30 }
31 }
32 cout << maxPathValue(pyramid, N);
33 }
34

29

18

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71494/submissions/2183860/edit 1/1
7/28/24, 5:32 PM Coursemology

1 2 3 4 5 6

#include <iostream>
#include<string.h>
int main()
{
char str1[11] = "Programming";
char str2[] = {'C','o','m','p','u','t','e','r'};
int n1 = strlen(str2)/strlen(str1);
cout<<n1;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:33 PM Coursemology

1 2 3 4 5 6

#include <iostream>
#include<string.h>
int main()
{
char str1[] = "Programming";
char str2[8] = {'C','o','m','p','u','t','e','r'};
int n1 = strlen(str2)/strlen(str1);
cout<<n1;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:33 PM Coursemology

1 2 3 4 5 6

#include <iostream>
#include<string.h>
using namespace std;
int test(char *str1)
{
char *str2 = str1;
while(*++str1);
return (str1-str2);
}

int main()
{
char *str = "Computational Thinking";
cout<< test(str);
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:33 PM Coursemology

1 2 3 4 5 6

#include <iostream>
#include <string>
using namespace std;

int main() {
int i,j;
char n[10];
char names[2][3][10] = {
{"Alice", "Bob", "Charlie"},
{"David", "Eve", "Frank"}
};

for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
n[i*3+j] = names[i][j][0];

}
}
cout<<n;
return 0;
}

Choose heading

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:33 PM Coursemology

1 2 3 4 5 6

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:34 PM Coursemology

1 2 3 4 5 6

#include <iostream>
#include <string>

bool isPalindrome(const std::string& str);

int main() {
std::string input;

// Take user input


std::cout << "Enter a string: ";
std::getline(std::cin, input);

// Check if the string is a palindrome


if (isPalindrome(input)) {
std::cout << "The string is a palindrome.\n";
} else {
std::cout << "The string is not a palindrome.\n";
}

return 0;
}

// Input: "level"
// Output: true

// Input: "Palindrome"
// Output: false

1 #include <iostream>
2 #include <string>
3 #include <cctype> // Required for std::tolower and std::isalnum
4
5 using namespace std;
6
7 // Function to check if a string is a palindrome
8 bool isPalindrome(const string& str) {
9 int left = 0;
10 int right = str.length() - 1;
11
12 while (left < right) {
13 // Skip non-alphanumeric characters
14 while (left < right && !isalnum(str[left])) {
15 left++;
16 }
17 while (left < right && !isalnum(str[right])) {
18 right--;
19 }
20
21 // Compare characters ignoring case
22 if (tolower(str[left]) != tolower(str[right])) {
23 return false;
24 }
25 left++;
26 right--;
27 }
28
29 return true;
30 }
31
32 void solution() {
33 string input;
34 getline(cin, input);
35 cout << isPalindrome(input);
36 }
37

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71495/submissions/2184540/edit 1/1
7/28/24, 5:39 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

int f(int x)
{

if(x==0)
{
return g(0);
}
else if(x==1)
{
return g(g(1) + g(1));
}
else if(x%2 == 0)
{
return f(g(x / 2)) + f(g(x / 2));
}
else
{
return g(f(x - 1));
}
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:39 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;
int g(int x)
{
return 1;
}
int f(int x)
{

if(x==0)
{
return g(0);
}
else if(x==1)
{
return g(g(1) + g(1));
}
else if(x%2 == 0)
{
return f(g(x / 2)) + f(g(x / 2));
}
else
{
return g(f(x - 1));
}
}
int main()
{

cout<<f(4);
return 0;

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:39 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int f(int x)
{

if(x==0)
{
return x;
}
else
{
return f(x/2) + x;
}
}
int main()
{

cout<<f(32);
return 0;

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:40 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int f(int x)
{

if(x==0)
{
return x;
}
else
{
return f(x/2) + x;
}
}
int main()
{

cout<<f(33);
return 0;

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:40 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;
int f(int n)
{
if(n <= 1)
return 0;
if(n%2 == 0)
return f(n/2);
return n + f(n/2) + f(n/2) + 1;
}

int main()
{
cout<< f(11);
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:40 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int f4(int n) {
if (n <= 0) {
return 0;
} else {
return f4(n - 2) + n;
}
}

int main() {
cout << f4(3) << endl;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:40 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int f5(int n) {
if (n <= 0) {
return 0;
} else {
return f5(n - 2) + f5(n - 1);
}
}

int main() {
cout << f5(5) << endl;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:41 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

#include <iostream>
using namespace std;

int f4(int n) {
if (n <= 0) {
return 0;
} else {
return f4(n - 2) + n;
}
}

int main() {
cout << f4(3) << endl;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:41 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Input: 12345
Output: 15
Explanation: The sum of digits in 12345 is 1 + 2 + 3 + 4 + 5 = 15.

Input: 876543
Output: 33
Explanation: The sum of digits in 876543 is 8 + 7 + 6 + 5 + 4 + 3 = 33.

1 #include <iostream>
2
3 using namespace std;
4
5 int sumOfDigits(int num) {
6 // Base case: If the number is 0, the sum of its digits is 0
7 if (num == 0)
8 return 0;
9 // Recursive case: Return the last digit plus the sum of digits of the rest of the number
10 return num % 10 + sumOfDigits(num / 10);
11 }
12
13 void solution() {
14 int inputNumber;
15
16 // Input the integer
17 cout << "Enter an integer: ";
18 cin >> inputNumber;
19
20 // Calculate and print the sum of digits using the recursive function
21 cout << "Sum of digits: " << sumOfDigits(inputNumber) << endl;
22 }
23

Enter an integer: Sum of digits: 11

Enter an integer: Sum of digits: 29

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:41 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Input: N = 2, P = 3
Output: 8
Explanation: 2^3 = 2 * 2 * 2 = 8.

Input: N = 5, P = 2
Output: 25
Explanation: 5^2 = 5 * 5 = 25.

Input: N = -3, P = 4
Output: 81
Explanation: (-3)^4 = (-3) * (-3) * (-3) * (-3) = 81.

1 #include <iostream>
2
3 using namespace std;
4
5 int powerOfN(int N, int P) {
6 // Base case: Any number to the power of 0 is 1
7 if (P == 0)
8 return 1;
9
10 // If the exponent is negative, convert it to positive and return the reciprocal
11 if (P < 0)
12 return 1 / powerOfN(N, -P);
13
14 // Recursive case: N^P = N * N^(P-1)
15 return N * powerOfN(N, P - 1);
16 }
17
18 void solution() {
19 int base, exponent;
20
21 // Input the integers N and P
22 cout << "Enter the base N: ";
23 cin >> base;
24 cout << "Enter the exponent P: ";
25 cin >> exponent;
26
27 // Calculate and print the result of N^P using the recursive function
28 cout << base << "^" << exponent << " = " << powerOfN(base, exponent) << endl;
29 }
30
31
32
33

Enter the base N: Enter the exponent P: 3^7 = 2187

Enter the base N: Enter the exponent P: -3^13 = -1594323

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:42 PM Coursemology

1 2 3 4 5 6 7 8 9 10 11

Input: [1, 2, 3]
Output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Explanation: The input array [1, 2, 3] has six possible permutations.

Input: [4, 5, 6]
Output: [[4, 5, 6], [4, 6, 5], [5, 4, 6], [5, 6, 4], [6, 4, 5], [6, 5, 4]]
Explanation: The input array [4, 5, 6] has six possible permutations.

Input: [7]
Output: [[7]]
Explanation: The input array [7] has only one permutation, which is the

1 #include <iostream>
2 #include <vector>
3
4 using namespace std;
5
6 // Function to generate permutations recursively
7 void generatePermutationsHelper(vector<int>& arr, int start, vector<vector<int>>& result) {
8 // Base case: if start index reaches the end of the array, store the permutation
9 if (start >= arr.size()) {
10 result.push_back(arr);
11 return;
12 }
13
14 // Recursive case: swap each element with the start element and recursively generate permutations
15 for (int i = start; i < arr.size(); i++) {
16 swap(arr[start], arr[i]);
17 generatePermutationsHelper(arr, start + 1, result);
18 swap(arr[start], arr[i]); // backtrack
19 }
20 }
21
22 // Function to call the helper function and initiate the permutations generation
23 vector<vector<int>> generatePermutations(vector<int>& arr) {
24 vector<vector<int>> result;
25 generatePermutationsHelper(arr, 0, result);
26 return result;
27 }
28
29 void solution() {
30 // Input: array size and elements
31 int n;
32 cout << "Enter the size of the array: ";
33 cin >> n;
34
35 vector<int> array(n);
36 cout << "Enter the elements of the array: ";
37 for (int i = 0; i < n; i++) {
38 cin >> array[i];
39 }
40
41 // Generate permutations for the array
42 vector<vector<int>> permutations = generatePermutations(array);
43
44 // Print the generated permutations
45 cout << "Permutations: [";
46 for (const auto& permutation : permutations) {
47 cout << "[";
48 for (int i = 0; i < permutation.size(); i++) {
49 cout << permutation[i];
50 if (i < permutation.size() - 1)
51 cout << ", ";
52 }
53 cout << "]";
54 if (&permutation != &permutations.back())
55 cout << ", ";
56 }
57 cout << "]" << endl;
58 }
59

Enter the size of the array: Enter the elements of the array: Permutations: [[1, 2, 3], [1, 3,
2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

Enter the size of the array: Enter the elements of the array: Permutations: [[1, 2, 3, 4, 5],
[1, 2, 3, 5, 4], [1, 2, 4, 3, 5], [1, 2, 4, 5, 3], [1, 2, 5, 4, 3], [1, 2, 5, 3, 4], [1, 3, 2,

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71497/submissions/2189621/edit 1/1
7/28/24, 5:45 PM Coursemology

1 2 3 4 5 6 7

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:45 PM Coursemology

1 2 3 4 5 6 7

#include <iostream>
using namespace std;
#include <stdio.h>
int main()
{
int i,j;
for(i=0;i<n;++)
{
for(j=0;j<m;j++)
{
cout<<i*j;
}
}
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:45 PM Coursemology

1 2 3 4 5 6 7

#include <iostream>
using namespace std;
#include <stdio.h>
int main()
{
int n=10;
for(int i = 1; i <= n; i = i * 2)
cout<< i;
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:45 PM Coursemology

1 2 3 4 5 6 7

#include <iostream>
using namespace std;
#include <stdio.h>

int test(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*test(n-1);
}
}
int main()
{
cout<<test(5);
return 0;
}

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:45 PM Coursemology

1 2 3 4 5 6 7

Choose heading

Add a new comment here...

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:46 PM Coursemology

1 2 3 4 5 6 7

aliceSizes bobSizes aliceSizes[i] ith bobSizes[j]


jth

answer answer[0] answer[1]

Input: aliceSizes = [1,1], bobSizes = [2,2]


Output: [1,2]

Input: aliceSizes = [1,2], bobSizes = [2,3]


Output: [1,2]

Input: aliceSizes = [2], bobSizes = [1,3]


Output: [2,3]

1 <= aliceSizes.length, bobSizes.length <= 104


1 <= aliceSizes[i], bobSizes[j] <= 105

1
2 #include <algorithm>
3 #include <iostream>
4 #include <vector>
5 #include <unordered_set>
6 #include <numeric> // Include this header for accumulate
7
8
9 using namespace std;
10
11 // Function to find fair candy swap
12 vector<int> fairCandySwap(vector<int>& aliceSizes, vector<int>& bobSizes) {
13 int sumA = accumulate(aliceSizes.begin(), aliceSizes.end(), 0);
14 int sumB = accumulate(bobSizes.begin(), bobSizes.end(), 0);
15 int delta = (sumB - sumA) / 2;
16
17 unordered_set<int> setB(bobSizes.begin(), bobSizes.end());
18
19 if (sumA != sumB)
20 for (int a : aliceSizes) {
21 if (setB.count(a + delta)) {
22 return {a, a + delta};
23 }
24 }
25
26 // default case, return if valid swap found
27 return {-1, -1};
28
29 }
30
31 void solution() {
32 // Input
33 cout << "Enter Alice's sizes separated by space: ";
34 vector<int> aliceSizes;
35 int sizeAlice;
36 cin >> sizeAlice;
37 aliceSizes.resize(sizeAlice);
38 if (aliceSizes.size() >= 1 && aliceSizes.size() <= 10000)
39 for (int i = 0; i < sizeAlice; ++i)
40 cin >> aliceSizes[i];
41
42 cout << "Enter Bob's sizes separated by space: ";
43 vector<int> bobSizes;
44 int sizeBob;
45 cin >> sizeBob;
46 bobSizes.resize(sizeBob);
47 if (bobSizes.size() >= 1 && bobSizes.size() <= 10000)
48 for (int i = 0; i < sizeBob; ++i)
49 cin >> bobSizes[i];
50
51 // Call the fairCandySwap function
52 vector<int> result = fairCandySwap(aliceSizes, bobSizes);
53
54 // Displaying the result
55 cout << "Result: [" << result[0] << ", " << result[1] << "]" << endl;
56
57 }
58
59

Enter Alice's sizes separated by space: Enter Bob's sizes separated by space: Result: [1, 2]

Enter Alice's sizes separated by space: Enter Bob's sizes separated by space: Result: [1, 3]

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1
7/28/24, 5:47 PM Coursemology

1 2 3 4 5 6 7

struct AlienSpecies {
std::string name;
std::string homePlanet;
int techLevel;
};

// Sort by name
sort(speciesDatabase.begin(), speciesDatabase.end(), [](const AlienSpecies& a, const AlienSpecies& b) {
return a.name < b.name;
});

1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4
5 using namespace std;
6
7 struct AlienSpecies {
8 string name;
9 string homePlanet;
10 int techLevel;
11 };
12
13 // Function to input data for an AlienSpecies
14 AlienSpecies inputSpecies() {
15 AlienSpecies species;
16
17 cout << "Enter species name: ";
18 cin >> species.name;
19
20 cout << "Enter home planet: ";
21 cin >> species.homePlanet;
22
23 cout << "Enter tech level: ";
24 cin >> species.techLevel;
25
26 return species;
27 }
28
29 void solution() {
30 vector<AlienSpecies> speciesDatabase;
31
32 // Get the number of species from the user
33 int numSpecies;
34 cout << "Enter the number of species: ";
35 cin >> numSpecies;
36
37 // Input data for each species
38 for (int i = 0; i < numSpecies; ++i) {
39 cout << "Enter details for species " << i + 1 << ":" << endl;
40 speciesDatabase.push_back(inputSpecies());
41 }
42
43 // Sorting based on techLevel and then by species name
44 sort(speciesDatabase.begin(), speciesDatabase.end(), [](const AlienSpecies& a, const AlienSpecies& b) {
45 if (a.techLevel == b.techLevel) {
46 return a.name < b.name;
47 }
48 return a.techLevel < b.techLevel;
49 });
50
51 // Output the sorted data
52 cout << "\nSorted Species Database based on Tech Level and then by Species Name:\n";
53 for (const auto& species : speciesDatabase) {
54 cout << "Name: " << species.name << ", Tech Level: " << species.techLevel << endl;
55 }
56 }
57
58

Enter the number of species: Enter details for species 1:


Enter species name: Enter home planet: Enter tech level: Enter details for species 2:

Enter the number of species: Enter details for species 1:


Enter species name: Enter home planet: Enter tech level: Enter details for species 2:

https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1

You might also like