0% found this document useful (0 votes)
7 views102 pages

Chapter-2-Introduction To Computer Programming

The document is an introduction to programming, covering essential concepts such as programming languages, their generations, and the importance of programming skills. It explains the fundamentals of programming, including the characteristics of various programming languages like C++, and the advantages of learning programming for problem-solving and career opportunities. Additionally, it discusses different programming paradigms and their significance in structuring and organizing code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views102 pages

Chapter-2-Introduction To Computer Programming

The document is an introduction to programming, covering essential concepts such as programming languages, their generations, and the importance of programming skills. It explains the fundamentals of programming, including the characteristics of various programming languages like C++, and the advantages of learning programming for problem-solving and career opportunities. Additionally, it discusses different programming paradigms and their significance in structuring and organizing code.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

University of Gondar

College of Informatics

Chapter Two: Introduction to Programming

April 2025 Information Science Students

BASIC COMPUTER PROGRAMMING


Contents
▪Introduction to Computer Programming

▪Reasons to Study Programming

▪What is a Programming Language?

▪Generation of Programming Language

▪Major Programming Paradigm

▪Computational Problems

▪Algorithm Development and Representation

FUNDAMENTALS OF PROGRAMMING 2
Introduction to Computer Programming
▪Computer programming, in its essence, is the art of instructing
computers to perform specific tasks or solve complex problems. It
involves creating a set of instructions, known as a program, that the
computer can understand and execute. These instructions are
written in programming languages, which are specialized languages
designed for this purpose.

FUNDAMENTALS OF PROGRAMMING 3
Cont…
▪Computer programming is the process
of designing and writing computer programs.

▪As a skill set, it includes a wide variety of different


tasks and technique.

FUNDAMENTALS OF PROGRAMMING 4
Cont…

▪Programming is writing the code, or instructions, that computers use to


perform tasks and solve problems. Writing computer code requires the
understanding and use of a programming language, that computers can
understand.

▪Programming languages come in various forms, each with its own syntax and
structure. Some popular programming languages include Python, Java, C++,
JavaScript, PHP and many more. Each language has its strengths and is suited
for different types of applications.

FUNDAMENTALS OF PROGRAMMING 5
Introduction to C++ Programming

▪C++ is a general-purpose programming language that was


developed as an enhancement of the C language to include object-
oriented paradigm.

▪C++ is a high-level, general-purpose programming language


designed for system and application programming. It was developed
by Bjarne Stroustrup at Bell Labs in 1983 as an extension of the C
programming language.
FUNDAMENTALS OF PROGRAMMING 6
Cont…
▪C++ is an object-oriented, multi-paradigm language that supports
procedural, functional, and generic programming styles.

▪One of the key features of C++ is its ability to support low-level,


system-level programming, making it suitable for developing
operating systems, device drivers, and other system software

FUNDAMENTALS OF PROGRAMMING 7
Cont…
Some of the features & key-points to note about the
programming language are as follows:
▪Simple: It is a simple language in the sense that programs can be
broken down into logical units and parts, has a rich library support
and a variety of data-types.
▪Machine Independent but Platform Dependent: A C++
executable is not platform-independent (compiled programs on
Linux won’t run on Windows), however they are machine
independent.
▪Rich library support: Has a rich library support (Both
standard ~ built-in data structures, algorithms etc.) as well 3rd
party libraries (e.g. Boost libraries) for fast and rapid development.

FUNDAMENTALS OF PROGRAMMING 8
Cont…
▪Speed of execution: C++ programs excel in execution speed. Since, it is
a compiled language, and also hugely procedural. Newer languages have extra
in-built default features such as garbage-collection, dynamic typing etc.
▪Pointer and direct Memory-Access: C++ provides pointer support
which aids users to directly manipulate storage address. This helps in doing
low-level programming (where one might need to have explicit control on
the storage of variables).
▪Object-Oriented: One of the strongest points of the language which sets it
apart from C. Object-Oriented support helps C++ to make maintainable
and extensible programs. i.e. Large-scale applications can be built.
Procedural code becomes difficult to maintain as code-size grows.
▪Compiled Language: C++ is a compiled language, contributing to its
speed.

FUNDAMENTALS OF PROGRAMMING 9
Reasons to Study Programming
◦ Improved problem-solving skills: Programming requires logical
thinking and problem-solving skills, which can be applied to various
aspects of life.
◦ Increased job opportunities: Programming skills are in high demand
across various industries, leading to better job prospects and career
growth.
◦ Ability to create technology solutions: Programming allows
individuals to build their own software, websites, and applications, giving
them the power to create and innovate.
◦ Enhanced creativity: Programming encourages creative thinking and
experimentation, fostering a mindset of innovation and problem-solving.

FUNDAMENTALS OF PROGRAMMING 10
Cont…
▪ Grow in your current job
▪ Enhance your marketability for a new job
▪Improve your performance as an employee or leader
▪Increase your income
▪Start your own business
▪Work abroad
▪ Improve your understanding of the world

