0% found this document useful (0 votes)
16 views

Problem Solving I Chapter 1

This document provides an overview of the CS221 Computer Programming I course. The chapter objectives are to understand computers and programming. It defines key concepts like algorithms, programs, and problem solving. It also covers the basic components of a computer system including hardware like the CPU, memory, buses, I/O interfaces, and peripheral devices. The document explains the Von Neumann architecture and how programs are stored and executed. It also outlines the steps of programming like understanding the problem, planning an algorithm, and implementing code.

Uploaded by

Estif Behailu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Problem Solving I Chapter 1

This document provides an overview of the CS221 Computer Programming I course. The chapter objectives are to understand computers and programming. It defines key concepts like algorithms, programs, and problem solving. It also covers the basic components of a computer system including hardware like the CPU, memory, buses, I/O interfaces, and peripheral devices. The document explains the Von Neumann architecture and how programs are stored and executed. It also outlines the steps of programming like understanding the problem, planning an algorithm, and implementing code.

Uploaded by

Estif Behailu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

CS221 : Computer Programming I

• Chapter 1: An overview of Computers and


Programming

1
Chapter Objective
After the completion of this chapter you are expected to
• Understand what computer system is, its essence, its classification
and the basic elements that comprise it and the functionality of these
elements.
• Understand the concept of algorithm, program, and their relation
with respect to problem solving
• Understand the steps involved in problem solving
• Learn about what programming language is, its essence and its
evolution.
• Learn about the tools and steps involved in program development
using C++
• Learn the different types of errors in program

2
CS221 : Computer Programming I

Overview of Computer
System

3
What is computer?

A computer is a general purpose electronic


device capable of taking an input, store it,
processing it and giving an output, all under
the control of a set of instruction called
program.

4
Characteristics of a computer

Characteristics of a computer:
– Speed
– Accuracy
– Reliability
– Diligence
– Memory and Mass Storage
– Versatility(Programmable)
5
Classification of computer
Based on their size and capacity
• Microcomputer: is a single user, compact and its memory
capacity is also low compare with others.
Palmtop, laptop, desktop
• Minicomputer: this kind of computer is multi-user .the
capacity of this computer is greater than Microcomputer.
Also known as mid-range computers,
• Mainframe computer: it is large computer and big
institution or organization has this type of computer.
• Supercomputer: very giant computer(They can occupy
anything from a few feet to hundreds of feet) and is found
only in few institution all over the world like NASA. Super
6
computer process vast amount of information.
Computer System

Computer system means the composition of


computer
Computer system components are classified as
hardware and software.
Hardware:- The physical equipment that goes
together to make up a computer
Software:- The set of instructions called a program
that directs the computer.

7
Architecture of a Computer

Von Neumann Architecture


• In 1946, Mathematician John Von Neumann
proposed that programs could be stored in memory,
the same way as data.
– Both can be represented by binary codes
• This “Stored program” concept is the
basis of all modern computers.

8
Architecture…

Von Neumann architecture - characteristics


• One processor
• Use of stored programs
• Sequential processing of instructions
• Single Instruction, Single Data stream (SISD)
mode : single uni-core processor executes a
single instruction stream, to operate on data
stored in a single memory.

9
Basic Computer Hardware
Components
Five logical units in every computer:
1.Central Processing Unit (CPU)
2.Memory
3.Bus
4.Input / Output Interfaces
5.Peripheral devices

10
Basic Computer Components

11
CPU( Central Processing Unit )
CPU is the part of the computer that performs the bulk of the
data processing operations. Its main function is to execute
programs stored in the main memory by fetching the
instructions, examining them and executing them

12
Parts of CPU
Parts of CPU (3 parts)
1. Control Unit ( CU )
• it fetches, decodes and executes instructions
• it issues control signals that
control hardware components within the CPU
• it transfers data and instructions around the
system
2. Arithmetic and Logical Unit (ALU)
Performs operations such as
– subtraction, addition, (arithmetic)
– comparison (logical)
13
Parts of CPU
3. Registers
Very high speed memory units in the CPU used to store
address of instruction , data and the result of operation

Examples
• Program Counter (PC) – Points to the address of the next
instruction to be executed
• Instruction Register (IR) – Holds the instruction currently
14
being executed
Parts of CPU…
• Memory Address Register (MAR) – Stores the physical
memory address where the next piece of data will be written
or read from
• Memory Buffer Register (MBR) – Holds the contents of the
location that has been read or that is to be written
• Accumulator (A) – A Processor register which serves as both
the input and output for lots of operations. It basically stores
the intermediate results of most of the operations.

