You are on page 1of 44

Computer Programming I

Bachelor in Telecommunication Technologies Engineering

Lecture 1
The algorithm and the programming languages
Year 2020-2021
Objectives
1. Know a computer’s structure and operation
2. Learn what a program and a programming language are
3. Distinguish between source code, object module and
executable program
4. Differentiate the stages in the process of developing
programs
5. Express the solution for a simple problem by means of an
algorithm
6. Sketch basic flowcharts
7. Know the basic elements in a C program
Computer Programming I Lecture 1 2
Contents
1. A computer’s structure and operation
2. The process of developing programs
3. The Algorithm
4. Simple Programming Examples
5. Software engineering concepts
6. Exercises

Computer Programming I Lecture 1 3


A computer’s structure and operation
• Computer = machine that can store and process
information
Input data Machine Output data
• The computer’s behaviour is controlled by a program
inside it
Computer
Input data Program Output data

Computer Programming I Lecture 1 4


A computer’s structure and operation
• The computer’s brain consists of:
– a CPU (central processing unit):
• CU (control unit) : control + decision
• ALU (arithmetic logic unit): carry out operations
– Primary memory: stores the program and the data

Arithmetic logic Primary


unit memory
Input data Program Output data
Control unit
Data

Computer Programming I Lecture 1 5


A computer’s structure and operation
• Primary memory consists of a series of memory cells (words)
– Each memory cell has an address (position in the memory)
• and consists of a sequence of bits, organized in bytes
– An instruction from the program occupies 1 or more cells
• in machine code
– Unfriendly and CPU-dependent
– Therefore, programs are written in high-level languages (C, java, ADA, …)
– Any piece of data occupies 1 or more cells
• with a specific format
• Information can be saved more permanently in Secondary
storage:
– Organized in Files:
• Programs
• Input data for a program or output data from a program

Computer Programming I Lecture 1 6


A computer’s structure and operation
• Peripherals
– Input / output units: keyboard, mouse, screen
– Secondary storage

Arithmetic logic Primary


unit memory Secondary
storage
Control unit Program

Data

Input data Output data


Other
peripherals
Computer Programming I Lecture 1 7
How the program gets into the computer
• Program: statement set or instruction sequence that the
computer executes in order to solve a problem.
• Programming: the process of writing and coding a program.
• User: a person which, as a part of his work or personal life,
uses the applications developed by other people in order to
get a problem solved.
• Programmer: person capable of building a program that
solves the problems and fulfils the needs of the users.

Computer Programming I Lecture 1 8


How the program gets into the computer
• The programmer writes the program in a high level language
– Normal written text => CPU independent => portable
– By means of a text editor (a program itself!)
– We call it source code
– Saved in secondary storage as a text file

Primary Secondary
memory storage
Text editor

Source code
Source code program.c

Computer Programming I Lecture 1 9


How the program gets into the computer
• The program text (source code) must be translated to machine code
– By means of a compiler (another program itself!)
– It checks that the text file obeys the rules of the language => is syntactically correct
– If so, it produces an object module in machine code and saves it in secondary storage
– If the compiler discovers faults, it displays an error message on the screen

Primary memory Secondary


Compiler
storage

Source code
Source code program.c
Object module
Object module program.o

Computer Programming I Lecture 1 10


How the program gets into the computer
• Usually a program consists of several object modules (and libraries)
• Thus, a second stage is needed in order to gather them together
• This is done by the linker (another program!!)
– It generates a single entity: the load module (the executable program)
– And saves it it secondary storage

Primary memory Secondary storage

Linker
Source code program.c
Object modules
Object module program.o
Load module
Load module program

Computer Programming I Lecture 1 11


How the program gets into the computer
• In order to execute the program, we must get the load module back into primary memory
• How does the computer know which program (editor, compiler, linker, our program) it should run?
• By means of the Operating System: a program (what else?) always running
– Accepts commands from the user
– If a command implies executing a program, the OS:
• locates it in secondary storage,
• loads it into primary memory and
• passes control to it

Primary memory Secondary storage

Operating System

Program Program