FUNDAMENTALS OF PROGRAMMING 11
Computer Programming

▪Computer programs (source code) are the instructions that


tells the computer what to do.
▪Object code == Binary code == Machine code.
▪The process of writing, testing, debugging/troubleshooting, and
maintaining the source code of computer programs.
◦ Data – characteristics
◦ Code – action

▪Computer programs is often written by professionals known as


Computer Programmers (simply programmers).
▪Source code is written in one of programming languages.

FUNDAMENTALS OF PROGRAMMING 12
Programming Language
▪A programming language is an artificial language that can
be used to control the behavior of a machine, particularly a
computer.
▪ Consists of words, symbols, and rules for writing a program

▪ Programming languages, like human languages, are defined


through the use of syntactic and semantic rules, to
determine structure and meaning respectively.

FUNDAMENTALS OF PROGRAMMING 13
Generation of Programming Language

▪Programming languages have been developed over the year


in a phased manner.
▪Each phase of developed has made the programming
language more user-friendly, easier to use and more
powerful.

FUNDAMENTALS OF PROGRAMMING 14
Cont…
▪Each phase of improved made in the development of the
programming languages can be referred to as a
generation.
▪First and second generations are low level and from
third to fifth they are high level programming language.
▪The programming language in terms of their
performance reliability and robustness can be grouped
into five different generations.

FUNDAMENTALS OF PROGRAMMING 15
First Generation Language (Machine language)
▪The first generation programming language is also called low-level
programming language because they were used to program the
computer system at a very low level of abstraction. i.e. at the machine
level.

▪The machine language also referred to as the native language of the


computer system is the first generation programming language.

▪In the machine language, a programmer only deals with a binary


number.

FUNDAMENTALS OF PROGRAMMING 16
Machine language
▪Machine language is a low-level programming language that is understood by
computers.

▪Machine language is made up of binary bits 0 and 1.

▪Machine language is also known as machine codes or object code. As machine


language consists of only 0 and 1, that’s why it is difficult to understand in raw
form. Machine language cannot understood by humans.

FUNDAMENTALS OF PROGRAMMING 17
Cont…
Advantages :
▪Fast & efficient as statements are directly written in binary language.
▪No translator is required.
They are translation free and can be directly executed by the computers.
The programs written in these languages are executed very speedily and
efficiently by the CPU of the computer system.
The programs written in these languages utilize the memory in an efficient
manner because it is possible to keep track of each bit of data.
Disadvantages :
▪Difficult to learn binary codes.
▪Difficult to understand – both programs & where the error occurred.
FUNDAMENTALS OF PROGRAMMING 18
Second Generation language (Assembly Language)

▪The second generation programming language also belongs to


the category of low-level- programming language.

▪The second generation language comprises assembly languages


that use the concept of mnemonics for the writing program.

▪In the assembly language, symbolic names are used to represent


the instruction.

FUNDAMENTALS OF PROGRAMMING 19
Assembly Language
▪An assembly language is a low-level language for
programming computers.
▪In assembly language, an instruction is an easy-to-remember
form called a mnemonic.
▪Assembler: A program that translates a program written in
assembly language into an equivalent program in machine
language.
LOAD rate
MULT hours
STOR wages

FUNDAMENTALS OF PROGRAMMING 20
Cont…
Advantages :
▪It is easier to understand if compared to machine language.
▪ Modifications are easy.
▪Correction & location of errors are easy.
Disadvantages :
▪Assembler is required.
▪This language is architecture /machine-dependent, with a
different instruction set for different machines

FUNDAMENTALS OF PROGRAMMING 21
Third Generation languages (High-Level Languages)

▪The third generation programming languages were designed to overcome


the various limitations of the first and second generation programming
languages.

▪The languages of the third and later generation are considered as a high-
level language because they enable the programmer to concentrate only on
the logic of the programs without considering the internal architecture of
the computer system.

FUNDAMENTALS OF PROGRAMMING 22
Advantages of third generation programming language
▪It is easy to develop, learn and understand the program.

▪As the program written in these languages are less prone to errors they are
easy to maintain.

▪The program written in these languages can be developed in very less time
as compared to the first and second generation language.
Examples: FORTRAN, ALGOL, COBOL, C++, C , Java, Visual Basic, and
JavaScript.

FUNDAMENTALS OF PROGRAMMING 23
Advantages
▪Use of English-like words makes it a human-understandable
language.
▪Lesser number of lines of code as compared to the above 2
languages.
▪Same code can be copied to another machine & executed on that
machine by using compiler-specific to that machine.
Disadvantages
▪Compiler/ interpreter is needed.
▪Different compilers are needed for different machines.

FUNDAMENTALS OF PROGRAMMING 24
Fourth generation language (Very High-level Languages)

