0% found this document useful (0 votes)
5 views134 pages

Principles of Programming Prof Appiahene

The document outlines the principles of programming, focusing on problem-solving, algorithms, and their representations through natural language, pseudocode, and flowcharts. It emphasizes the importance of understanding problems before attempting to solve them and provides guidelines for creating algorithms and pseudocode. Additionally, it discusses the characteristics and properties of algorithms, as well as the distinctions between low-level and high-level programming languages.

Uploaded by

danielakorley959
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)
5 views134 pages

Principles of Programming Prof Appiahene

The document outlines the principles of programming, focusing on problem-solving, algorithms, and their representations through natural language, pseudocode, and flowcharts. It emphasizes the importance of understanding problems before attempting to solve them and provides guidelines for creating algorithms and pseudocode. Additionally, it discusses the characteristics and properties of algorithms, as well as the distinctions between low-level and high-level programming languages.

Uploaded by

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

INFT153: PRINCIPLES

OF PROGRAMMING
Prof. Peter Appiahene
BSc Information Technology
Level 100 A, B, C & D

Dr. Peter Appiahene


CONTENTS

Introduction to Programming
01 Definitions, Processes of programming

The Art of Problem Solving


02 Steps to problem solving, examples

Algorithms
03 Definition, Properties, Characteristics, Guidelines, examples

Algorithms and Their Representation


04 Natural language, flowcharts, pseudocodes

Flowcharts
05 Deep dive into flowcharts

Dr. Peter Appiahene


Introduction to Programming

Programming?
Writing computer codes(set of instructions) that tells a computer what to do and how to do it.

The goal of computer programming is to find a set of instructions that will allow a computer to solve a given
problem (Martin, 2021).

Computer Program
Programs are a collection of instructions that tell a computer what to do and how to do it.

Who then is a Programmer?

NOTE: The role of a programmer is to find solutions

Dr. Peter Appiahene


Introduction to Programming (cont.)

Very simple programs you might have already written’😁

Alarm Auto-Reply

Reminder
Dr. Peter Appiahene
The Art of Problem Solving

• Before you can learn how to use a computer to solve a problem,


you must first understand what the problem is,

• Before attempting to solve the problem, read the problem


statement several times to ensure that you understand what is
being asked.

• Successful problem solving requires finding the right solution to


the right problem (Russell L. Ackoff).

• All new technologies, social and cultural evolution, and market-


driven economies are founded on problem-solving. It is the fou
ndation for lifelong learning, communication, and progress

Dr. Peter Appiahene


The Art of Problem Solving(cont.)
These are steps you follow to understand and solve problems:

1 Identify and Define the Problem

2 Clarify the Problem

3 Define the Goals

4 Identify Potential Solutions

5 Implement the Solutions

Dr. Peter Appiahene


The Art of Problem Solving(cont.)

Following the steps above, let’s see how to solve some common life problems.

1. You noticed you usually miss morning lectures😒


2. You need to register your courses for the semester📚
3. You are hungry and want to eat your favourite food👌
4. There is a faulty socket in the lecture hall⚡

• What other problems can you identify around you?


• Which of these challenges can you solve with a computer?

Dr. Peter Appiahene


Jack and Joe in the Army😁

• What went wrong?


• What are the consequences?

Dr. Peter Appiahene


Algorithms

o An algorithm is a finite series of instructions telling a computer how to transform a set of facts
about the world into useful information.

o A step-by-step procedure for solving a problem

o In programming we usually refer to the sequence of actions which the computer follows to
execute a particular task as a programming algorithm

o An algorithm works by having your computer perform a series of prescribed actions that
describe how to do something, and your computer will execute it the same way every time.

o A programming algorithm can be thought of as a recipe for the computer to follow to solve a
problem or achieve a goal.

NOTE: ALGORITHMS ARE NOT CODE!


Dr. Peter Appiahene
Characteristics of Algorithms

Every algorithm must possess the following characteristics:

• Finiteness: An algorithm should have a finite number of steps and it should end after a finite time.

• Input: An algorithm may have many inputs or no inputs at all.

• Output: It should result in at least one output.

• Definiteness: Each step must be clear, well-defined and precise. There should be no ambiguity.

• Effectiveness: Each step must be simple and should take a finite amount of time, and must do what
its intended for.

Dr. Peter Appiahene


Properties of an Algorithm

1. It should be straightforward.

2. There should be no misunderstanding about it.

