CS1 Materials
CS1 Materials
https://coursemology.org/courses/2806/materials/folders/90165/ 1/1
CS1:
Programming Methodology
UNIT 1
Computational Thinking
Computational Thinking
Breaking the problem into smaller,
more manageable parts.
CT: Decomposition
Breaking the problem into smaller,
more manageable parts.
Example:
Baking a cake
Video:
https://www.youtube.com/watch?v=yQVTijX437c
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.
CT: Algorithms
Creating solutions using a series of
ordered steps.
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)
Oh no! Run!
CeNCE Computational Thinking Unit1 - 13
I only need to
@*%$#! outrun you!
Problem Definition
Guidelines for good problem definition
Clear, concise, unambiguous.
Problem Definition
Verifying your problem definition
Is a solution possible?
Is a solution desirable?
Anything missing?
Anything extraneous?
CeNCE Computational Thinking Unit1 - 19
Happy tourists
Is a solution possible/desirable?
A no-brainer solution:
Unhappy boss
CeNCE Computational Thinking Unit1 - 23
Lessons Learned
Verbal statements can be vague.
Too hard!
What do you do when a problem
looks too hard?
Generalized problem:
What is the largest rectangular
block in a rectangular-base
pyramid?
Lesson Learned
Generalized
problem
Simplified
problem
Solve it
CeNCE Computational Thinking Unit1 - 33
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 2
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.
Contract of a Task
The Task Giver The Task Solver
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 AB
Task Solver Task Giver Br
}
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 - 8
2. Make a Plan
Design Iterative
process
Determine
problem features Analysis
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.
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
Algorithm: Example #1
CeNCE Algorithmic Problem Solving Unit2 - 14
Yes end of
input?
No
Enter num
increment count
ave sum/count sum sum + num
No
end
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
Sequence • Default
True False
• Also called ?
Selection branching
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
return 0;
}
Algorithm B:
enter values for num1, num2 Variables
used:
// Swap the values in the variables if necessary
if (num2 < num1) num1 num2
int main(void) {
int num1, num2, temp;
return 0;
}
CeNCE Algorithmic Problem Solving Unit2 - 24
False
// Display answer
print ans
Initialisation is
very important!
False
False
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
End of File
CeNCE Overview of C Programming Unit3 - 1
CS1:
PROGRAMMING METHODOLOGY
UNIT 3
Overview of C Programming
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
Executable code
Compile produces
a.out Cannot
eg: gcc first.c
compile?
Executable code
Compile produces
a.out Cannot
eg: g++ first.cpp
compile?
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
return 0;
}
declaration of variables
executable statements
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
preprocessor directives
main function header
{
declaration of variables
executable statements
} “Executable statements”
usually consists of 3 parts:
Input data
Computation
Output results
executable statements
© CeNCE Overview of C Programming Unit3 - 11
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
int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometres
return 0; punctuations
}
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’
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
Redundant initialization
int count = 0;
Initialization here
count = 123; is redundant.
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
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
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;
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.
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
Preprocessor
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
Preprocessor
int main(void) {
float miles, // input - distance in miles.
kms; // output - distance in kilometers
return 0;
}
Preprocessor
Preprocessor
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
Preprocessor
Preprocessor
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
Preprocessor
Preprocessor
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.
Preprocessor
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
Preprocessor
h
ℎ= (𝑎 + 𝑏 ) a
int main(void) {
float hypot, side1, side2;
return 0;
}
CeNCE Overview of C Programming Unit3 - 47
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.
UNIT 4
Top-Down Design & Functions
Write
Iterative
Design process
algorithm
Produce
code Implementation
Check for
correctness and Testing
efficiency
stepwise
refinement
NO (hierarchy of)
sub-problems
Knowledge in C Knowledge in
Knowledge in data structures
and its libraries
algorithms (mostly CS2)
CeNCE Top-Down Design & Functions Unit4 - 7
d2 d1
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)
Compute Total
Weight
Compute circle
area
This is called twice.
CeNCE Top-Down Design & Functions Unit4 - 13
int main(void) {
double d1, // hole circle diameter
d2, // big circle diameter
thickness,
density;
int qty;
// output
printf("Total weight of the batch of %d washers is %.2f grams.\n",
qty, total_weight);
return 0;
}
int main(void) {
int main(void) {
// identical portion omitted for brevity
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
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.
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
Unit4_DrawFigures.c
int f(int);
int main(void) {
int a;
...
}
int f(int x) {
return a + x;
}
CeNCE Top-Down Design & Functions Unit4 - 37
#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
}
#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
#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
}
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;
}
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;
}
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
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 5
Problem Solving with
Selection and Repetition Statements
Sequence
Selection
Repetition
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
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
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
if ( condition ) {
/* Execute these statements if TRUE */
}
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)
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);
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
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
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");
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;
}
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
What is wrong with this code? (There are more than one error.)
What test data should you use to expose its flaw?
Do NOT rely on
Coursemology to test your
programs!
CeNCE Problem Solving with Selection and Repetition Statements Unit5 - 37
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.
// 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
:
Loop
body
cond?
true
false
do {
// loop body
statement-1; No indentation!
statement-2;
} while (cond);
Initialization:
initialize the Condition: repeat loop
loop variable while the condition on
loop variable is true Update: change
value of loop
variable
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
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
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
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 6
Pointers
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?
“Contents”
• Now • Now
• 3 Science Drive 2, 117543 • Quantum Tech
• 6 Science Drive 2, 117546 • Graphene Research Centre
© CeNCE CS1 (Nov 2023) Unit6 - 9
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
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.
123
3. Declaring a Pointer
Syntax:
type *pointer_name;
int *a_ptr;
© CeNCE CS1 (Nov 2023) Unit6 - 15
123
123
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
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
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;
(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)
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;
}
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
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 7
Arrays
UNIT 7: Arrays
Objectives:
Understand the concept and application of arrays
Problem solving using arrays
CeNCE Arrays Unit7 - 3
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
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
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;
}
}
. . .
}
C0 C1 C2 … C28 C29
Votes for Candidates: 10 21 14 20 … 42 7
int c[30];
Element type Array size
Array name
Array Indexing
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?
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
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;
}
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
int f[5];
f[5] = {8, 23, 12, -3, 6}; // too late to do this;
// compilation error
dest[0] dest[9]
10 20 30 40 50 0 0 0 0 0
Too big!
And compiler won’t be able to detect such “error”!
May get “Segmentation Fault (core dumped)”
when you run the program!
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
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
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]);
}
In main():
foo[0] foo[1] foo[7]
44
88 9
18 17
34 12 -4 22 0 0
Enter data:
3
3
4
:
2.9
3.65
-1
Number of up-slopes = 4
CeNCE Arrays Unit7 - 39
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
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 8
Multidimensional Arrays
3. Exercise: Pyramid
CeNCE Multidimensional Arrays Unit8 - 5
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
Calling:
int main(void) { Value must not
int numbers[6]; exceed actual
... array size.
Computational
1.3 Sum Elements Thinking time again!
Computational
1.4 Sum Alternate Elements Thinking time again!
Computational
1.5 Sum Odd Elements Thinking time again!
Computational
1.6 Sum Last 3 Elements (1/3) Thinking time again!
int i, count = 0;
for (i = size - 1; (i >= 0) && (count<3) ; i--) {
. . .
count++;
}
return sum;
}
CeNCE Multidimensional Arrays Unit8 - 15
arr[2]
Inner loop index
arr[1] arr[3]
j from 2 to size-1
arr[4]
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
Lab5 58 79 73
Students’ lab marks: marks[4][5][3]
CeNCE Multidimensional Arrays Unit8 - 23
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
: :
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.
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
return maxClass;
}
10 21 7 9 3 7 18 20 13 28 25 29
4 6 14 5 6 5 8 15 10 11 22 20
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
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.
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
return 0;
}
CeNCE Multidimensional Arrays Unit8 - 35
return num_rows;
}
return 123;
}
CeNCE Multidimensional Arrays Unit8 - 37
Summary
In this unit, you have learned about
Declaring 2D arrays
Using 2D arrays in problem solving
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 9
Characters and Strings
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/
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
For example,
character 'O' is
70 O 79 (row value
70 + col value 9
= 79).
ch – 48 or ch – ‘0’
© CeNCE CS1 Problem Solving Methodology Unit9 - 15
#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;
}
Quick Quiz
1. Are 'A' and "A" the same thing? No
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
strncpy(s1, s2, n)
Copy first n characters of string pointed to by s2 to s1.
C h a n T a n \0 \0 \0 \0
C h a n T a n \0
© CeNCE CS1 Problem Solving Methodology Unit9 - 31
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
strcpy(s1,s2);
printf("After strcpy(s1,s2), s1 = %s\n", s1);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 33
Unit9_strlen.c
int mystrlen(char *p) {
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
© CeNCE CS1 Problem Solving Methodology Unit9 - 35
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!
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.
Let’s play!
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
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;
}
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
End of File
CS1:
PROGRAMMING METHODOLOGY
Unit 10
Structures
result
stuNum score grade
card
cardNum expiryDate
day month year
CS1234 178
CS1010E 358
:
© CeNCE CS1 Problem Solving Methodology Unit10 - 9
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;
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 result2;
result2.stuNum = 456654;
result2.score = 62.0;
result2.grade = 'D';
card2.expiryDate.year = 2021;
Using initializers:
player_t player1 = { "Brusco", 23, 'M' };
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;
Unit10_Demo2.c is Unit18_Demo4.c
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'
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
int main(void) {
point_t points[MAX_POINTS];
int size; // number of points
size = read_points(points);
return 0;
}
return size;
}
Unit10_Points.c
© CeNCE CS1 Problem Solving Methodology Unit10 - 25
5
34
-1 4
5 -2
-6 -2
03
max_dist = dist_sq(points[0]);
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
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
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;
typedef struct {
int max;
float ave;
} result_t;
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);
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
numStore = readStores(storeList);
return 0;
}
© CeNCE CS1 Problem Solving Methodology Unit10 - 41
return numStore;
}
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
End of File
CS1:
PROGRAMMING METHODOLOGY
UNIT 11
Recursion
1. Introduction (1/3)
Garfield dreaming
recursively.
Sierpinski triangle
Droste effect
Recursive tree
©CeNCE CS1 Problem Solving Methodology Unit11 - 5
1. Introduction (2/3)
Recursive acronyms:
1. GNU = GNU’s Not Unix
2. PHP = PHP: Hypertext Preprocessor
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
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
n! = n (n – 1) (n – 2) … 2 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.
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
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
1 0
fib(1) fib(0)
©CeNCE CS1 Problem Solving Methodology Unit11 - 15
f(0)
else else
return n * factorial(n-1); return fib(n-1) + fib(n-2);
} }
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
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?
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
100 25
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
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.
return count;
}
©CeNCE CS1 Problem Solving Methodology Unit11 - 31
to:
countValue(value, list, 0, ARRAY_SIZE)
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
A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 45
A B C
A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 47
A B C
A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 49
A B C
A B C
©CeNCE CS1 Problem Solving Methodology Unit11 - 51
A B C
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
Summary
In this unit, you have learned about
Recursion as a design strategy
The components of a recursive code
Differences between Recursion and Iteration
End of File
CS1:
PROGRAMMING METHODOLOGY
Unit 12
Searching and Sorting
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.
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]
Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2
Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2
• If A[M] == x
• Yeah.. we are done. x is found!
Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2
• 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
Binary Search
• Goal: Search for x
• Check the middle one
• With index M = (0 + n-1) / 2
• 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
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 - 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
Order of Growth
Linear
Worst case: N
Binary Search
Log2 N
y=x
y = log2 x
CeNCE Searching and Sorting Unit12 - 27
Computation
• Usually we rely on the computer to do tasks that are
• repetitive
• e.g. computing a function with series like cosine
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?
Google?
CeNCE Searching and Sorting Unit12 - 31
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…..
Speed Improvement
• If the number of data N is even larger, the improvement in
speed is even greater
y=x
y = log2 x
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
• 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
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
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
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?
Pass #comparisons
1 n–1
2 n–2
3 n–3
… …
n–1 1
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
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
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
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
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
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
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
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;
return 0;
}
Choose heading
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 }
Choose heading
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 () {
Choose heading
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 () {
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
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;
*ptr += 5;
cout<< x <<" ";
cout<< *ptr<<" ";
(*ptr)++;
cout<< x <<" ";
cout<< *ptr<<" ";
return 0;
}
Choose heading
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
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
a=4;
**c=10;
Choose heading
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
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
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
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
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
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
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
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;
}
Choose heading
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 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
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
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 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";
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
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
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
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
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
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
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
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);
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
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 pyramid[4][MAX_ROWS] = {
{5},
{9, 8},
{3, 6, 2},
{8, 5, 9, 3}
};
int rows = 4;
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
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
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
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
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
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>
int main() {
std::string input;
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
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
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
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
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
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
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
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
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
Choose heading
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
Choose heading
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
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
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
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
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
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
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
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
https://coursemology.org/courses/2806/assessments/71498/submissions/2189736/edit 1/1