▪The languages of this generation were considered as very high-


level programming languages required a lot of time and effort that
affected the productivity of a programmer.

▪The fourth generation programming languages were designed and


developed to reduce the time, cost and effort needed to develop
different types of software applications.

FUNDAMENTALS OF PROGRAMMING 25
Advantages of fourth generation languages
▪These programming languages allow the efficient use of data
by implementing the various database.
▪They require less time, cost and effort to develop different
types of software applications.
▪The program developed in these languages are highly portable
as compared to the programs developed in the languages of
other generation.
Examples: SOL, CSS, ColdFusion, Perl, Python, Ruby, SQL,
and MATLAB (Matrix Laboratory).

FUNDAMENTALS OF PROGRAMMING 26
Fifth generation language (Artificial Intelligence Language)
▪The programming languages of this generation mainly focus on constraint
programming. The major fields in which the fifth generation programming language
are employed are Artificial Intelligence and Artificial Neural Networks.

Advantages of fifth generation languages

These languages can be used to query the database in a fast and efficient manner.

In this generation of language, the user can communicate with the computer system
in a simple and an easy manner.

Examples: mercury, prolog, OPS5

FUNDAMENTALS OF PROGRAMMING 27
Cont…
•The fifth-generation languages are also called 5GL. It is based on the
concept of artificial intelligence.

•It uses the concept that rather than solving a problem algorithmically,
an application can be built to solve it based on some constraints, i.e.,
we make computers learn to solve any problem. Parallel Processing &
superconductors are used for this type of language to make real
artificial intelligence.

Examples: PROLOG, LISP, etc.


FUNDAMENTALS OF PROGRAMMING 28
Advantages
•Machines can make decisions.
•Programmer effort reduces to solve a problem.
•Easier than 3GL or 4GL to learn and use.
Disadvantages
•Complex and long code.
•More resources are required & they are expensive
too.

FUNDAMENTALS OF PROGRAMMING 29
Difference between Interpreter and compiler

FUNDAMENTALS OF PROGRAMMING 30
Programming paradigm
▪Programming paradigm is a fundamental style of computer
programming.
▪A programming paradigm is a certain way or style of
programming. It is a way of conceptualizing how to structure and
organize code.
▪Programming paradigm:
◦ programming “technique”
◦ way of thinking about programming
◦ view of a program
▪Paradigms differ in concepts and abstractions used to represent the
elements of program.

FUNDAMENTALS OF PROGRAMMING 31
Programming Paradigms Importance?
•Provide rules and guidance on how to write code.
•Help us to organize and structure code.
•Help us to match a particular programming language to a
particular task based on pros and cons. This is especially important
when dealing with other people’s code, libraries, or frameworks.
•Help us to classify programming programs
•Help us to learn new programming languages. If you understand
the programming paradigm used in a particular programming
language, you can quickly pick up a related language.

FUNDAMENTALS OF PROGRAMMING 32
Con…

▪Popular approaches
▪Procedural Programming

▪Structured Programming

▪Object-oriented Programming

FUNDAMENTALS OF PROGRAMMING 33
Procedural Programming
▪This programming paradigm is essentially an abstraction of
machine /assembly language.
▪ Program is organized around procedures
▪ Focus on data structures, algorithms and sequencing of steps
▪A procedural programming language usually consists:
▪ A collection of variables, each of which at any stage contains a certain value
(a number, a character, a string of characters, etc)
▪ A collection of statements that change the values of these variables.

▪The building-block of this type program is the procedure or


function
Programs = Algorithm + Data Structure
An algorithm is a set A data structure is a
of instructions for construct used to organize 34
solving a problem FUNDAMENTALS OF PROGRAMMING data in a specific way
Cont…
▪Procedural programming is an imperative style of
programming based on procedure calls where the program is
divided into a smaller set of instructions called procedures.

▪Procedures are also known as subroutines, functions, or


methods.

FUNDAMENTALS OF PROGRAMMING 35
Procedural Programming
▪It uses a list of instructions to tell the computer what to do step-
by-step.
▪Procedures also known as routines or subroutines.
▪A procedure contains a series of computational steps to be carried
out.
▪Procedural programming is also referred to as imperative
programming.
▪Procedural programming languages are also known as top-down
languages.

FUNDAMENTALS OF PROGRAMMING 36
Procedural Programming
If you want a computer to do something, you should provide step-
by-step instructions on how to do it.

Therefore most of the early programming languages are all


procedural.

Examples: Some procedural languages include Fortran, COBOL


and C, which have been around since the 1960s and 70s.

FUNDAMENTALS OF PROGRAMMING 37
Procedural Programming: Example

Writing a program to handle bank accounts


◦ Customer can open different type of accounts, such as cash
account, check account and Loan account
◦ For each account, customer can deposit, withdraw or transfer