15
Memory
Memory refers to a place to store programs and data.
Categories:
• Primary Memory
• Secondary Memory
• Internal Memory

16
Primary Memory
Primary Memory:
Implemented in high speed devices located outside CPU, Costly
There are basically two sorts
• RAM - Random Access Memory
– general purpose memory
– can be used for storing currently running program and data
– Can be written to or read from
– Volatile
• ROM - Read Only Memory
– used to contain permanent data or instructions
– Replaces hardwiring(firmware)
– Non volatile
– In a PC it contains BIOS (basic
input/output systems) which contains POST (power on self test),
bootstrap loader, and BIOS drivers
17
Secondary Memory
Secondary Memory:
• Low speed memory(internal or external)
• Non-volatile
• Holds data and program not currently being executed
• Holds large data
• Less expensive
Examples Magnetic Disk, Tape, Optical Disc

18
Internal Memory
Internal Memory:
• Implemented in very high-speed devices located near
or within CPU
• Holds currently execution instructions and few data
related items
• Very expensive
• Examples: Registers, Cache

19
Memory Hierarchy

20
Buses
Buses are Parallel wires (a set of wires) which act as
a data highway for moving binary information around the
computer
•Carries instructions, data, addresses or commands
•Unidirectional or bi-directional
Three major categories
1. Address bus carries memory addresses from cpu to other
components such as RAM or input/output devices.
2. data bus used to carry data
3. control bus - carry control signals between the CPU
(central processing unit) and other devices. Carries
commands from the CPU and returns status signals from
the devices. 21
I/O Interfaces
I/O Interfaces are devices that interfaces the system to the
outside world.

22
A peripheral device
A peripheral device is typically a device that is external
to a computer and connected either wirelessly or via a
cable, although some are internal to the digital system
There are three different types of peripherals:
1. Input, used to interact with, or send data to the
computer (mouse, keyboards, etc.)
2. Output, which provides output to the user from the
computer (monitors, printers, etc.)
3. Storage, which stores data processed by the
computer (hard drives, flash drives, etc.)

23
Programming and Problem
Solving

24
Which side you are?

World
Problem, Solution and Problem Solving

A problem is the state of situation that needs to be


resolved. I t is something that we are not happy or
satisfied about it.
A solution is idea or artifact that removes the
problematic situation.
Problem solving is a process to derive a
solution to a problem.
Programming - Concepts

Algorithm: is a sequence of logical steps expressed informally


that solves a given problem.

A program is a list of formal instruction that the computer


must follow in order to solve a problem. It is the solution to a
problem.

Programming is a problem-solving activity. It is the art and


science of creating computer solution to a problem(program)

27
Program versus Algorithm

• Program is written in programming language whereas


algorithm is in English like pseudo language or
flowchart.

• When an algorithm is coded using any programming


language (e.g. C++), then it is called a program.

28
Steps of programming

Six steps for solving problem


1. Understand the problem
a) Specify the program objects and program
users
b) Specify output and input requirement
c) Specify processing requirement

29
Steps…

2. Plan it out beforehand (write an algorithm) to


solve the problem
a) Determine program logic through top-down
approach
b) Design details using pseudo code and/or using
flow chart
c) Test design with structure walk through

30
Steps…

3. Implementation (Coding)
Each statement of the algorithm is translated into a
target programming Languages.
a) Select the appropriate programming language.
b) Code the program in that language following the
syntax carefully.
c) Use the programming language.
 Editing: to write the source code.
 Compiling: to convert source code into object code.
 Linker(Linking): convert object file into executable file.
 Loader(Running): to load the program into RAM for
execution.
31
Steps…

4. Program Testing
a) Check the program to discover errors
b) Run the program and debug it.
c) Run the program with real-world data.

32
Steps…

5. Documentation
To aid the maintenance of a program during its life
time.
Documentation may include: A problem statement, a
description of the system, i.e., program functions and
system specifications, a description of the program
that involves program flowcharts, program listing, test
data and result, and Instructions for installing and
running the program.

33
Steps…

6. Maintenance
Modify the program to meet changing requirements or
to correct any errors that show up while using it.

34
Algorithm