3. It should result in a one-of-a-kind solution to the problem.

4. The solution should be reached in a finite number of steps.

5. It should be able to deal with a variety of unforeseen events.

Dr. Peter Appiahene


Important Steps to Note When Creating Algorithms

1. You don't have to write an algorithm in code.

2. Drawing diagrams or making a list of the processes neces


sary will be the initial stages in figuring out the design.

3. Use conventional tools such as flowcharts and


pseudocode to break down the problem and then
structure a solution.

4. You can begin coding the answer only after it has some
structure.

5. Pseudocode is the first step toward actually coding your


answer because it defines programming constructs
without relying on any specific language syntax.

Dr. Peter Appiahene


Examples of Algorithms

1. Prayer session (Preferred religion)

2. Recipe for cooking your favourite meal

3. Your daily morning routine before class

4. Checking your mobile money balance

5. Calculating the weekly wage of an employee given hours worked and hourly rate

6. Using long division to divide a given number

Dr. Peter Appiahene


Representation of Algorithms
There are several ways of representing(writing/creating/designing) algorithms

In the context of this course we will look at the following:

Natural Language
Pseudocodes Flowcharts
Algorithms

Dr. Peter Appiahene


Natural Language Algorithms(NLA)
Natural language algorithms are algorithms that are expressed using human language, as opposed
to a formal programming language.

These algorithms are typically written in a way that is easily understandable by humans and may
serve as a high-level description before being translated into a specific programming language.

Here are some key points regarding the representation of natural language algorithms:

• Informal and Readable


• No formal Syntax
• Structured Steps
• Abstraction

Dr. Peter Appiahene


Natural Language Algorithms(NLA) Examples

Refer to the examples of algorithms on Page 16-21 of “Practical Approach to Principles of


Programming”.

Dr. Peter Appiahene


Pros and Cons of NLA
PROS CONS

1. Accessibility 1. Lack of Precision

2. Ease of Understanding 2. Not Executable

3. Rapid Prototyping 3. Difficulty in Automated Translation

4. Problem-Solving Focus 4. Limited Expressiveness

5. Communication 5. Less Rigorous Validation

Dr. Peter Appiahene


A lil fun time😁😂

Dr. Peter Appiahene


A lil fun time😁😂

Can you spot the


“hidden tiger”?

Dr. Peter Appiahene


Pseudocodes

Dr. Peter Appiahene


Pseudocodes

• Pseudocode is a high-level description of a computer program or algorithm.

• It uses a mixture of natural language and programming language syntax to


represent the logic of the program without being tied to a specific program
ming language.

• Pseudocode is not an actual programming language as a result it cannot be


compiled into a program that can be executed

Dr. Peter Appiahene


Features of Pseudocodes

• Simplicity: Pseudocode is simple and easy to understand, making it


accessible to both programmers and non-programmers.

• Flexibility: It allows for multiple solutions to a problem and can be easily


modified or adapted.

• Language-independent: Pseudocode is not tied to any specific programming


language, making it universally applicable.

• Readability: Pseudocode is designed to be easily readable and


comprehensible, aiding in communication between developers.
Dr. Peter Appiahene
Why Pseudocodes are Used (Pros)

• Clarity: Pseudocode helps in clarifying the logic of a program before actual


coding begins, reducing the likelihood of errors.

• Transition to code: Using pseudocodes makes it easier to write actual code

• Learning: It serves as an excellent teaching tool for beginners learning progr


amming concepts, as it is less intimidating than actual code.

• Problem-solving: It allows developers to focus on solving the problem at


hand without being bogged down by language syntax.
Dr. Peter Appiahene
Disadvantages of Pseudocodes (Cons)

• Ambiguity: Sometimes pseudocode can be ambiguous, leading to different


interpretations by different individuals.

• Lack of Standards: There are no strict standards for writing pseudocode,


which can lead to inconsistency across different documents.

• Not Executable: Pseudocode cannot be directly executed by a computer;


it serves only as a blueprint for writing actual code.

• Potential Misrepresentation: Poorly written pseudocode may misrepresent


the actual logic of the program, leading to implementation errors.
Dr. Peter Appiahene
Guidelines for Preparing Pseudocodes

1. Pseudocode will be enclosed by START (or BEGIN) and STOP (or END).

2. Pseudocode should be concise so ignore unnecessary details.

3. To accept data from the user, generally used statements are INPUT, READ,
GET or OBTAIN.