Struct account {
char name; Procedure 1: Deposit() {...}
Data Structure: int accountId;
Bank Account float balance; Procedure 1: Withdraw() {...}
float interestYTD;
char accountType; Procedure 1: Transfer() {...}
};

FUNDAMENTALS OF PROGRAMMING 38
Features & benefits of procedural programming

•It follows an imperative style where detailed instructions are given in a


step-by-step manner. This makes the code easier to understand and follow.

•Program code is organized as a set of procedures or functions. A


function is a block of code that contains a list of instructions to be carried
out by the computer. Functions help to break down large projects into
smaller chunks and this makes debugging easier.

•Functions can be reused in other parts of the program. This


shortens the amount of code you need to write.

FUNDAMENTALS OF PROGRAMMING 39
Cont…

•Uses a top-down approach where a complex algorithm is broken down into


smaller fragments which are then developed further. This makes it easier to track the
program flow. However, it might lead to redundancy once you start to build up each
fragment separately.

•Data and functions are detached from each other. This might be easier to
implement in projects that are not complex.

The best known examples of languages that use procedural programming


include COBOL, FORTRAN, Pascal, ALGOL, BASIC, C, C++, and Visual Basic among
others. However, most modern languages support this style of programming.

FUNDAMENTALS OF PROGRAMMING 40
Where is procedural programming used?

•Creating operating systems. For example, the Linux Kernel is


written in C.

•Creating embedded systems drivers and applications (C,


C++).

•Creating database applications such as MySQL and Oracle.

FUNDAMENTALS OF PROGRAMMING 41
Object-Oriented Programming
▪Widely used programming methodology
▪Some terminology:
▪ object - usually a person, place or thing (a noun)
▪ method - an action performed by an object (a verb)
▪ type or class - a category of similar objects
Where all computations are carried out using objects.
An object is a component of a program that knows how to perform
certain actions and how to interact with other elements of the
program.

FUNDAMENTALS OF PROGRAMMING 42
Cont…
Object-oriented programming (OOP) is an imperative style
of programming that is based on the concept of objects.

An object is an entity that contains attributes and functions. For


example, if you have an object ‘Car’, it can
have attributes like color, model, and size, as well
as functions like drive, brake, and start.

FUNDAMENTALS OF PROGRAMMING 43
Features and benefits of object-oriented programming

•Data (attributes) and functions (methods) are bound together in objects


(i.e. encapsulation). Objects simplify the complex human world in ways
we can understand. This makes troubleshooting and collaboration
easier. It also protects data from unintended corruption.

•Only essential details are exposed to the user and the rest are hidden
(i.e. abstraction). This helps to deal with complexity, especially for large
projects.

FUNDAMENTALS OF PROGRAMMING 44
Cont…
•Child classes can inherit data and behaviors from one or more
parent classes (i.e. inheritance). This helps developers to reuse
common code and cut down on development time.

•Variables, functions, or objects can take on multiple forms


(i.e. polymorphism). A single function, for example, can adapt to
the class that it is placed in. This reduces complexity and the
amount of code you have to write.

FUNDAMENTALS OF PROGRAMMING 45
Cont…
▪OOP is one of the most popular programming paradigms and it
is present in many programming languages. These languages
include Java, C++, Python, JavaScript, PHP, R, and Scala among many
others.
Where is object-oriented programming used?
OOP has many applications and it is especially useful in modeling
real-world problems. It can be used in developing web and
desktop applications, expert systems, office automation,
object-oriented databases, and neural networks among
many other uses. Its popularity stems from the fact that it is easier
to write when creating complex programs

FUNDAMENTALS OF PROGRAMMING 46
…continued
❑Object Example:-
Person:
✓Name → Property
✓To do something(E.g. Waking) → Method

A method in object-oriented programming is like a


procedure in procedural programming.
The key difference here is that the method is part of
an object.
In object-oriented programming, you organize your
code by:-
◦ Creating objects
◦ Give those objects properties
◦ Make them do certain things

FUNDAMENTALS OF PROGRAMMING 47
…continued

A key aspect of object-oriented programming is the use of


classes.
A class is a blueprint of an object.
Let's say, you want to use a person in your program. You
want to be able to describe the person and have the person
do something.
A class called 'person' would provide a blueprint for what a
person looks like and what a person can do.
Examples of object-oriented languages include C#, Java, Perl
and Python.
FUNDAMENTALS OF PROGRAMMING 48
OOP Programming: Example

▪ Combine the accounts (data) with the operations