An algorithm is defined as a well-ordered collection


of unambiguous and effectively computable
operations, that when executed, produces a result
and halts in a finite amount of time.

35
Basic Steps in Writing Algorithm

1. Define the problem: State the problem you are


trying to solve in clear and concise terms.
2. Analyze the problem to identify the inputs, the
outputs and the process that convert the input to
the output
3. Describe the steps needed to convert or
manipulate the inputs to produce the
outputs(Write the algorithm)
4. Test the algorithm: choose data sets and verify
that your algorithm works!
36
Basic Algorithm Constructs

All algorithm are constructed using three control


structure or construct. These are:-
Sequence structure is the construct where one
statement is executed after another
Selection structure is the construct where statements
can executed or skipped depending on whether a
condition evaluates to TRUE or FALSE
Repetition structure is the construct where
statements can be executed repeatedly until a
condition evaluates to TRUE or FALSE
37
Algorithm languages

There are two well known language that are used to


describe algorithm: Pseudocode and Flowchart

38
Pseudocode

Pseudocode consists of natural language-like


statements that precisely describe the steps of an
algorithm or program
• Statements describe actions
• Focuses on the logic of the algorithm or program
• Avoids language-specific elements
• Written at a level so that the desired
programming code can be generated almost
automatically from each statement
39
Pseudocode Language Constructs

1. Input/output
Input: GET var1, var2, … or READ var1, var2
Output: DISPLAY var1, var2, … or PRINT var1,
var2

2. Computation/Assignment
Compute var1 as Sum of X and Y or var1 X + y
ASSIGN X to Y or Y X
INCREMENT counter or counter counter + 1
DECREMENT counter or counter counter -1
40
Pseudocod Language…

3. Selection
a. Single-Selection IF
IF condition THEN
statement 1
statement2
etc
END IF
Statements 1, statement2, etc are executed if the
condition is evaluated true otherwise they are
skipped
41
Pseudocod Language…

b. Two-Way-Selection IF
IF condition THEN
statement 1
statement2
etc
ELSE
statement 1
statement2
etc

END IF
Statement 1, statement2, etc under the if are executed if
the condition is evaluated true otherwise Statement1,
statement2, etc under the else is executed
42
Pseudocod Language…
Multiple-Selection IF
IF condition THEN The first condition is evaluated. If it is true, the
statement 1
statement2 statements under that condition are executed
etc otherwise these statements are skipped and the
ELSE IF condition THEN second condition is evaluated and if it is true ,
statement 1
statement2 the statements under that condition will be
etc executed otherwise these statements are
….
skipped and so on. If none of the condition is
ELSE evaluated to true the statements under the
statement 1 “ELSE” will be executed. Only the statements
statement2
etc under one of the condition or under the ELSE
END IF will be executed.
. The ELSE IF and ELSE part is optional.

43
Pseudocod…

d. Multiple-Selection Switch
SWITCH expression TO Expression is evaluated. Depending on the
case 1: value of the expression, the control is
statement1 transferred to one of the cases or the default
statement2 case. If the value is 1, the statements under the
etc label case 1 will be executed. If it is 2, the
case 2 :
statement1 statements under case 2 will be executed and so
statement2 on. If the expression matches to none of the
etc cases, the statements under default will be
…. executed. Only the statements under one of the
default: cases or the default are executed.
statement1 The expression value and the case numbers
statement2 must be integers.
etc The default case is optional
END SWITCH
44
Pseudocod…

4. Repetition
a. While Structure
while condition is true, then do subordinate statements.
WHILE condition
statement 1
statement 2
etc.
END WHILE

45
Pseudocod…

b. Do-While Structure
DO – WHILE structure (like WHILE, but tests condition at
the end of the loop. Thus, statements in the structure will
always be executed at least once.)
DO
statement 1
statement 2
etc.
WHILE condition

46
Pseudocod…

c. FOR Loop Structure


FOR structure (a specialized version of WHILE for repeating
execution of statements a specific number of times)
FOR counter -> i TO n STEP k
statement 1
statement 2
etc.
END FOR
The statements under the for loop will be executed for every
iteration of the counter variable starting from initial value i to
n every time the counter value incremented by k (the step
value).
47
Pseudocode Example1 (Sequence)

Write an algorithm that calculates and display the area and


perimeter of a rectangle. The width and the length given by
the user.

48
Pseudocode Example2 (Selection)