Computer Programming I Lecture 1 12


How a program is written
• Programming language: is a vocabulary and a set of
grammatical rules for instructing a computer to perform
specific tasks ( https://www.webopedia.com )
• Machine language:
– Directly understandable by the computer (instructions are in
binary form)
• Assembly or low-level language (=> CA):
– Close to the machine, but needs translation (assembler)
• High-level language (=> CP I, CP II):
– Close to human language, but needs translation (compiler)

Computer Programming I Lecture 1 13


How a program is written
Advantages Drawbacks
Machine language • No need of translation • Machine dependent
• Faster and more memory efficient • More difficult and slower programming
• More error prone
• More difficult to debug and maintain
• No portable

Assembly language • Easier coding • Machine dependent


• Faster computation • More complex training (the programmer needs additional
knowledge of the computer architecture)

High-level language • Short training times • Takes additional translation times


• Syntactic rules similar to human • Doesn’t take full advantage of the hardware resources of
languages the machine
• Portability • Less memory efficient
• Easier debugging and maintenance, • Takes higher execution times
hence better productivity

Computer Programming I Lecture 1 14


C Programming language
• “High-level language at a low level”
• Gives the programmer great freedom to control the
computer in detail
• Most operating systems are written in C
• Monitoring is lax => easy to make mistakes

Computer Programming I Lecture 1 15


Generating programs with C
• We will use gcc: GNU’s Compiler Collection
command Generates Meaning
emacs myprog.c & myprog.c Source code
gcc myprog.c a.out Executable code (load module)
gcc myprog.c –o myprog myprog Executable code (load module)
gcc –c mylib.c mylib.o Object module
gcc mylib.o myprog.c –o myprog myprog Executable code (load module)
Executable code (load module)
gcc –Wall myprog.c –o myprog myprog
Generates ALL the warnings

Computer Programming I Lecture 1 16


The process of developing programs
Programmer
client
Analysis
problem
Design
process
Implementation

user
Testing

program solution
Installation
Computer Programming I Lecture 1 17
The process of developing programs
• Programming = building a program
– Not just writing a code
– Analogy: building a house
• Not just laying bricks
• Careful preparation: intended use, draw plans, make calculations, …
• Goal: provide a high-quality program
– within given constraints of time and cost,
– that matches the client’s demands, and
– is reliable, well documented and easy to maintain
• A well structured approach is necessary => software engineering
– https://medium.com/edge-coders/software-engineering-is-different-from-
programming-b108c135af26
Computer Programming I Lecture 1 18
The process of developing programs
1. Requirements analysis and specification Waterfall model
– Determine what has to be done
– Outcome: requirements specification document:
• accepted by the customer and the developer
– Might include a preliminary user manual and test procedures
2. Design
– Determine how the program should meet the demands
– Parts, interconnection, algorithms, data structures, user interface, …
– Outcome: detailed system description
– And a user manual
3. Implementation
– Write the code and conduct partial tests
– Outcome: the program code
– And final test protocols

Computer Programming I Lecture 1 19


The process of developing programs
Waterfall model
4. Test and installation
– Put together all the program parts and check that everything works
– Outcome: accepted test protocol
5. Operation and maintenance
– The longest phase in the life of the product
– Corrections and updates

• So described, the waterfall model is too static


– Some degree of feedback is needed
• Clear and unambiguous specifications are necessary

Computer Programming I Lecture 1 20


Algorithms
• A description of how a particular problem is solved
• Consists of a number of elemental operations and instructions
about the order in which the operations should be carried out
• Algorithms are frequently used in everyday life:
– Cooking recipes, furniture assembly instructions, knitting patterns, …
• An algorithm should solve the given problem
• It should be unambiguous
• If the program has an end in view, the algorithm should terminate
after a finite number of steps
• I must be deterministic:
– For a given input, it must always produce the same result
Computer Programming I Lecture 1 21
Algorithms
• Problem: How to get to the CUVI?
– Buy a transport card
– Charge the card with enough money for 2 tickets (up/down)
– Go to a bus stop suitable for lines 8, 15C or CUVI shuttles
– Wait for the bus to come
– Get into the bus
– Validate every trip, by inserting the transport card in the reader located at the bus
entrance
– Get off the bus when arriving to the Telecommunication Engineering School (in case it is
unknown ask some other passenger or the driver)
• Algorithm for determining if
an integer number is a prime
number.

Task
Computer Programming I Lecture 1 22
Problem solving with computers
1. Specification: define the problem in a formal way
2. Programming: design an algorithm for solving the problem
– Top-down design of the algorithm
• Split the problem into smaller subproblems
• Solve the subproblems separately
• Split the subproblems into simpler subproblems
• Keep doing this until the subproblems are trivial

3. Coding: express the algorithm as a program in a programming


language
4. Executing: compile and run the program in the computer
Computer Programming I Lecture 1 23
Designing an algorithm
• One common way is in natural language
– Not recommendable
• Other option is the use of pseudo code:
– Uses the conventional structures common to many programming languages.
– But is independent of the programming language.
– Avoid details not necessary for the algorithm comprehension.
– Uses a compact mathematical notation.
• Flowcharts can also be used:
– Same features as pseudo codes
– But with a graphical notation

Computer Programming I Lecture 1 24


Designing an algorithm Start

Specification:
Swap the letters in a word, leaving the first and the last
character unchanged Lines to No
A word is formed by all consecutive characters (both be read?
End
letters and digits) between spaces
INPUT: a text file (organized in lines) Yes
OUTPUT: write to the screen the words of the file with
their letters swapped (except for the first and the last)
Read a line

Pseudocode: Write the “new” word

• Until all the lines have been read:


• Read a line from the file, No Words to be
• Until the whole line has been processed: extracted?
• Extract a word, Yes
• Swap its characters, and
• Write to the screen the swapped word
Extract a
Swap letters
word
Computer Programming I Lecture 1 25
Flowcharts
Terminal: Start or End
On-page connector

Process
Subroutine

Decision

Data input
Data output

Computer Programming I Lecture 1 26


Flowcharts
1. Every flowchart must have a beginning and an ending.
2. The flowlines used to show the order of operation must be straight lines:
vertical or horizontal (except for loops)
3. All flowlines must be connected. The connection can be a symbol
denoting data input, data output, processing, decision, start or end of the
chart.
4. The flowchart must run top-to-bottom left-to-right (except for loops)
5. The notation used in the flowchart must be independent of the
programming language.
6. When describing a complex task, it is advisable to add comments in order
to clarify concepts and help to understand the graph.
7. No more than one line can arrive to a given symbol (except for connectors)

Computer Programming I Lecture 1 27


Flowcharts Start
Inicio

• Purposes: Data de
Lectura

– Design
datos
input

– Communication
Data de
Procesado

• For yourself datos


processing

• Among programmers
• With the final user Impresión
Results de
displaying
resultados

– Facilitate programming
Finnish
FIN

Computer Programming I Lecture 1 28


The simplest C program

• Output:
Hello, World!
_

Computer Programming I Lecture 1 31


Several statements?
Enter the first integer number: 34
Enter the second integer number: 4

The sum is: 38


The product is: 136
_

• Block: {
• Every statement (instruction) is terminated statement;
with a semicolon (‘;’) …
• Wherever we can write a single statement, statement;
we can write a block instead }
Computer Programming I Lecture 1 32
Decision statements
Enter the first integer number: 34
Enter the second integer number: 56

The second integer number is bigger


_

Incorrect if the
numbers are equal

Computer Programming I Lecture 1 34


What if the numbers are equal?
Enter the first integer number: 34
Enter the second integer number: 34

The integer numbers are equal


_

Computer Programming I Lecture 1 35


The else part is optional
Enter the number of items sold: 100
Enter the cost per item: 20.0

Final price is: 1800.00€


_

Computer Programming I Lecture 1 36


Block construction
• It is the simplest of C
language’s constructions if (condition)
statement;
if (a > b)
max = a;
• Any place in a program else
statement;
else
max = b;
where we can write a
simple statement, we can if (a > b) {
also write a block max = a;
if (condition) min = b;
• No ending semicolon! block }
else else {
block max = b;
min = a;
}

Computer Programming I Lecture 1 37


Iteration instructions
Enter the table size: 5

Number Square
1 1
2 4
3 9
4 16
5 25
_

• What if the numbers are bigger than the reserved space?


Computer Programming I Lecture 1 39
More iteration instructions
Day 1. Profit: 0.01
Day 2. Profit: 0.03
Day 3. Profit: 0.07
Day 4. Profit: 0.15
...
Day 25. Profit: 335544.31
Day 26. Profit: 671088.62
Day 27. Profit: 1342177.25

You will be a millionaire in: 27 days


_

Computer Programming I Lecture 1 41


*****

Code reuse?
* *
* *
*****
*
*
*

******
*
*
*****
*
*
******

*****
* *
* *
*****
*
*
*

******
*
*
*****
*
*
******
_

Computer Programming I Lecture 1 43


*****

Functions
* *
* *
*****
*
*
*

******
*
*
*****
*
*
******

*****
* *
* *
*****
*
*

• What if we want
*

subprograms to do
******
*
*
different things for *****
*
different values? *
******
_

Computer Programming I Lecture 1 44


Modular Programming
• The program is divided into independent modules
• Each module performs just one specific task
• A special module is in charge of controlling the whole program
– Called the “main routine”
– In C, it is the main() function (surprised?)
– The only mandatory function in a C program
– Marks the code to be executed when the program is run
– Transfers control to the other modules as needed
– Recovers control when the other modules finish
– When a module needs to hand a value back to the caller module, it uses the return statement

Different programmers can work simultaneously in different parts of the


same program:
• The program’s design and coding time is reduced
• Modifications to a module don’t affect the rest
Computer Programming I Lecture 1 45
Structured Programming
• The program exhibits a modular design
• Modules are built using a top-down design
• Every module is coded using three basic control structures:
– Block
– Decision
– Iteration

Using a reduced number of control structures:


• Minimizes complexity
• Reduces mistakes
• Makes programs easier to write, verify, read and maintain
Computer Programming I Lecture 1 46
Programming Paradigms
• Procedure oriented programming (POP):
– The problem is visualised as a sequence of tasks to perform, which are
deployed as functions.
– Centred around the functions, and not the data which the functions work with
Ø we deal with POP in Computer Programming I

• Object oriented programming (OOP):


– Programs are defined in terms of “object classes”.
– Centred around the data; functions (methods) are built around them
Ø we deal with OOP in Computer Programming II

Computer Programming I Lecture 1 47


Exercise: calculate the mid-term tests grade
for Computer Programming I
• We have 3 input data:
– NP1: mid-term test 1 grade
– NP2: mid-term test 2 grade
– NP3: mid-term test 3 grade
• And 1 output datum:
– NPP: mid-term tests grade
• How many variables do we need?
• Which types?
• Top-down design:
1. Get the input data
2. Do the calculations
3. Show the output data
Computer Programming I Lecture 1 48
Exercise: calculate the final grade for
Computer Programming I
• We have 3 input data:
– NPP: mid-term tests grade
– ETF: final theory test grade
– EPF: final practice test grade
• And 1 output datum:
– The final grade
• How many variables do we need?
• Which types?
• Top-down design:
1. Get the input data
2. Do the calculations
3. Show the output data
Computer Programming I Lecture 1 50
References
• Brian W. Kernighan & Dennis M. Ritchie, The C Programming
Language, 1995, Prentice Hall.
• Manuel Caeiro Rodríguez, Enrique Costa Montenegro, Ubaldo
García Palomares, Cristina López Bravo, J, Practicar Programación
en C, 2014, Andavira.
• Learn C Programming,
https://www.tutorialspoint.com/cprogramming/
• Stephen G. Kochan, Programming in C, 2014, Addison Wesley.

A lot of material for this lecture comes from a book on Ada language
(proving that programming != coding):
• Jan Skansholm, Ada from the Beginning, 1994, Adisson-Wesley.
Computer Programming I Lecture 1 52

You might also like