on the accounts to objects.
▪ A new kind of data type: BankAccount class
Class BankAccount {
private:
float balance;
float interestYTD;char * owner;
int account_number;
public:
void Deposit (float amount) {...}
float WithDraw (float amount) {…}
bool Transfer (BankAccount & to, float amount) {…}
};
FUNDAMENTALS OF PROGRAMMING 49
Procedure Oriented Object Oriented Programming
Programming
Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.
Importance In POP, Importance is not given In OOP, Importance is given to the data
to data but to functions as well rather than procedures or functions
as sequence of actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access OOP has access specifiers named Public,
specifier. Private, Protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in POP OOP provides an easy way to add new
is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, data can not move easily from
data for sharing that can be accessed function to function, it can be kept
freely from function to function in the public or private so we can control the
system. access of data.
Data Hiding POP does not have any proper way for OOP provides Data Hiding so
hiding data so it is less secure. provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the
form of Function Overloading and
Operator Overloading.
Examples Example of POP are : C, VB, FORTRAN,
FUNDAMENTALS OF PROGRAMMING Example of OOP are : C++, JAVA, 50
Computational problem
▪In computer programming, a computational problem refers to a well-defined task
or question that can be solved through computational means, typically involving
mathematical or logical operations.

▪It involves transforming input data into desired output based on a set of rules or
algorithms. Computational problems are often characterized by their complexity,
which can range from simple and straightforward to highly complex and challenging.

▪The complexity of a problem is often measured in terms of the resources required


to solve it, such as time and memory usage.

FUNDAMENTALS OF PROGRAMMING 51
Cont…
▪A computational problem is a problem that can be solved step-by-
step with a computer. These problems usually have a well-defined
input, constraints, and conditions that the output must satisfied.
Here are some types of computational problems:
▪A decision problem is one where the answer is yes or no. For
instance, "given a number , is
even?" is a decision problem. Some decision problems take more
steps to solve than others. For instance, "given a number , is
prime?" takes more steps than just checking the parity of a number.

FUNDAMENTALS OF PROGRAMMING 52
Cont…
▪A search problem is one where the solution consists of one or
more values that satisfies a given condition. For instance, we may
want to compute a path from one geographical location to another
on a map.
▪A counting problem is one where the answer is the number of
solutions to a search problem.
▪An optimization problem is one where the solution is the "best"
possible solution, where the "best" can be defined in a different
way. For instance, we may want to compute the fastest route from
one location to another.

FUNDAMENTALS OF PROGRAMMING 53
The main programming paradigms and their key differences:
Paradigm Definition Key Features Examples Advantages Disadvantages
Procedural Focuses on step-by-step instructions to Sequential execution, C, Fortran, Easy to understand, Poor modularity for large
solve problems. functions, control structures Pascal structured approach. systems, harder to
(loops, conditionals). maintain.

Object-Oriented Organizes code into objects containing Encapsulation, inheritance, Java, Python Modular and reusable Steeper learning curve,
(OOP) data (attributes) and behavior polymorphism, abstraction. (OOP), C++, code, easier to may lead to over-
(methods). Ruby maintain and extend. engineering.

Functional Treats computation as the evaluation of Immutability, first-class Haskell, Lisp, Predictable behavior, Less intuitive for
mathematical functions, avoiding functions, recursion, higher- Scala supports parallel beginners, limited library
mutable state. order functions. computing. support.

Logical Based on formal logic, defines rules and Declarative, uses facts, rules, Prolog, Datalog Clear problem-solving Slower execution, not
facts for problem-solving. and queries. structure, useful in AI suited for all types of
and databases. problems.

Declarative Focuses on defining what the program High-level abstraction, SQL, HTML, CSS Easy to write and read, Limited control over
should accomplish, not how it does so. describes the desired suitable for non- execution, less flexible for
outcome. programmers. complex tasks.

Event-Driven Program responds to events like user Asynchronous execution, JavaScript, C#, Responsive and Can become complex
actions or system messages. event handlers, listeners. [Link] interactive with many events, harder
applications. to debug.
Concurrent/Para Executes multiple processes or threads Multi-threading, Go, Java, Erlang Efficient use of Hard to debug, potential
llel simultaneously to optimize synchronization, shared resources, faster for race conditions and
performance. resources. execution for large deadlocks.
tasks.
Aspect-Oriented Focuses on separating cross-cutting Modularization of concerns, AspectJ, Spring Improves modularity, Requires additional tools,
concerns like logging and security from aspects, joins points. AOP reusable aspects. complexity in design.
core functionality.

FUNDAMENTALS OF PROGRAMMING 54
Algorithm Development and Representation
▪An algorithm is defined as a step-by-step sequence of instructions that
must terminate and describe how the data is to be processed to produce the
desired outputs.

▪A procedure or formula for solving a problem Often used for calculation,


data processing and programming.

▪Algorithms can be expressed in any language

Two common forms of algorithm are flow chart and Pseudocode.

FUNDAMENTALS OF PROGRAMMING 55
Cont…
▪Algorithms for making things will often be divided into sections
◦ The parts/components/ingredients(inputs)required to accomplish the
task
◦ Actions/steps/methods(processing)to produce the required out
come(output)

For example: To build a model car, the parts(inputs)are needed