Write an algorithm that determining the monthly income


of a salesperson by using the following commission
schedule:the
Monthly Sales user, Income
Greater than or equal to $50,000 $375 plus 16% of sales
Less than $50,000 but greater than or equal to $40,000 $350 plus 14% of sales
Less than $40,000 but greater than or equal to $30,000 $325 plus 12% of sales
Less than $30,000 but greater than or equal to $20,000 $300 plus 9% of sales
Less than $20,000 but greater than or equal to $10,000 $250 plus 5% of sales
Less than $10,000 $200 plus 3% of sales

49
Pseudocode Example 4 (Repetition)

Write an algorithm that calculates class average of n students


for math's score where n is supplied by the user.

50
Pseudocode Example5 (Repetition)

Repeat the previous problem where the number of student is


not known in advance. Assume an entry less than zero for
score signifies end of entry for score(sentinel value)

51
Pseudocode Example 6

1. It has been decided that a bonus of 12% of gross salary is to be given for each
employee in an organization. It was also agreed that if an employee has
worked for more than 13 years she/he is to receive an additional amount of
Birr 350.00. Write an algorithm that calculate and display the bonus and the
net salary.
2. Write an algorithm that chooses a random number between 1 and 20 and allow
the user to guess the number. The user is allowed only five trials. The algo
should display guess result (success or failure) and the number of trial.

52
Pseudocode Example 7

Write an algorithm that determines the square root of a


number

53
Flowchart
Flowchart is a graphical tool that diagrammatically depicts
the steps and structure of an algorithm. Most commonly used
symbol are listed below
Symbol Name/meaning Symbol Name/meaning

Process – Any type of internal Connector – connects sections


operation: data transformation, of the flowchart, so that the
data movement, logic operation, diagram can maintain a smooth,
etc linear flow
Input/Output – input or output Terminal – indicates start or end
of data of the program or algorithm

Decision – evaluates a condition Flow lines – arrows that indicate


or statement and branches the direction of the progression
depending on whether the of he program
evaluation is true or false
54
Flowchart…

General rules for flowcharts


• All symbols of the flowchart are connected by flow lines
(note arrows, not lines)
• Flowlines enter the top of the symbol and exit out the
bottom, except for the decision symbol, which can have
flow lines exiting from the bottom or the sides
• Flowcharts are drawn so flow generally goes from top to
bottom
• The beginning and the end of the flowchart is indicated
using the Terminal symbol

55
Flowchart…

Sequence

.
.
.

56
Flowchart…

SELECTION
SINGLE SELECTION IF

57
Flowchart…

TWO WAY SELECTION IF

58
Flowchart…

Multi Way Selection IF OR T

Switch F

59
Flowchart…

REPITITION
WHILE OR FOR STRUCTURE

60
Flowchart…

REPITITION
DO - WHILE STRUCTURE
s

61
Flowchart Example

Write an algorithm using flowchart for Example 1-7

62
Programming Languages
and its Evolution

63
Programming Languages and its
Classification

A Computer Programming language is a set of rules that tells the


computer what operations to do. It is a tool used by a programmer
to write a computer program.
E.g. BASIC, FORTRAN, COBOL, PASCAL, C, C++, Java,
VISUAL BASIC.
Programming has gone through an evolution, which is derived by
the need to make program writing and maintenance simpler.
There are three major levels, or types of programming languages:
1. Machine Language
2. Assembly Language
3. High Level Languages

64
Machine Language

• The first programming language.


• Consists of string of 0’s and 1’s.
• The one that CPU directly understand
Advantage
⁻ the fastest type of computer program
Disadvantage
⁻ Much closer to the machine so that you need to know the
architecture of the machine.
⁻ Very Difficult to learn, write, debug and maintain
⁻ Prone to error
⁻ Machine Dependent
65
Assembly Language
Assembly language is a symbolic representation of machine
language, in that each machine language instruction is
represented by a symbol or abbreviation in assembly
language.
A program written in assembly language should be translated
to machine language by a translator known as Assembler
before it is executed by the machine.
Machine language and assembly language together are called
Low Level Language
Assembly language instructions Machine language
instructions
MOV A, 47 1010 1111
ADD A, 26 01101011 00011010
66
Assembly…

Advantage
⁻ Relatively simplifies the task of program
writing because programmers can easily
remember symbols
Disadvantage
⁻ still difficult to remember all symbols and
abbreviations of assembly languages.
⁻ Prone to error