4. To display results or any message generally used statements are OUTPUT,


PRINT, DISPLAY, or WRITE.

5. Generally used keywords are capitalized while preparing pseudocode


Dr. Peter Appiahene
Examples of Pseudocodes

Example 1: Tower of Hanoi

Note:
• You can move only 1 piece at a time
• You can not place a larger piece on a smaller one
Dr. Peter Appiahene
Examples of Pseudocodes

Example 1: Tower of Hanoi (Sample Answer)


1. Algorithm start
2. Move from Tower A to Tower C
3. Move from Tower A to Tower B
4. Move from Tower C to Tower B
5. Move from Tower A to Tower C
6. Move from Tower B to Tower A
7. Move from Tower B to Tower C
8. Move from Tower A to Tower C
9. Algorithm end
Dr. Peter Appiahene
Examples of Pseudocodes

Example 2: An algorithm to add two numbers

1. BEGIN
2. NUMBER firstnumber, secondnumber, sum
3. OUTPUT("Input first number:")
4. INPUT firstnumber
5. OUTPUT("Input number2:")
6. INPUT secondnumber
7. sum=firstnumber+secondnumber
8. OUTPUT sum
9. END
Dr. Peter Appiahene
Examples of Pseudocodes

Example : An algorithm to add two numbers

1. Average of two numbers


2. Area of a square
3. Algorithm to find the area of a triangle
4. Simple Interest
5. Issuing a driver’s license

Dr. Peter Appiahene


THANK
YOU

Dr. Peter Appiahene


FLOWCHATS

• A flowchart is a graphical representation of a series of steps indicating flows. It is


commonly used to present the flow of algorithms, workflows, or processes since it shows
steps in a sequential manner.

• A flowchart often displays the processes as various types of boxes, with arrows
connecting them in the correct order.
EXAMPLE OF A FLOWCHAT
FLOWCHAT SYMBOLS

• The conventional meaning of


various flowchart shapes vary. The
following are the meanings of some
of the more frequent shapes:
• Terminator:
• The terminator symbol represents
the starting or ending point of the
system.
PROCESS

• Process
• A box indicates some particular
operation/process. It can represent a
single step ("add two cups of flour"),
or an entire sub-process ("make
bread") within a larger process.
DOCUMENT

• Document
• This represents a printout, such as a
document or a report. This symbol,
for example, could be used to show
a document input, such as receiving
an email or a report. It can also be
used to symbolize the result of a
document, such as a presentation or
a project
DECISION

• Decision
• A diamond represents a
decision or branching point.
Lines coming out from the
diamond indicate different
possible situations, leading
to different sub-processes.
DATA

• Data
• It represents information
entering or leaving the
system. An input might be an
order from a customer.
Output can be a product to be
delivered.
FLOW

• Flow

• Lines represent the flow of the sequence and direction of a


process. A line that extends from one symbol to another. If the
flow is not the typical top-to-bottom, left-to-right, arrowheads are
added.
EXAMPLES OF FLOWCHATS
A flowchart showing how undergraduate students
register for courses on the UENR portal.
A FLOWCHART SHOWING HOW CLINICAL CASES
SHALL BE PROCESSED AT A MEDICAL CENTER.
ASSIGNMENT

• Draw a flowchart to show the recipe for baking a cake.


• Draw a flowchart to show how to create a Gmail
Account.
• Draw a flowchart to show how to register for National
Service.
USING PROGRAMMING LANGUAGE TO REPRESENT
ALGORITHMS
• Once we've planned our algorithm, whether, in natural language, flow charts, pseudocode,
or a combination, it's time to turn it into running code.

• A simple programming code for calculating the area of a triangle.


AREA OF A TRIANGE

using System;

class Program

{ static void Main()

float b, h, area ;

b =5 ;

h = 8;

area = ( b * h) / 2;

Console.WriteLine("Area of Right Angle Triangle is: "+area);

}}
CHAPTER THREE

OVERVIEW OF PROGRAMMING LANGUAGES


COMPUTER PROGRAMS

• A computer program is a set of instructions written in a programming language that


instructs the computer to carry out a certain activity to achieve a specific purpose.

• Programming Language

• With a computer program, a programming language is used to specify to the computer a


way to perform a particular task.
• As we have many human languages like English,
French and

PROGRAMMING • many others there are also types of programming