plus instructions on how to assemble the car(processing)and the
result is the car(output)

FUNDAMENTALS OF PROGRAMMING 56
An algorithm can be represented as:-
◦ Flowchart
◦ Pseudocode
◦ Structured chart
▪Pseudocode is an artificial and informal language that
helps programmers to develop algorithms.
▪It allows the designer to focus on the logic of the
algorithm without being distracted by details of language
syntax.
▪Pseudocode is not an exact notation, since it is read by
other people, not by the computer.
57
Pseudocode
▪Pseudocode (which means fake code, because its not really
programming code) specifies the steps required to accomplish the
task.
▪Pseudocode is a type of structured English that is used to specify
an algorithm.
▪Pseudocode cannot be compiled nor executed, and there are no
real formatting or syntax rules.
▪Pseudo code is an artificial and informal language that helps
programmers develops algorithms.

FUNDAMENTALS OF PROGRAMMING 58
Programs Vs. Algorithms
To make a computer do anything, you have to write a program.
To write a computer program, you have to tell the computer,
step by step, exactly what you want it to do.
The computer then "executes" the program, following each
step mechanically, to accomplish the end goal.
An Algorithm is a finite, step-by-step sequence of instructions
that describe how the data is to be processed to produce the
desired outputs.
The algorithm is implemented by a program.

59
How to Write Pseudocode Statements?
There are six basic computer operations
1. A computer can receive information
◦ Read (information from a file)
◦ Get (information from the keyboard)
2. A computer can put out information
◦ Write (information to a file)
◦ Display (information to the screen)
3. A computer can perform arithmetic
◦ Use actual mathematical symbols or the words for the symbols

Example: Add number to total, Total = total + number, +, -,


*, /
Calculate, Compute also used
FUNDAMENTALS OF PROGRAMMING 60
How to Write Pseudocode Statements?
4. A computer can assign a value to a piece of data
3 cases:

1st case: to give data an initial value


Initialize, Set
2nd case: to assign a value as a result of some processing
=
x=5+y

3rd case: to keep a piece of information for later use


Save, Store

FUNDAMENTALS OF PROGRAMMING 61
How to Write Pseudocode Statements?
5. A computer can compare two piece of information and select
one of two alternative actions

IF condition THEN
some action
ELSE
alternative action
ENDIF
6. A computer can repeat a group of actions
WHILE condition (is true)
some action
ENDWHILE
FOR a number of times
some action
ENDFOR

FUNDAMENTALS OF PROGRAMMING 62
Example 1:
Write a Pseudocode algorithm that obtains two integer numbers
from the user. It will print out the sum of those numbers.
The possible Pseudocode algorithm:

Step 1: Prompt the user to enter the first integer

Step 2: Prompt the user to enter a second integer

Step 3: Compute the sum of the two user inputs

Step 4: Display an output prompt that explains the answer as the sum

Step 5: Display the result

FUNDAMENTALS OF PROGRAMMING 63
Example 2:
Write a Pseudocode algorithm that finds average of any three
numbers.
The possible pseudocode algorithm:

Step 1: Start

Step 2: Read values of X,Y,Z

Step 3: S=X+Y+Z

Step 4: A=S/3

Step 5: Write value of A

Step 6: Stop

FUNDAMENTALS OF PROGRAMMING 64
Example 3:
Write a Pseudocode algorithm that finds the biggest of two
numbers.
The possible pseudocode algorithm:

Step 1: Start

Step 2: Read A,B

Step 3: If A>B, then BIG=A, other wise BIG=B

Step 4: Write BIG

Step 5: Stop

FUNDAMENTALS OF PROGRAMMING 65
…continued
Example:
Set student_total to 0
WHILE student_total < 50
Read student record
Print student name and address
Add 1 to student_total
ENDWHILE
Note: The variable student_total is initialized before the loop condition is executed.
▪The student_total variable is incremented within the body of the loop so
it will eventually STOP.
▪These are both essential feature of the WHILE construct.
FUNDAMENTALS OF PROGRAMMING 66
Cont…
Algorithm to read 10 integers entered by user and find their sum.
Input ends after the 10th.
number is entered.
print "This algorithm adds 10 numbers that you enter."
Sum = 0
for i = 1 to 10
print "Enter a number"
input N
Sum = Sum + N
end for
print "The sum of the numbers you entered is " Sum

FUNDAMENTALS OF PROGRAMMING 67
Class Work

Write a Pseudocode algorithm for the following problems


1. Write an algorithm which calculates the average exam
grade for a class of 5 students.
2. Write an algorithm to determine a student’s average
grade and indicate whether he is successful or not.
3. Write an algorithm calculate a Fahrenheit value of
temperature if Celsius value is given.

FUNDAMENTALS OF PROGRAMMING 68
Flow Chart
A flowchart is a graphical representation of an algorithm
Graphically depict the logical steps to carry out a task and show
how the steps relate to each other.
Once the flowchart is drawn, it becomes easy to write the
program in any high level language.
A flowchart can therefore be used to:
◦ Define and analyze processes
◦ Build a step-by-step picture of the process for analysis, discussion, or
communication
◦ Define, standardize or find areas for improvement in a process
FUNDAMENTALS OF PROGRAMMING 69
Flow Chart Symbols
Symbol Name Meaning Examples
Flow line • Used to connect symbols & Start
indicate the flow of logic
Read A, B

• Used to represent the


Start/End beginning & the end of a task
End
• Used for input and output
Input/Output operations Print
C
• Used for arithmetic and data
Process manipulation operations C=A+B

• Used for any logic and If


C>50
Decision comparison operations Yes No
Print Print
Pass Fail
FUNDAMENTALS OF PROGRAMMING 70
Rules for Flowchart
Every flowchart has a START symbol and a STOP symbol
The flow of sequence is generally from the top of the
page to the bottom of the page. This can vary with loops
which need to flow back to an entry point
Use arrow heads on connectors where flow direction may
not be obvious
There is only one flowchart per page
A page should have a page number and a title
A flowchart on one page should not break and jump to
another page
A flowchart should have no more than around 15symbols
(not including START and STOP).
FUNDAMENTALS OF PROGRAMMING 71
Control structures and statements in C++
▪All program processes can be implemented with
these 3 control structures only.
▪Control structures are the basic entities of a
structured programming language.
▪To implements these “control structures” in a C++
program, the language provides “control
statements”.
▪So to implement a particular control structure in a
programming language, we need to learn how to use
the relevant control statements in that particular
language.

72
…continued
▪ There are three types of control structures
available in C++.
1) Sequence structure (straight line paths)
2) Selection structure (one or many branches)
3) Loop structure (repetition of a set of activities)
▪Selection structures are implemented using If , If
Else and Switch statements.
▪Looping structures are implemented
using While, Do While and For statements.

73
Flowchart of Sequence structure

74
Flowchart for if and else..if statement

75
Selection statements using switch
Multiple Selection (switch)
If the light is ...
red -> stop Light True
Red? Stop
green -> go
yellow -> slow down False
True
Light
Green? Go
False
True
Light Slow
Yellow? Down
False

76
do… while and while loop

77
for Loop Flowchart in C++

78
Repetition (continued)

For loop:-

Teaching a baby to count


Counter = 1
from 1 to 10:
counter = 1
Add 1
to counter if counter <= 10:
increment counter
Counter True
≤ 10? Print print
counter
counter number
False

79
…continued
The flowchart below represents an algorithm that displays the
numbers 20, 40, 60, 80, 100, 120, 140, 160, 180 on the screen
by do while loop.

80
Flowchart for break statement

81
Flowchart for continue statement

82
Flowchart for goto statement

83
Structure Charts
▪The primary tool used in structured design is the
structure chart.
▪Structure charts are used to graphically depict a
modular design of a program.
▪Specifically, they show how the program has been
partitioned into smaller more manageable modules,
the hierarchy and organization of those modules, and
the communication interfaces between modules.

84
…continued
▪Structure charts, however, do not show the internal procedures performed
by the module or the internal data used by the module.
•There are three components in the structured chart:
▪Modules
▪Connections between modules
▪Communication between modules

85
…continued

86
Example 1
Draw a flow chart that finds average of any two numbers.

START

Input x

Input y

Sum = x+y

Average=Sum/2

Average
output

END
FUNDAMENTALS OF PROGRAMMING 87
Example 2
Draw a flowchart to find the largest of three numbers A, B, and C.

START

Read A, B, C

IS No IS Yes IS Yes
Yes B>C? A>B? C>B?

PRINT B PRINT C
PRINT A

END
FUNDAMENTALS OF PROGRAMMING 88
Add two number by Flowchart symbols

89
Translating algorithms to programming
languages
To translating algorithms to programming
languages you must follow the following steps.
✓Understand the problem
✓Do a small example by hand
✓Write an algorithm to solve the problem
✓Translating algorithms to programming
languages

90
Qualities of good algorithm
▪Solves the problem efficiently: It achieves the desired result with minimal
computational resources.

▪Is easy to understand and implement: The algorithm should be


straightforward to comprehend and code, reducing the chances of errors.

▪Is versatile: A good algorithm can be applied to a wide range of problems with
minimal modifications.

▪Has a proven track record: If the algorithm has been successfully used in
similar scenarios, it increases its credibility.

FUNDAMENTALS OF PROGRAMMING 91
Cont…
▪Time – To execute a program, the computer system takes
some amount of time. The lesser is the time required, the
better is the algorithm.
▪Memory – To execute a program, computer system takes
some amount of memory space. The lesser is the memory
required, the better is the algorithm.
▪Accuracy – Multiple algorithms may provide suitable or
correct solutions to a given problem, some of these may
provide more accurate results than others, and such
algorithms may be suitable.

