Principles of C Language
Principles of C Language
Basics of C Language
Part I: Orientation and Principles of Programming
Teaching & Requirements
2 University of Oulu
Your task is to study!
University of Oulu
Objectives
First programming course
Basic principles of
programming in C
language
Basics of designing
programs in C language
Image by OpenClipart-Vectors from Pixabay
University of Oulu
Course Book &
1. Basic Principles of Programming
Contents 2. C Language and Problem Solving
3. Control Structures
4. Step-by-step Refinement and
Deitel, Paul & Deitel, Harvey:
Modular Programming
”C How to Program”
(Pearson Education) 5. Data Types
6. Arrays
7. Strings
Course material is sufficient. 8. Pointers
You may use a book of your choice, if you like.
9. Structures
10. File Handling
5 University of Oulu
About 1. Principles of
Programming
Programming
2. Programming
Langugages
3. Designing
Algorithms
University of Oulu
Principles of
Programming
University of Oulu
Waterfall Model
Requirements
Definition
Design
Implementation
Integration
Production
&
Testing Maintenance
8 University of Oulu
Analysis Phase
Preliminary Analysis of the requirements
University of Oulu
Definition Analysis of customer requirements
Phase Deriving requirements for the software (system
and technical requirements & properties)
University of Oulu
Design Phase Design of specified functionalities
= HOW those will be done
University of Oulu
Implementation
Phase Convert the designs to the programming
language to be used
University of Oulu
Integration & The purpose of testing is to find
Testing Phase errors, not to demonstrate
faultlessness
Fixing errors
Including ALU
Secondary
Output Unit
Storage Unit
University of Oulu
17
Central Memory (example values)
Address Contents
… … …
… … …
18 University of Oulu
Programming
languages
University of Oulu
Programming
‒ Machine Language
Languages ‒ Each computer vendor has it own machine
language (defined by its hardware design, CPU)
‒ For example, piece of a payroll program adding
overtime pay to base pay, and storing the result in
gross pay:
+1300042774
+1400593419
+1200274027
‒ Or, 1101101010011010 could be an instruction to
add two numbers
‒ Such languages are cumbersome for humans,
error-prone and very slow to write programs
with.
University of Oulu
21
‒ English-like instructions & commonly
High-Level used mathematical notations
Languages & ‒ One instruction may execute many
small tasks
Compilers ‒ Possible to produce portable programs
‒ E.g. Basic, Fortran, Cobol, Pascal, C,
C++, Ada, Java…
‒ Compiler = Translator program, gets
the program source code as input and
produces target code as output (target
code may be either instructions in
machine language or byte code)
‒ Examples of instructions
grossPay = basePay + overTimePay;
sqArea = cRadius * cRadius * 3.1415;
https://dribbble.com/shots/3135751-COBOL-Programming-
Class/attachments/663937?mode=media
22 University of Oulu
Interpreter Compilation a large high-level
computer program into machine
language can take (computer) time
No delay of compilation
University of Oulu
Many solutions to
Solution
a given problem #2
Solution
#4
28 University of Oulu
Functionalities In general, a programming language will provide
basic functionalities and ability to construct more
Image by Gerd Altmann from Pixabay
complicated tasks
Basic functionalities
• Assignment statements
• Arithmetic operations
• Logical operations
• Reading texts
• Output
29
University of Oulu
Pseudocode ‒ An algorithm is a method for solving
a problem in terms of the actions to
be executed and the order in which
// Calculate average grade for 10 students
those actions are to be executed.
// Input one grade at a time ‒ An algorithm is just the sequence of
steps taken to solve a problem.
Set total to zero
‒ The steps are normally sequence,
Set grade counter to one
selection, iteration type statements.
While grade counter is less than or equal to ten
Input the next grade ‒ Pseudocode is an informal way to
Add the grade into the total outline a rough draft of a program.
Set the class average to the total divided by ten
‒ Pseudocode summarizes the flow of
Print the class average.
a program but excludes underlying
details.
30 University of Oulu
Pseudocode Ask for the value of number1
Example Get the value of number1
IF number1 is greater than or equal to 0
Program to sum two numbers Ask for the value of number2
given by the user. Get the value of number2
The program will output the sum IF number2 is greater than or equal to 0
of the two numbers only if both Sum number1 and number2
of the given numbers have value
that is greater than or equal to Output the sum
zero. ELSE
Output error – number 1 is less than 0
In other cases, the program will
output zero. ELSE
Output error – number1 is less than 0
31 University of Oulu
Step-by-Step Refinement
‒ The following examples will try to provide an intuitive
explanation for an algorithm using pseudo-language (a
mixture of a programming language and natural language)
‒ Constructing an algorithm may be difficult and error-prone
‒ For example, calculating the flight time based on the
schedules
1. Get departure time
2. Get arrival time
3. Subtract departure time from arrival time
32 University of Oulu
‒ A simple problem and a simple algorithm,
Step-by-Step which will normally provide the correct
answer.
Refinement ‒ There would be problems if the places of
departure and arrival were located in
different time zones
‒ Errors may be difficult to detect, we need to
have a systematic approach in designing
1. Get departure time the algorithms
2. Get arrival time ‒ A common approach is to refine the
3. Subtract departure time from algorithm step by step (destruct and
arrival time conquer)
- Stepwise refinement or top-down design
- More general tasks are iteratively refined into
sub-tasks
‒ As an example, an algorithm for instructing a
robot to make a cup of tea (instructing a
computer to complete the task)
33 University of Oulu
Step-by-Step Algorithm for making a cup of tea
35 University of Oulu
Step-by-Step ‒ Refining the 2nd instruction
Refinement “Put tea into a cup”
36 University of Oulu
Step-by-Step ‒ Two first instructions of the
initial algorithm have been
Refinement refined
‒ We have two sub-algorithms
‒ The robot is intended to
execute the instructions
sequentially, one after another
in a pre-defined order
‒ But we may have to refine the
algorithm(s) further
‒ For example, we may want to
refine the instruction
1.1 “Fill the kettle with water”
“Method 1: Boiling water on the stove, step 1"
by wikiHow is licensed under CC BY-NC-SA 3.0
37 University of Oulu
Step-by-Step ‒ Refining the instruction
38 University of Oulu
Step-by-Step /* Algorithm for making a cup of tea */
/* Algorithm for boiling the water */
Refinement
39 University of Oulu
Step-by-Step /* Algorithm for putting tea into a cup */
2.1 Take the box of tea from the shelf
Refinement 2.2 Open the box
2.3 Take a tea bag from the box
2.4 Put the tea bag into the cup
2.5 Close the box of tea
2.6 Put the box back to the shelf
40 University of Oulu
Step-by-Step The algorithm can also be
Refinement shown with a flow chart,
see examples below… ☺
Boil water
42 University of Oulu
Image by Shahid Abdullah from Pixabay
Sequential
Execution
University of Oulu
Sequential ‒ Previous algorithm is
Execution straightforward, sequential
series of instructions for the
robot to complete the task
- The instructions will be executed
sequentially, one at a time
Task1 Task2 End - Each instruction will be executed
exactly once
- The order of writing and
executing the instructions is the
same
- The execution of the last instruction
will end the algorithm
44 University of Oulu
Sequential
‒ A sequential series of
Execution instructions is inflexible
- What happens if the box of tea
bags is empty?
- There are no options for
possible different situations?
‒ Sequential execution is an
important and fundamental
structure, but way too simple for
covering all possible cases.
45
University of Oulu
Selection
University of Oulu
Selection The algorithm needs flexibility
that is achieved by using
selection. For example, case of
empty box of tea bags…
47 University of Oulu
Selection The algorithm needs flexibility
that is achieved by using
selection. For example, case of
empty box of tea bags…
2.1 Take the box of tea from the shelf
2.1.1 IF the box is empty Condition
THEN take a new box from the cupboard Conditional
2.2 Open the box instruction
2.3 Take a tea bag from the box
2.4 Put the tea bag into the cup
2.5 Close the box of tea
2.6 Put the box back to the shelf
48 University of Oulu
Selection
‒ Common format
IF condition
THEN statement1 ‒ Selection structure can be
ELSE statement2 nested.
‒ We will design an algorithm
for choosing the largest of the
IF x > y
three number values, stored in
THEN choose x or z
ELSE choose y or z variables x, y and z.
‒ The initial version…
49 University of Oulu
Selection ‒Refining the part of
choosing x or z
IF x > y
THEN choose x or z
ELSE choose y or z
IF x > z
THEN choose x
ELSE choose z
50 University of Oulu
Selection ‒ The final algorithm…
‒ Choosing the largest of the
IF x > y number values stored in
THEN IF x > z variables x, y & z
THEN choose x
ELSE choose z ‒ Indentation is important
ELSE IF y > z for clarity, helping the
THEN choose y
ELSE choose z
reviewer to view the flow
51 University of Oulu
Iteration
University of Oulu
Iteration ‒ Let’s focus on finding some
data. Let’s assume we have
a list of persons, where
each data entry (person) is
a combination of name &
address. Our task is to find
the address of a person
with a given name.
‒ One possible algorithm
Image by Peggy und Marco Lachmann-Anke from Pixabay
could be as follows…
53 University of Oulu
Iteration
check the name of the first data entry in the list
IF the name is the same as the given name
THEN read the address of the data entry
ELSE check the name of the next data entry in the list
IF the name is the same as the given name
THEN read the address of the data entry
ELSE check the name of the next data entry in the list
IF the name is the same as the given name
THEN read the address of the data entry
ELSE check the name of the next data entry in the list …
54 University of Oulu
Iteration ‒ Do you spot the problem?
- How do we know when the
search will end?
- We do not know how many
times we would have to write
the selection sentences.
‒ Solution is iteration
structure: repeat – until
‒ By using iteration (loop) we
Image by Peggy und Marco Lachmann-Anke from Pixabay could reformat the algorithm
as follows…
55 University of Oulu
Iteration
check the name of the first data entry in the list
REPEAT
IF the name is the same as the given name
THEN read the address of the data entry
ELSE check the name of the next data entry in the list
UNTIL the given name has been found OR the list has ended
56 University of Oulu
Iteration ‒ The common format for iteration
‒ The body of the iteration will be
executed as long as the condition
is false.
repeat ‒ For example: “given name found” is
body false AND “the list has ended” is
until condition false.
‒ So, as long as the name has not
been found and the list has not
come to end, we can continue with
the search.
57 University of Oulu
Iteration
The number of times to repeat the
instructions is not fixed for a finite
structure.
• How to ensure that the iteration will be stopped?
• What if we forget to check if we have reached
the end of the list
Remember simplicity!
58 CodinGeek.com
University of Oulu
Iteration
‒ The iteration structure repeat –
until is not suitable for all tasks
set the first number N in the list as the largest number
REPEAT
requiring iteration, because the
chcek the next number in the list N condition is at the end of the
IF N > the largest number so far structure.
THEN set N as the largest number
‒ For example, if we have a list of
UNTIL the list has come to its end
print the largest number found from the list
numbers and we need to find the
largest one…
59 University of Oulu
Iteration ‒ Do you spot the problem in the
previous example?
‒ What happens if there is just one
number in the list?
- The numbers in the list will be handled
in sequence.
- The conditional statement is at the end
of the structure.
- We will need conditional statement for
ending the iteration to the beginning of
Image by Peggy und Marco Lachmann-Anke from Pixabay the iteration structure.
- One solution is iteration structure
while – do
60 University of Oulu
Iteration ‒ The iteration structure
while – do…
WHILE the list has not come to its end DO Condition to stop
chcek the next number in the list N
IF N > the largest number so far
THEN set N as the largest number
61 University of Oulu
Iteration
‒ Another common variation
for iteration
Repeat – for every element body
‒ For example, an algorithm
for calculating the factorial
of n first integers
n! = n * (n -1) * … * 1
62 University of Oulu
Iteration An example, an algorithm for
calculating the factorial of N first
integers
63 University of Oulu
Iteration And yet, another simple variation
for iteration – we know the
number of loops in advance…
set sum to zero
output sum
64 University of Oulu
MODULARITY
University of Oulu
Modularity ‒ By step-wise refinement, an
algorithm can be divided into
smaller pieces. By refinement,
we try to get to the level of
understanding the functionality.
‒ Many times the small pieces of
an algorithm may be
independent of one another
and the main algorithm.
‒ Thus, we may not have to know
the larger context in which the
pieces will be used. That is
modularity.
Image by Peggy und Marco Lachmann-Anke from Pixabay
66 University of Oulu
Modularity ‒ For example, algorithms for
instructing a plotter to draw
/* Move forward x cm */ squares.
moveForward(x) ‒ Let’s assume the plotter can
/* Turn left x degrees */ interpret the following
turnLeft(x) instructions…
/* Turn right x degrees */
turnRight(x)
/* Place the pencil on the paper */
putPencilDown
/* Lift the pencil up */
liftPencilUp
67 University of Oulu
Modularity ‒ Let’s assume that the plotter will
have to draw two squares (A & B)
inside each other, as shown below.
‒ In addition, we assume the plotter
B
will initially be placed in the center
A x, having the pencil up and facing
the direction shown by the
x arrow…
68 University of Oulu
Modularity
‒ In general, an algorithm could be
composed of four sequential instructions
‒ The 2nd and 4th instructions are
Move to point A independent functionalities, not depending
Draw a square having a side of 10 cm on the other instructions. Thus, those
Move to point B can be designed and implemented
separately as modules.
Draw a square having a side of 20 cm
‒ A module can be called differently in
different programming languages: e.g.,
procedure, routine, subroutine, function,
method…
69 University of Oulu
Modularity ‒ To be useful, in general, the method
should be able to draw a square of
given size
‒ Now drawn with side length of 10
Move to point A cm and 20 cm
Draw a square (10)
Move to point B
Draw a square (20)
70 University of Oulu
Modularity ‒ Then the module itself could be
written as follows, using the
instructions understood by the
module draw square (size) plotter
putPencilDown
repeat 4 times B
moveForward (size) A
turnLeft (90) x
liftPencipUp
71 University of Oulu
Modularity ‒ A specification will describe the
functionality of the module.
‒ E.g, for our module, the
”This module will draw a square with ”size” specification could be as follows…
being the length of its side.
The drawing will start from the spot where
the pen is currently placed, to the current
direction. The drawing will be done
counterclockwise.
When the square is completed, the pen will be
uplifted, it will return to the location from
where the drawing started and have the same
direction as when the drawing started.”
72 University of Oulu
Modularity ‒ A common format for a module
‒ Formal parameters are used in the
body of the module to perform
module draw square (size)
the given task in a general format
putPencilDown
‒ In our case the parameter ”size”
repeat 4 times will provide the length of the side
moveForward (size) for the square to be drawn.
turnLeft (90) module name (formal parameters)
liftPencipUp body
73 University of Oulu
Modularity ‒ True parameters depend on the
case.
draw square (10) ‒ True parameters are defined in the
main algorithm, in the module call.
draw square (20)
Here our module has been called
twice…
74 University of Oulu
Modularity
‒ The interface between the
module and its caller is
A side effect - when a function relies on, or
expressed
modifies, something outside its parameters to
do something.
- Explicitely (visibly) with parameters
e.g. in our case with ”size”
For example, a function which reads or writes
from a variable outside its own arguments, a - Implicitly (indirectly) with possible
database, a file, or the console can be
described as having side effects.
side effects
e.g., in our case having the pen lifted
up after completing the task
75 University of Oulu
Modularity
turnLeft (45) module draw square (size)
‒ The drawing algorithm was
moveForward (√50) putPencilDown divided into two algorithms:
turnLeft (135)
repeat 4 times the main algorithm and the
draw square (10)
moveForward (size) module (sub-algorithm)
turnLeft (90) used by it.
turnRight (135) liftPencipUp
moveForward (√50) ‒ The final main algorithm
turnLeft (135) (after elaboration) uses the
draw square (20) sub-algorithm…
76 University of Oulu
Modularity
‒ Modularity
- Central concept in programming and in designing the programs
- Fits well with the idea of step-wise refinement
- To make the design process easier, the design of a module and any modules
calling it can be done separately
- To use a module, you have to know how to call it (and what it does), not how
it completes the task
- Helps to understand algorithms, small tasks
- Helps with reusability and to reduce errors
77 University of Oulu
Data Structure
Non-Linear Linear
Stack
Queue
University of Oulu
Data Structures
‒ Data handled by the algorithms is categorized
‒ Primitive data types
- boolean values (true, false)
- characters (e.g., ’A’, ’k’, ’1’, ’<’, …)
- integers (whole numbers, e.g., 1, 24, -100, 99999, …)
- real numbers (floating point numbers, e.g., 1.5,
-99.124, 4.9E2, -0.32e32, …)
79 University of Oulu
Data Structures
‒Aggregate data types
- a character string e.g., ”cat”
- a record, e.g., (<firstname><lastname><id><tax>)
- an array
- a file
- and other more complicated types such as linked list,
queue, stack, tree, networks…
80 University of Oulu
Data Structures
‒The control structures in algorithms and the
data handled by the algorithms are closely
related.
- The way the data is structured may impact the selection of the
control structures for an algorithm, i.e., structured data
- Structured data reflects the internal relations between the data
elements
81 University of Oulu
Data Structures
‒ A common example, a list or a queue
- A list of person-address pairs
- A word in English is a queue of characters
- A sentence in English is a queue of words
- A numeric value is a sequence of numbers
- A phone book
82 University of Oulu
Learning to program = practice ! ☺