67
High Level Language
High Level Language
Close to human language, using familiar notations and
words
Assembly language instructions High Level
language instructions
MOV A, 47 A = 47;
ADD A, B A = A + B;
A human readable program statements written in high
level language or assembly language that are not directly
readable by the machine is commonly referred as source
code.
The source code should be translated to machine code (or
called object code) by a translator program to be executed
by the machine.
68
Translators

There are two types of translator:


1. Interpreter- is a program that converts each high-level
language statement into machine language, when needed to
be executed immediately, statement by statement.
2. Compiler: is a program that converts the entire program
(source code) of a high level language into machine code
before the computer executes the program.

Compiler or
Source Code Object Code
Assembler

69
Interpreter …
Using Compiler:

Object Code
Source Code Compiler

Execute Program
Using Interpreter:

Execute a line
Source Code Interpreter
of Program

70
High Level Language

Note:
• Programs written in machine languages are the fastest
programs
• High level programming languages can be translated in to
machine language using compilers or interpreters.
• Those high level languages which use compilers, such as
C, C++ etc,are called compiled languages. Those that use
interpreters, such as Java, are called Interpreted
languages.
• Compiled languages are generally faster and takes less
memory than interpreted languages
71
Introduction to C++

72
Origin of C++

C is a programming language developed by Dennis Ritchie of


AT&T Bell Laboratories in 1970's alongside the UNIX
operating system. It evolved from two other programming
languages, BCPL and B
• C provides a comprehensive set of features for handling a
wide variety of applications, such as systems
development and scientific computation.
• C++ is an “extension” of the C language, in that most C
programs are also C++ programs.
• C++, as opposed to C, supports “object-oriented
programming.”
• Both C & C++ are compiled languages.
73
Phases of Program Development in
C++
Programs typically go through six phases to be executed. These are:-
1. Edit: - in this phase a program is created using a text editor. (e.g.
Turbo C++ editor, notepad, DOS-Editor, etc). The result of the
edit phase is a collection of text files containing C++ source code.
C++ source files usually have a ".cpp" or ".cc" extension.
2. Preprocess: - the preprocess, compile and link phases are usually
done together, with the preprocessor running first, the compiler
next and the linker. The role of the preprocessor is to transform
the source file into an equivalent file by performing the
preprocessing instructions contained by it. These instructions
facilitate a number of features, such as:
• file inclusion
• conditional compilation
• macro substitution
• Removal of comment, and unnecessary spaces and newline
character 74
Phases…
3. Compile: - the compiler translates the C++ source code into
machine (or object) code that the computer can execute. The
type of machine code depends on the type of computer. The
result of the compile phase is a binary file containing machine
code. Object files usually have a ".o" or ".obj“
ending/extension. While object file contain machine code, they
do not contain a complete program, so they cannot be executed
by themselves.
4. Link: A linker combines the object files into a single
executable file that the computer can run. The linker may also
extract object code from libraries. Libraries are files containing
the object code of commonly used functions. The executable
file contains machine code. Executable files in a MS-DOS or
Microsoft Windows system have a ".com" or ".exe" ending.
75
Phases…
5. Load:- A loader program loads the executable file from the disk into
memory so that it can be run by the CPU
6. Execute:- Each instruction of the machine code are fetched from the
RAM one by one in to the CPU and executed by the processor.
C++ Program

Editor Step1

Preprocessor Step2
Syntax
Compiler Step3
Error
Library
Linker Step4

Loader Step5

Execution Step6
76
Program Errors
A mistake in a program is usually called a bug, and the process of
eliminating bugs is called debugging.
There are three kinds of program errors:
1. Syntax Errors: Violation of syntactic rules in a Programming
Language generates syntax errors.
Effect? Interpreter or Compiler finds it in Syntax Check Phase.
Program doesn't compile until all syntax errors are removed
2. Semantic or logical Errors: Doing logical mistakes causes semantic
errors in Source code. - this error occurs when we ask the computer to
do something, but mean for it to do something else.
Effect? Interpreters and Compilers can not notice them, but on
execution, they causes unexpected results.
3. Run-time Errors: Occur on program execution. Mostly caused by
invalid data entry or tries to use not existing resources or occurs
when we ask the computer to do something it can’t do.
Effect? It occurs on run time and may crash the program execution
77

You might also like