LANGUAGE languages like C, C++, Fortran, Java, Python,
• SQL and others.
• The figure below is an illustration using C++
C++ PROGRAMMING
PROGRAMMING
LANGUAGE
• A programming language is in
simple terms a computer language
that can be used by programmers to
connect with computers to
implement a specific task.
Programming languages allow us to
tell machines what to do.
What is a computer program?

QUIZ Computer program


instructions may be called
source code True/False?

In your own words, define a


programming language?
• There are a lot of programming languages, but
very few of them are accepted by programmers to
pursue their careers in coding. As we know that the
programming languages are used to get control
TYPES OF over the performance of a machine or computer.

PROGRAMMING • There are two types of computer programming


languages.
LANGUAGES
1. Low-level language
2. High-level language
LOW-LEVEL PROGRAMMING LANGUAGE

• This language is the most understandable language used by computers to perform their
operations. The program instructions written in these languages are in binary form.

• It can be further categorized into Machine Language and Assembly Language.


• A machine language consists of strings of binary
numbers (i.e., 0s and 1s) and it is the only language the
MACHINE processor directly understands. Machine language is
LANGUAGE also known as the first generation of programming
language.
Assembly language is another low-level programming
language because the program instructions written in
this language are close to machine language.

Assembly language is also known as the second


generation of programming languages.This language ASSEMBLY
uses mnemonics code (symbolic operation code like
‘ADD’ for addition) in place of 0s and 1s. LANGUAGE
The program is converted into machine code by the
assembler.

The resulting program is referred to as an object


code.
• These languages are close to natural language - the
spoken and written language of humans.
• For example, Python uses 'print', ‘if’, 'input', and
'while' statements - all words from the English language
- to form instructions. Instructions often look like
HIGH LEVEL abbreviated English sentences.
PROGRAMMING • A high-level language is a programming language
LANGUAGES designed to simplify computer programming. High-
level languages contain easy-to-read syntax that is later
converted into a low-level language.
C++ C# Cobol
EXAMPLES OF
HIGH-LEVEL
Fortran Java JavaScript PROGRAMMING
LANGUAGES

Python Pascal PHP


High-level programming languages can be further
categorized as:

Procedural-Oriented Language
HIGH-LEVEL
PROGRAMMING Logic Programming Language
LANGUAGES
Object-Oriented Programming

Problem-Oriented Language
• This programming executes a series of
PROCEDURAL statements that lead to an outcome. Usually, this

ORIENTED
kind of programming uses heavy loops, multiple
variables, and some other elements, which is also
LANGUAGE a major difference between procedural and
functional languages.
Its emphasis is on the
algorithm.

CHARACTERISTICS
OF PROCEDURAL The function can
PROGRAMMING communicate by a global
LANGUAGE variable.

Data move freely from


one function to another
function
• This programming language treats the data as a
OBJECT- collection of objects that have some internal data

ORIENTED and external portions of that data.


• This programming aims to think about the
PROGRAMMING problem by separating it into an object collection
LANGUAGE that offers solutions that can be used to resolve a
particular issue.
CHARACTERISTICS  Encapsulation – Encapsulation is capturing data and
OF OBJECT- keeping it safely and securely from outside interfaces.
ORIENTED
PROGRAMMING
 Inheritance- This is the process by which a class can
LANGUAGE
be derived from a base class with all features of the
base class and some of its own. This increases code
reusability.

 Polymorphism- This is the ability to exist in various


forms. For example, an operator can be overloaded to
add two integer numbers and two floats.
CHARACTERISTICS  Abstraction- The ability to represent data at a very
OF OBJECT- conceptual level without any details
ORIENTED
PROGRAMMING
 Generic Classes – Class definitions for unspecified
LANGUAGE
data. They are known as container classes. They are
flexible and reusable.

 Class Libraries – they have built-in language-


specific classes.
DIFFERENCE BETWEEN PROCEDURAL AND OBJECT-
ORIENTED PROGRAMMING LANGUAGES
DIFFERENCE BETWEEN PROCEDURAL AND OBJECT-
ORIENTED PROGRAMMING LANGUAGES
• Easy to learn.
• Easy to understand.
ADVANTAGES OF • Easy to write program.
HIGH-LEVEL
• Easy to detect and remove errors.
LANGUAGES
• Built-in library functions.
• Machine Independence.
INTERPRETERS
ASSEMBLERS AND
COMPILERS
TRANSLATORS
INTERPRETERS