FUNDAMENTALS OF PROGRAMMING 92
Data structure
▪ A data structure is a specialized format for organizing and
storing data in the memory of a computer.
▪General data structure types include the array, file, record, table,
tree, lists, stacks, queues, heaps, and graphs.
▪Any data structure is designed to organize data to suit a
specific purpose so that it can be accessed and worked with in
appropriate ways.
…continued
▪The way in which the data is organized affects the
performance of a program for different tasks.
▪Computer programmers decide which data structures to use
based on the nature of the data and the processes that need to
be performed on that data.

94
Role of data structures in writing programs
▪Control structures organize algorithms, Whereas data
structures organize information.
▪In particular, data structures specify types of data, and thus
which operations can be performed on them, while
eliminating the need for a programmer to keep track of
memory addresses.
▪Simple data structures include integers, real numbers,
Booleans (true/false), and characters or character strings.
▪Compound data structures are formed by combining one or
more data types.
Differences Between Algorithm, Flowchart, and Pseudocode
Feature Algorithm Flowchart Pseudocode
Definition A step-by-step A graphical representation A textual representation of an
procedure to solve a of the steps in a process or algorithm using plain language
problem in a finite algorithm. and programming-like syntax.
number of steps.
Representation Written in natural Depicts steps using symbols Written using programming
language or structured like ovals, rectangles, constructs but in plain text, not
lists. diamonds, and arrows. bound to specific syntax.

Purpose To describe the logic To visually illustrate the To bridge the gap between
and sequence of process or workflow. algorithmic thinking and actual
operations. programming.
Ease of May be less intuitive Easy to understand for both Easier to follow for programmers
Understanding due to text-based technical and non-technical and closely related to actual
format. users. coding.
Detail Level High-level, focuses on Visual and process-oriented, Mid-level, focusing on steps and
steps rather than showing workflow data without strict syntax or low-
implementation. connections. level coding details.

Use Case Used for designing the Used to communicate or Used as an intermediary before
logic of complex explain processes visually to actual coding begins.
problems. stakeholders.
Tools Required None (written Requires drawing tools or Requires plain text or simple
manually). software like Lucidchart, text-editing tools.
Visio, or pen-and-paper.
FUNDAMENTALS OF PROGRAMMING 96
Review Questions
1. Define “Machine Language.”
A language consisting of a series of numbers. These numbers represent the actual
instructions used by the computer. Easy for computers to understand, but very difficult for
humans.
2. Define “Assembly Language.”
A language in which a single instruction translates directly into a single machine
instruction.
3. Define “source code.”
The high level code written by the programmer. In a high-level language, the source code is
usually machine independent.
4. Define “object code.”
The source code after it has been translated into machine language.
FUNDAMENTALS OF PROGRAMMING 97
Review Questions
5. Define “linker.”
A program that combines one or more object files with a set of
libraries and produces an executable program.
6. Define “executable program.”
A machine dependent file that contains all the instructions
necessary to perform a task.
7. Assembly language versus machine language?
Machine language is solely numbers. Assembly language uses
words to represent those numbers.
8. What does a compiler do?
It takes a source file and transforms it into an object file. Note:
many “compilers” are actually wrappers that run a compiler and a
linker.
FUNDAMENTALS OF PROGRAMMING 98
Review Questions
9. How is a compiler different from an assembler?
One assembly instruction translates to one machine language
instruction. Assembly language is a low-level language.
A compiler translates one statement into many instructions.
Compilers are also machine-independent, while assemblers are
machine-dependent.
10. What are the two common forms of algorithms?
Pseudocode
Flowcharts

FUNDAMENTALS OF PROGRAMMING 99
Worksheet One

For each of the problems below, write a

pseduocode algorithm and draw a flow chart


1. Receive a number from the keyboard and determine whether it is odd or even.

2. Obtain two numbers from the keyboard, and determine which is the larger of the two

numbers.

3. Enter three numbers and display them in ascending order from smallest to largest.

4. Find the average of two even numbers given by the user.

5. Find the average, maximum, minimum, and sum of three numbers given by the user.
FUNDAMENTALS OF PROGRAMMING 100
Con…
6. Find the area of a circle where the radius is provided by the user.

7. Swap the contents of two variables using a third variable.

8. Take an integer from the user and display the factorial of that number

9. Draw a flow chart that allows the user to input the text/code/password. This password

compared with an existing word “UOGINSC2010” which is stored in the server computer. If

the word you enter match with an existing/stored word, you can enter in and print “welcome

to UOG” on the screen. If the word doesn’t match, print “sorry, you can’t enter”.

10. Computes sum from 1 to 100(sum=1+2+3….+100).

FUNDAMENTALS OF PROGRAMMING 101


BASIC COMPUTER PROGRAMMING 102

You might also like