• Humans can only understand high-level languages,(examples of high-level languages are


C++, Python, C# etc.), which are called source code. Computers, on the other hand, can
only understand programs written in binary languages (machine code), that is, 0’s and 1’s.

• an interpreter is a computer program that is used to directly execute program instructions


written using one of the many high-level programming languages.

• It can also be defined as a program that reads an executable program (high-level


language) and produces the results of running that program.
ROLE OF INTERPRETER

Example: Perl, Python, GWBASIC , and Matlab.


• The interpreter reads each statement of code and then
INTERPRETERS
converts or executes it directly. If there is an error in the
statement, the interpreter terminates its translating process
at that statement and displays an error message.
• The interpreter moves on to the next line for execution
only after the removal of the error.
• An Interpreter directly executes instructions written in a
programming or scripting language without previously
converting them to an object code or machine code.
ASSEMBLERS

An assembler translates assembly language into machine code. Assembly language


is a low-level language written in mnemonics that closely reflects the operations of
the CPU. A typical sequence of assembly language instructions might be

• MOV a, R1

• ADD #2, R1

• MOV R1, b
ROLEOF AN ASSEMBLER
COMPILERS

• A compiler is a program that translates a source program written in some


high-level programming language such as (such as Java) into machine
code.

• It also reports to its users the presence of errors in the source program.
C++ uses a compiler.
ROLE OF A COMPILER

In a compiler, the source code is


translated to object code successfully if it
is free of errors.

The errors must be removed before the


compiler can successfully recompile the
source code.
COMPILATION PROCESS

• A source code must go through several steps before it becomes an executable program.
• In the first step, the source code is checked for any syntax errors.
• After the syntax errors are traced out a source file is passed through a compiler which first
translates high-level language into object code (A machine code not ready to be executed).
• A linker then links the object code with pre-compiled library functions, thus creating an
executable program.
• This executable program is then loaded into the memory for execution.
• The general compilation process is shown in Figure below:
Preprocessing

STEPS OF Compiling
COMPILATION
Assembling

Linking
DIFFERENCE BETWEEN AN INTERPRETER AND A
COMPILER
• The interpreter translates just one statement of the program at a time into machine code
whereas a compiler scans the entire program and translates the whole of it into machine
code at once.
• An interpreter takes very less time to analyze the source code. However, the overall time
to execute the process is much slower. A compiler takes a lot of time to analyze the source
code. However, the overall time taken to execute the process is much faster.
• An interpreter does not generate an intermediary code. Hence, an
interpreter is highly efficient in terms of its memory. A compiler
always generates an intermediary object code. It will need further
linking. Hence more memory is needed.
DIFFERENCE • Interpreter Keeps translating the program continuously till the

BETWEEN AN first error is confronted. If any error is spotted, it stops working


and hence debugging becomes easy. A compiler generates the
INTERPRETER error message only after it scans the complete program and hence

AND A debugging is relatively harder while working with a compiler.


• Interpreters are used by programming languages like Ruby and
COMPILER Python for example.
• Compliers are used by programming languages like C and C++
for example.
QUIZ

• Name one example of a high-level programming language.

• What is meant by the term ‘machine code’?

• What are two advantages of writing computer programs using a high-level language?

• Define the following

• Compiler
• interpreter
• C++ is a programming language created by Bjarne
Stroustrup and his team at Bell Laboratories in 1979.
Forty years later, it has become one of the most widely
used languages in the world; we can find C++
applications everywhere, from the bottom of the oceans
PROGRAMMING to the surface of Mars.
WITH C++ • As the name implies, C++ was derived from the C
language; Bjarne’s goal was to add object-oriented
programming into C, a language well-respected for its
portability and low-level functionality.
WHY C++?
● It is fast and flexible.
● It is well-supported.

● C++ programs are stored in files that usually have the file extension .cpp, which simply
stands for “C plus plus”.
STRUCTURE
OF A C++
PROGRAM
PROGRAMMING WITH PYTHON
• Python is a widely-used general-purpose, high-level programming language.
• It was initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation.
• It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.
WHY PYTHON?
 Simple and easy to use.

 One of the most used languages on the field

• There are also more uses of python for a growing range of applications from machine
learning, statistical sciences, data sciences and many more
TYPICAL PYTHON PROGRAM

• # Example 1

• print('Welcome to Geeks for Geeks')


PROGRAMMING
SYNTAX AND SEMANTICS
ERRORS
• Syntax refers to the rules that define the structure of a
language.
• Syntax in computer programming means the rules that
control the structure of the symbols, punctuation, and
words of a programming language.
• Syntax is made up of functions and keywords.

SYNTAX • Function refers to pieces of code that perform a unit of


work. An example of a function is print.

• Keywords are reserved words that are used to construct


instructions. Example of keywords is while, if etc.
SYNTAX • Syntax errors are mistakes in using the language.
ERRORS • Examples of syntax errors are missing a comma or a
quotation mark or misspelling a word. Syntactic errors
are handled at the compile time.
• Syntax errors are usually easy to fix once you figure
out what they are.
HOW TO • Here are some ways to avoid the most common syntax
AVOID errors:
● Make sure you are not using a keyword for a variable
SYNTAX name.
ERRORS ● Check that you have a semicolon at the end of the
header of every compound statement, including for,
while, if, and def statements.
● Make sure that any strings in the code have matching
quotation marks.
● If you have multiline strings with triple quotes (single
or double), make sure you have terminated the string
properly.
SEMANTICS • Semantics refers to the interpretation of the
code or the associated meaning of the
symbols, characters, or any part of a program.
SEMANTIC • These are valid codes the compiler
ERRORS understands, but they do not perform the
operations you, the programmer, intended.
These may be using the wrong variable, the
wrong operation, or operations in the wrong
order. There is no way for the compiler to
detect them.

• Syntactic errors are handled at the compile


time. Semantic errors are difficult to find and
encounter at the runtime.
EXAMPLE OF • For example, in c++ a variable “s” is declared as “int
SEMANTIC s;”, to initialize it we must use an integer value. Instead
of using integers, we have initialized it with “Seven”.
ERROR This declaration and initialization are syntactically
correct but semantically incorrect because “Seven”
does not represent integer form
QUIZ • Define what we mean by a function and a keyword
with 2 examples each

• Briefly explain what is meant by the syntax and the


semantics of a programming language. Give an
example to illustrate the difference between a
syntax error and a semantics error.
I/O OPERATIONS
CHAPTHER
FOUR
 Input and output, or I/O operation is the
communication between an information processing
system, such as a computer, and the outside world.
I/O The outside word can be a human being or another

OPERATIONS
information processing system. Inputs are the
signals or data received by the system and outputs
are the signals or data sent from it.
I/O
OPERATIONS
CPU-(MEMORY )

 Programs that are loaded into memory has two areas that is,
 Machine instructions – the instructions for what we want the computer to do for us.
 Data storage – the variables that we are using in our program.
 Often programs contains instructions to interact with the input/output devices.
 Data is moved into (read) and/or out of (write) the memory data area.
 A device is a piece of equipment that is electronically connected to the memory so
that data can be transferred between the memory and the device.
INPUT-PROCESS-OUTPUT MODEL

 The input–process–output (IPO) model is a widely used approach in systems


analysis and software engineering for describing the structure of an information
processing program or another process. Many introductory programming and
systems analysis texts introduce this as the most basic structure for describing a
process.
EXAMPLE

 A computer program or any other sort of process using the input-process-output


model receives inputs from a user or other source, does some computations on the
inputs, and returns the results of the computations. The system divides the work into
three categories.

 A requirement from the environment (input)

 A computation based on the requirement (process)

 A provision for the environment (output)


EXAMPLE

 For example, a program might be written to convert Fahrenheit temperatures into


Celsius temperatures. Following the IPO model, the program must:

● Ask the user for the Fahrenheit temperature (input)


● Perform a calculation to convert the Fahrenheit temperature into the corresponding
Celsius temperature (process)
● Display the Celsius temperature (output)
VARIABLES AND DATA
CHAPTHER FIVE
TYPES
INTRODUCTION

 Variables and data types form part of the integral part of all programming
languages. This is because variables serve as storage locations in memory to hold
the values of our data during programming whereas data types serve as attributes
used in specifying what kind of data (value) we can store in our variables.
VARIABLES

 Programmers use the term ‘variable’ to refer to a position or location in the


memory of the computer where a value can be stored.
 Initially, the variable need not contain a value.
 The word variable indicates that the value of the variable may vary as needed, or
as processing is done.
 You can visualize a variable as a box in memory that contains one and only one
specific value at a given time.
RULES FOR NAMING VARIABLES

 The name must be unique.


 The name must be descriptive.
 The name may not contain spaces, but more than one word can be joined to form a name.
 A name can contain letters and numbers, such as department23, but cannot contain only
numbers.
 A variable name must start with a letter; it cannot start with a number.
 A variable name may not contain special characters, such as &, # and @.
 A variable name should be as short as possible while remaining descriptive.
STNDARDS TO FOLLOW WHEN NAMING
VARIABLES

 The convention (accepted behavior by programmers) is to use only lower-case


letters in the name of a variable, except where two or more words are joined.
 In such cases, all the following words start with an upper-case letter, which is
known as camel casing.
 The following table will throw more light on how to name variables properly and
concisely.
EXAMPLE
DATA TYPES

 A data type is an attribute associated with a piece of data that tells a


computer system how to interpret that data (value).

 Thus, it is a formal description we give to our data so that the


computer will know what to do with our data.

 We have numeric and non-numeric data types.


NUMERIC DATA TYPES

 Integers

 An integer variable contains a whole number that has no fractional or


decimal part. The number can be positive, negative or zero. Examples of
integers are the number of students or the number of items in stock. Integer
variables are typically used for items that cannot be split.

 Examples: 15, –233, 972.


FLOATING POINT VALUES

 A floating-point value contains a positive or negative number with


a decimal

 part. Examples of floating-point values are the length of a window


in metres or centimeters or an amount of money in Rands and cents.

 Examples: 12.47, –987.123, 17.00


NON-NUMERIC DATA TYPES

 Character
 A character variable contains a single letter, number or special character, such as $,
% or @. The value of a character variable is always enclosed in quotes.
 Examples: “A”, “G”, “*”, “8”
 Note that the character “8”, which is declared as a character, is not regarded as
numeric and may not be used in calculations. When declared as a character, it can be
used as a code – for instance, the group number is “8”.
Non-Numeric Data Types.
 String
 A string variable consists of two or more characters and must also be enclosed in
quotes.
 Examples: “32 Long Street” or a message, such as “The name is found.”

 Boolean
 A Boolean value can only contain a true or false value. In an everyday life
situation, a Boolean value can be compared with a light switch, which is either on or
off. In a computer language, a true value is represented by a non-zero value, whereas a
false value is represented by zero.
ARITHMETIC AND LOGICAL
OPERATORS

 Arithmetic Operators are used to performing mathematical calculations.

 The arithmetic operators perform addition(+), subtraction(-),


multiplication(*), division(/), exponentiation(^), and modulus
operations(mod).

 . Precedence is the order in which operations are performed in an


equation.
ARITHMETIC AND LOGICAL OPERATORS

Operator Description Example Result Precedence

^ Exponentiation 2^5 32 1

- Negation -True False 2


--6 +6

*,/ Multiplication, 5*10 50 3


division 10/5 2

\ Integer division 49\10 4 4

Mod Modulus arithmetic 37mod5 2 5

+,- Addition, subtraction 3+2 5 6


3-2 1
ARITHMETIC OPERATORS

 Integer division can only be done when dividing an integer value by another.
Integer value because it discards (drops) the decimal part and doesn’t round the
answer. Example: 27 \ 10 = 2
 Modulus arithmetic is done when the user only wants to know what the value of
the remainder is when dividing. Example: 52 mod 10 = 2
 Note that when operators with the same precedence occur in one expression, they
will be executed from left to right.
ARITHMETIC OPERATORS

 The order of precedence in execution is important. When an expression is


executed, it is always done:
 from left to right and
 the operator with the highest order of precedence is done before the others.
EXAMPLE

 Study this example:


 5 – 3 ^ 2 \ 8 + 17 𝑚𝑜𝑑 3 ∗ 2
 To find the answer to this expression, we need to determine which operator to execute first.
 Step 1: The exponentiation (3^2=9) is done first:
 5 – 9 \ 8 + 17 𝑚𝑜𝑑 3 ∗ 2
 Step 2: Multiplication and division are done from left to right (3*2=6):
 5 – 9 \ 8 + 17 𝑚𝑜𝑑 6
 Step 3: Integer division (9\8=1) is done next:
 5 – 1 + 17 𝑚𝑜𝑑 6
 Step 4: Modulus arithmetic (17 mod 6=5) is done
before addition or subtraction:
 5– 1 + 5
EXAMPLE  Step 5: Lastly, addition and subtraction are done
from left to right, so
 subtraction is done first because the minus is to the
left of the plus: 4 + 5 = 9
 Logical Operators, also called Boolean Operators
are used to performing logical operations which
include AND, OR, or NOT.

LOGICAL  A logical operator is a symbol or word used to


connect two or more expressions such that the value
OPERATORS of the compound expression produced depends only
on that of the original expressions and on the
meaning of the operator.
 The logical operators are often used to help create a
LOGICAL test expression that controls program flow.

OPERATORS
This type of expression is also known as a Boolean
expression because they create a Boolean answer or
value when evaluated.
OPERATORS AND THEIR MEANING

Operator Name Description Example

&& Logical Returns true if both statements are x < 5 && x < 10
and true

|| Logical or Returns true if one of the statements x < 5 || x < 4


is true

! Logical not Reverses the statement, returns false !(x < 5 && x < 10)
if the result is true
CONTROL STRUCTURES

 Control Structures can be considered as the building blocks of computer programs.


They are commands that enable a program to “take decisions”, following one path
or another.
 The basic Control Structures in programming languages are:
 Conditionals (or Selection): which are used to execute one or more statements if a
condition is met.
 Loops (or Iteration): whose purpose is to repeat a statement a certain number of
times or while a condition is fulfilled.
CONDITIONALS

 Conditionals” are at the very core of programming.


 The idea behind them is that they allow you to control the flow of the code that is
executed based on different conditions in the program.
 With conditional control structures, there is the if statement and if-else statement.
IF STATEMENTS

 If statements” execute one or more statements when a condition is met. If the


testing of that condition is TRUE, the statement gets executed. But if it’s FALSE
(the condition is not met) then nothing happens.
 The condition inside the parentheses of the IF statement is evaluated. If the result
of the test condition is true, then the instructions inside the IF body are executed. If
the result of the condition is false, then the statements are skipped.
FLOWCHAT OF
IF STATEMENT
IF-ELSE STATEMENTS

 This Control Structure allows a program to follow alternative paths of execution,


whether a condition is met or not.
 The IF-ELSE statement is used to follow a certain set of instructions based on the
result of a decision. Consider a situation in real life when you would want to make
a decision based on a condition. Let's take a very basic example that we face in
everyday life.
 If it rains, you will use an umbrella; otherwise, you will not.
STRUCTURE OF
IF-ELSE
STATEMENTS
LOOPS

 Loop statements” are nothing more than the automation of multi-step processes by
organizing sequences of actions and grouping the parts that need to be repeated.
 In general terms, there are two types of “Looping techniques”:
 “For Loops”: are the ones that execute for a prescribed number of times, as
controlled by a counter or an index.
 “While Loops” and “Repeated Loops”: are based on the onset and verification of
a logical condition. The condition is tested at the start or the end of the loop
construct.
FOR LOOP

 In this Control Structure, statements are executed one after another in consecutive
order over a sequence of values that gets evaluated only when the “For Loop” is
initiated (never re-evaluated).
 In this case, the number of iterations is fixed and known in advance. A for loop
enables a particular set of conditions to be executed repeatedly until a condition is
satisfied.
STRUCTURE
OF FOR
LOOP
WHILE LOOP

 In “While Loops” a condition is first evaluated, and if the result of


testing that condition is TRUE, one or more statements are repeatedly
executed until that condition becomes FALSE.

 Unlike “If statements”, in which a condition tested as TRUE


executes an expression only once and ends.
WHILE LOOPS

 “While Loops” are iterative statements that execute some


expression repeatedly until the condition becomes FALSE.
 If the condition never turns out to be FALSE, the “While Loop”
will go on forever and the program will crash.
 The other way around, if the condition test results FALSE at the
beginning of the loop, the expression will never get executed.
STRUCTURE
OF WHILE
LOOP
DO-WHILE LOOP

 The do while loop checks the condition at the end of the loop. This
means that the statements inside the loop body will be executed at
least once even if the condition is never true. The syntax for the do
while loop is as follows

 do {

 /* statement(s); */

 /*increment loop counter*/


QUESTIONS

 The do while loop checks the condition at the end of the loop. This
means that the statements inside the loop body will be executed at
least once even if the condition is never true. The syntax for the do
while loop is as follows

 do {

 /* statement(s); */

 /*increment loop counter*/


 What value of x will be returned with this code?
How many times does the loop execute?
 x = 0;
 do {
QUESTIONS  x = 1;
 } while (x<0);
 return x;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy