Programming I
Programming I
Chapter One
Introduction and Programming Basics
I. Basics of computers
Computer is an electronic device, operating under the control of instructions called programs
.It is a device which can accept data, manipulate the data according to specified rules, produce
information from the processing, and store the results for future use.
Characteristics of computers
Speed: - computers can calculate at very high speed. Their speed is measured in
milliseconds, microseconds, nanoseconds
Accuracy: errors in computing (data processing) is mostly due to human factor
Storage:-can store large amount of data
Versatility: can be programmed and applied for different purposes
Diligence:-can handle very routine and repetitive tasks
. [AASTU] Page 1
Introduction To Computer And Programming
Computer is in general does is it takes an input in various forms, it process the input
according to a given set of instructions and produces an output in various forms.
The different hardware parts of a computer which are responsible for this operation are
illustrated by the following diagram
….
. [AASTU] Page 2
Introduction To Computer And Programming
- Its primary function is to select and interpret instructions and to send appropriate
signals to other units in the computer . i.e. CU does not execute instructions rather it
directs to other units .
Registers
. [AASTU] Page 3
Introduction To Computer And Programming
- they are memories , when an instruction loaded from memory it is placed first in the
register, to wait signal from the control unit and data also placed in register prior to execution
in the ALU .
Storage Devices
Storage Devices: there are two types of storages primary/main storage (memories) and
secondary/Auxiliary storages (memory)
Primary storages are of two types RAM and ROM
ROM
- it referred to read only memory
- it provides permanent storage
- ROM in a PC contains a basic set of instructions, called the basic input output system
(BIOS). the PC uses the BIOS to start up the OS
- data can be read from ROM , but can’t be written on ROM
Note nowadays there is erasable ROM like EPROM (Erasable programmable ROM)
. [AASTU] Page 4
Introduction To Computer And Programming
- are normally used to store information that are the computer the computer may need
frequently for its own operations
Secondary Storage (Auxiliary storages)
Since RAM is expensive and volatile it is not possible to store data permanently, hence we
need other storage devices secondary storages.
There are two types of secondary storages magnetic storage and optical storage.
Magnetic drum
- it is a metallic cylinder ranging from few inches to a few feet s coated with a
special magnetic alloy
- data is recorded as magnetic spots arranged in binary form
- data is recorded by read /write head and one for each truck
- magnetic drum provides random access for selecting a truck but once the truck is identified
, the information is recorded sequentially
Magnetic
disks Hard
. [AASTU] Page 5
Introduction To Computer And Programming
Disk
. [AASTU] Page 6
Introduction To Computer And Programming
Optical storage
Optical storage devices use the principle of light rather than magnetism to store information
CD-ROM (Compact Disk Read Only Memory)
- it is optical storage media
- it is possible to read from the disk but you can’t write onto it
- is a rigid plastic disk that store s a large amount of data through the use of laser
optic technology
- since CD-ROM store data optically ,they have much higher memory capacity than
disks that store data magnetically
- its underside is coated with a very thin layer of aluminum that reflects light
. [AASTU] Page 7
Introduction To Computer And Programming
- data is written to the CD-ROM is by burning microscopic pits into the reflective surface of
the disk with powerful laser
DVD -ROMs (digital video disc-ROM)
- is a very high capacity compact disk
- is used to store large amount of data even videos
Input devices
Input devices are
- Parts of the computer hardware that are used to convert data or information into
electronic machine readable form
- used to gather data for the microprocessor so that it can be
processed Examples of input devices
Keyboard, mouse, image scanner, disk drives, microphone etc.
1. Keyboard
- is an input device with buttons or keys that the user presses to enter data characters
and commands into a computer
- is most widely used input device
Keyboard contain the letters of the alphabet, numbers and frequently used symbols like
$,%,& etc..
The size of the keyboard depends on the number of keys that are included in the keyboard
The normal PC keyboard includes 105 keys .These keys can be divided in to five sections
1. Typing keys:- These keys work just like conventional type writer. These keys
include Alphabet A-Z, digits 0-9, the Enter key, Space, the Back space, the Shift key
etc
2. Numeric keypad
Is used to enter numeric data more easily when you are working number intensive tasks.
Num lock is used to switch the light of numeric keypad to use the pad.
3. Function keys
. [AASTU] Page 8
Introduction To Computer And Programming
There are 12 function keys labeled F1 to F12 arranged at the top. when any of the keys is
pressed, it performs a certain task. For instance, in many programs F1 is pressed to display
help information.
4. Navigation keys
These are keys that are used to navigate (move) through your document.
5. Computer keys
These are not found on typewriter.
They are performs different tasks when used alone or in conjunction with other keys.
Example: Esc, Alt, Ctrl, print screen Insert etc
2. Mouse
- is the pointing device that is used to move the insertion point around the screen.
- is an inverted trackball device that has a number of selection buttons associated with it
- the hand moves it across a flat surface , and its position is displayed on the screen
- the buttons are used to select items and make choices on the screen
3. Image scanner
Is used to input images and words directly into a computer using a visible light or
electromagnetic radiation like laser. Is image processing device.
Image processing is an activity of converting visual information into a format that can be
managed with in a computer system.
There are two types of scanners flatbed scanner and handheld scanner
Flat scanner: - which is similar to an office photocopier
A hand held scanner, is a scanner passed manually across the image to be processed.
4. Disk drives
Disk drives are devices that input data from the storage devices for further processing
Examples hard disk drives and floppy disk drives
5. Microphone
. [AASTU] Page 9
Introduction To Computer And Programming
Microphone converts sound into signals that can be stored, manipulated and played by the
computer.
is used to gather information to the computer when the computer is a multimedia system .a
computer is said to be a multimedia system if it processes multiple types of information ( such as
text , images and voices ) simultaneously.
Output devices
Out put hardware consists of external devices that used to get information (data) out of a
computer’s CPU to the computer user so that it can be examined, analyzed, or distributed to
others
These are devices that are used to display the processed information to the user either in Soft
copy of hardcopy
- Soft copy: is temporary output such as that produced by a monitor (unprinted copy
/ document)
- Hard copy: permanent output such as that produced by a printer (printed copy / document )
- Outputs convert the result of processing to a form that is easy to understand by
human beings.
Monitor (screen)
- Converts information gathered by then computer into visual information.
- It looks like a television screen
- Is the most widely used output device
- It displays the output of the processing activity for the user
- The monitor (screen) attached to the computer gives the user feedback while the user types
a character from the keyboard
- It is used to display both text and graphics data
LCD projector
. [AASTU] Page
10
Introduction To Computer And Programming
LCD projector is an output device used for displaying the output of the computer into a large
screen, mostly used in conferences and class room for presentations.
Printer
- Printer produces a permanent hardcopy output from the computer by converting
digital information into marks on a paper
A printer allows the user to print out on paper a copy of the screen or the data that is being
processed by the computer
- Printers are available in both color and black and white. color printers are slower and
more expensive than black and white printers
- Printers can be categorized into impact and non impact
Impact printers
Impact printers are printers which are physically strike the paper. i.e. the paper and the
characters being printed come in contact with one another .
Impact printers has hammering parts, hence printing is noisy.
Examples of impact printers are Dot matrix, line and character printers
Dot matrix printer: is most common and versatile. The character it prints consists of dots
arranged in a pattern. It is possible to print graphics images and variety of type styles.
Wire rods pushed against a ribbon and paper form the characters.
The quality of output from a dot matrix printer depends largely on the number of dots in
the matrix .dot matrix printers are low cost and they are also simple to use.
Non-impact printers
These printers do not physically strike papers. One advantage of these printers is that it
can print higher quality text and graphics than impact printers. Here the characters of the
print material are produced on the paper through a heat, chemical or spraying process
Examples are laser printers and ink jet printers
Laser printers
Laser printers are the best, the most expensive and versatile printer’s .laser printers are
very fast in printing and the quality of the print is also very good .laser printers work similarly to
a copying machine by converting data from the computer into a beam of light is focused on a
photoconductor drum, forming the images to be printed. The photoconductor attracts particles of
toner that are fused by heat and pressure onto paper to produce an image. The laser printer prints
. [AASTU] Page
11
Introduction To Computer And Programming
an entire page at a time. Hence the speed of laser printer is measured in terms of the number of
pages that it can print per minute.
Inkjet printers
These printers spray tiny streams of ink from holes in the print mechanism onto the paper.
These printers are highly used to print graphs and charts.
Plotters
These devices are similar to printers, but are generally vector based in the way they drew lines
and information on the paper. Plotters draw images information, such as charts and graphs, line
drawings, and blue prints of buildings. Plotters are able to produce every line that drawers use as
if they are drawing by hand. They also produce shadows and patterns. There are two types of
plotter, one where the paper moves, and the other where the paper is stationary.
When you choose printers consider the paper size the printer uses, whether it is automatic feed (to
print several pages continuously), fonts and the print quality.
Computer software
Software
- is the invisible part of the computer system
- is collection of programs and routines that the computer needs to perform a task
- is a serious of instructions that tells the hardware what to do
- Usually software also includes documentation, rules and operational procedures.
Software is in general classified into two system software and application software
System software
- General purpose SW that is used to facilitate the utilization of the hardware.
- consists of instructions or programs that are used to manage the hardware resources of
a computer and perform required information processing tasks
- it provides the interface between the hardware and the user
System software includes operating systems and system development (language software)
. [AASTU] Page
12
Introduction To Computer And Programming
Human to computer
Knowledge transfer from human to human is much simpler than
knowledge transfer from human to computer. Why?
o All humans have the same internal working mechanism
o All humans have the ability to think
Programming: is the system of transferring human knowledge from
human to computers.
Programmer: is the one who can transfer knowledge from human to
computers.
Program: is a human knowledge represented in computer
understandable format. Or in professional meaning, a program is a list
of instruction that the computer must follow in order to process data
into information.
What kinds of knowledge can be transferred from human to computer?
Answer: A knowledge that can be expressed algorithmically.
How can this knowledge be transferred?
Answer: Using problem solving steps.
Algorithm: is a sequence of logical steps expressed informally that can
accomplish a given task.
A Program: is a sequence of logical steps expressed formally that can
accomplish a given task.
Example:
1. Given the following list, develop an algorithm that finds the smallest
number.
4 3 -1 6 -4 7
. [AASTU] Page
13
Introduction To Computer And Programming
7 2 -1 8 10 8 Sn=11
Compare the search key with the element of the list one by one
starting from first element until a match is found or the list is
exhausted.
Expressing Algorithm
There are two ways by which you can express or describe your algorithm.
A. Using Pseudo code
An algorithm is a procedure for solving a problem in terms of the actions to
be executed and the order in which those actions are to be executed. An
algorithm is merely the sequence of steps taken to solve a problem. The
steps are normally "sequence," "selection,” "iteration," and a case-type
statement.
. [AASTU] Page
14
Introduction To Computer And Programming
Do nothing
End Do
. [AASTU] Page
15
Introduction To Computer And Programming
Display min
Stop
2. the program computes the sum, average and product of three numbers:
Read X, Y, Z
Compute Sum (S) as X + Y + Z
Compute Average (A) as S / 3
Compute Product (P) as X * Y * Z
Write (Display) the Sum, Average and Product
3. a program that reads two numbers and displays the numbers read in decreasing order:
Read A, B
If A is less than B
BIG = B
SMALL = A
else
BIG = A
SMALL = B
Write (Display) BIG, SMALL
4. A program that calculate the average of 10 numbers:
set average to zero
set count to zero
set total to zero
read number
while ( not end-of-data )
increment count by 1
total = total + number
read number
if ( count > 0 ) then
average = total / count
display average
B. Using Flowchart
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very
helpful in writing program and explaining program to others. Symbols Used In
Flowchart Different symbols are used for different states in flowchart, For
example: Input/output and decision making has different symbols.
Represent an algorithm graphically.
. [AASTU] Page
16
Introduction To Computer And Programming
Examples:
. [AASTU] Page
17
Introduction To Computer And Programming
2. Draw flowchart to find the largest among three different numbers entered by user.
. [AASTU] Page
18
Introduction To Computer And Programming
. [AASTU] Page
19
Introduction To Computer And Programming
. [AASTU] Page
20
Introduction To Computer And Programming
. [AASTU] Page
21
Introduction To Computer And Programming
. [AASTU] Page
22
Introduction To Computer And Programming
Though, flowchart is useful in efficient coding, debugging and analysis of a program, drawing
flowchart in very complicated in case of complex programs and often ignored.
. [AASTU] Page
23
Introduction To Computer And Programming
Note
:
Machine language and assembly languages are called low
level programming language.
The computer (CPU) can understand directly or with little
translator, so that they are very fast.
They require less resource (Memory).
You can get the power of the machine.
Disadvantages:
Much closer to the machine so that you need to know the architecture of
the machine.
. [AASTU] Page
24
Introduction To Computer And Programming
Note:
These are some basic things to apply
. [AASTU] Page
25
Introduction To Computer And Programming
. [AASTU] Page
26
Introduction To Computer And Programming
4. Program Testing
Check the program to discover errors
Run the program and debug it.
Run the program with real-world data.
Errors
1. Syntax Error (Compile-time error): it occurs when you violate the
syntax.
And it is called Compiler complaints because it is detected by the
compiler.
5. Documentation
All your works at different stages has to be documented.
Documentation is necessary for
o The program
o The other user
o The user
6. Maintenance
After delivering the program to the end user, different things
might happened
a. Error might be discovered
b. User need(Requirements) might be changed
2.Introduction to C++
Structure of a Program
Probably the best way to start learning a programming language is by writing
a program. Therefore, here is our first program:
// my first program in C++ Hello World!
#include<iostream.h>
#include<conio.h>
void main ()
{
cout<<"Hello World! \n ";
getch();
}
// my first program in C++
This is a comment line. All lines beginning with two slash signs ( //) are
considered comments and do not have any effect on the behavior of
the program.
Lines beginning with a pound sign (#) are directives for the
preprocessor. They are not regular code lines with expressions but
indications for the compiler's preprocessor. In this case the directive
#include<iostream.h> and #include<conio.h> tells the preprocessor to
include the iostream and conio standard file. Iostream.h is a standard
C++ header file and contains definitions for input and output.
void main ()
getch()
getch is a code that wait until the user enters any character from
keyboard so here we can see the output on the screen until any character
entered.
Notice that the statement ends with a semicolon character ( ;). This
character is used to mark the end of the statement and in fact it must
be included at the end of all expression statements in all C++
programs
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to insert
notes or descriptions embedded within the source code.
Kassahun T. Page
[AASTU] 30
Introduction To Computer And Programming
// line comment
/* block comment */
1 #include <iostream.h>
2 /* This program calculates the weekly gross pay for a worker,
3 based on the total number of hours worked and the hourly
4 pay rate. */
Comment
5 int main (void)
6 {
7 int workdays = 5; // Number of work days per week
8 float work Hours = 7.5; // Number of work hours per
9 day float pay Rate = 33.50; //
10 Hourly pay rate
11 float weekly Pay; // Gross weekly
12 pay weekly Pay = workdays * work Hours * pay
13 Rate; cout<< "Weekly Pay = " <<weekly Pay<<
'\n';
}
#include<iostream.h>
#include<conio.h>
int main ()
{
cout<<"Hello World! "; // prints Hello
World!
cout<<"I'm a C++ program"; // prints I'm a
C++ program
getch();
}
Memory
1 1 0 1 0 0 0 1
Bit
The C++ compiler generates executable code which maps data entities to
memory locations. For example, the variable definition
int salary = 65000;
Causes the compiler to allocate a few bytes to represent salary. The exact
number of bytes allocated and the method used for the binary representation
of the integer depends on the specific C++ implementation, but let us say
two bytes encoded as a 2’s complement integer. The compiler uses the
address of the first byte at which salary is allocated to refer to it. The above
assignment causes the value 65000 to be stored as a 2’s complement integer
in the two bytes allocated (see Figure below).
Variables
Compilers have to replace variables' symbolic names with the actual locations
of the data. While a variable's name, type, and location often remain fixed,
the data stored in the location may be changed during program execution.
Each variable needs an identifier that distinguishes it from the others, for
example, in the previous code the variable identifiers were a, b and result,
but we could have called the variables any names we wanted to invent, as
long as they were valid identifiers.
Identifiers
An identifier is a name that identifies (that is, labels the identity of) either a
unique object or a unique class of objects, where the "object" or class may be
an idea, physical [countable] object (or class thereof), or physical
[noncountable] substance (or class thereof). The abbreviation ID often refers
Another rule that you have to consider when inventing your own identifiers is
that they cannot match any keyword of the C++ language nor your
compiler's specific ones, which are reserved keywords. The standard
reserved keywords are:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue,
default, delete, do, double, dynamic_cast, else, enum, explicit, export,
extern, false, float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct,
switch, template, this, throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t, while
Next you have a summary of the basic fundamental data types in C++, as
well as the range of values that can be represented with each one:
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
Declaration of variables
int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable
of type int with the identifier a. The second one declares a variable of type
float with the identifier mynumber. Once declared, the variables a and mynumber
can be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can
declare all of them in a single statement by separating their identifiers with
[Type here] [Type here] [Type here]
Introduction To Computer And Programming
int a, b, c;
To see what variable declarations look like in action within a program, we are
going to see the C++ code of the example about your mental memory
proposed at the beginning of this section:
#include<iostream.h>
#include<conio.h>
void main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Scope of variables
Global variables can be referred from anywhere in the code, even inside
functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they are
declared.
Initialization of variables
int a = 10;
Constants
In computer programming, a constant is an identifier whose associated value
cannot typically be altered by the program during its execution (though in
some cases this can be circumvented, e.g. using self-modifying code). Many
programming languages make an explicit syntactic distinction between
constant and variable symbols.
With the const prefix you can declare constants with a specific type in the
same way as you would do with a variable:
Here, pathwidth and tabulator are two typed constants. They are treated just
like regular variables except that their values cannot be modified after their
definition.
Exercises
variable
object.oriented
Operators
Assignment (=)
a = b;
For example, let us have a look at the following code - I have included the
evolution of the content stored in the variables as comments:
a = b = c = 5;
+ addition
- subtraction
* multiplication
/ division
% modulo
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing
11 between 3.
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
Shortening even more some expressions, the increase operator (++) and the
decrease operator (--) increase or reduce by one the value stored in a
variable. They are equivalent to +=1 and to -=1, respectively. Thus:
c++;
c+=1;
c=c+1;
are all equivalent in its functionality: the three of them increase by one the
value of c.
Example 1 Example 2
[AASTU] Page
49
Introduction To Computer And Programming
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4
int k = 5;
Relational and equality operators ( ==, !=, >, <, >=, <= )
== Equal to
!= Not equal to
[AASTU] Page
50
Introduction To Computer And Programming
[AASTU] Page
51
Introduction To Computer And Programming
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use any valid
expression, including variables. Suppose that a=2, b=3 and c=6,
[AASTU] Page
52
Introduction To Computer And Programming
The Operator ! is the C++ operator to perform the Boolean operation NOT, it
has only one operand, located at its right, and the only thing that it does is to
inverse the value of it, producing false if its operand is true and true if its
operand is false. Basically, it returns the opposite Boolean value of evaluating
its operand. For example:
The logical operators && and || are used when evaluating two expressions to
obtain a single relational result. The operator && corresponds with Boolean
logical operation AND. This operation results true if both its two operands are
true, and false otherwise. The following panel shows the result of operator &&
evaluating the expression a && b:
&& OPERATOR
a b a && b
true true true
true false false
false true false
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
For example:
Conditional operator ( ? )
// conditional operator 7
#include<iostream.h>
#include<conio.h>
void main ()
{
Inta,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
If condition is true the expression will return result1, if it is not it will return
result2.
cout<< c;
getch();
}
In this example a was 2 and b was 7, so the expression being evaluated (a>b)
was not true, thus the first valuespecified after the question mark was
discarded in favor of the second value (the one after the colon) which was b,
with a value of 7.
Basic Input/output
By default, the standard output of a program is the screen, and the C++
stream object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as <<
(two "less than" signs).
The << operator inserts the data that follows it into the stream preceding it.
In the examples above it inserted the constant string Output sentence, the
numerical constant 120 and variable x into the standard output stream cout.
Notice that the sentence in the first instruction is enclosed between double
quotes (") because it is a constant string of characters. Whenever we want to
use constant strings of characters we must enclose them between double
quotes (") so that they can be clearly distinguished from variable names. For
example, these two sentences have very different results:
The insertion operator (<<) may be used more than once in a single
statement:
This last statement would print the message Hello, I am a C++ statement on
the screen. The utility of repeating the insertion operator ( <<) is
demonstrated when we want to print out a combination of variables and
constants or more than one variable:
If we assume the age variable to contain the value 24 and the zipcode
variable to contain 90064 the output of the previous statement would be:
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For
example:
cout<<"First sentence."<<endl;
cout<<"Second sentence."<<endl;
First sentence.
Second sentence.
The standard input device is usually the keyboard. Handling the standard
input in C++ is done by applying the overloaded operator of extraction ( >>)
on the cin stream. The operator must be followed by the variable that will
store the data that is going to be extracted from the stream. For example:
int age;
cin>> age;
The first statement declares a variable of type int called age, and the second
one waits for an input from cin (the keyboard) in order to store it in this
integer variable.
void main ()
{
inti;
cout<<"Please enter an integer
value: ";
cin>>i;
cout<<"The value you entered is
"<<i;
cout<<" and its double is
"<<i*2<<".\n";
getch();
}
You can also use cin to request more than one datum input from the user:
cin>> a >> b;
is equivalent to:
cin>> a;
cin>> b;
In both cases the user must give two data, one for variable a and another
one for variable b that may be separated by any valid blank separator: a
space, a tab character or a newline.
We can use cin to get strings with the extraction operator (>>) as we do with
fundamental data type variables:
cin>>mystring;
However, as it has been said, cin extraction stops reading as soon as if finds
any blank space character, so in this case we will be able to get just one
word for each extraction. This behavior may or may not be what we want; for
example if we want to get a sentence from the user, this extraction operation
would not be useful.
In order to get entire lines, we can use the function getline, which is the
more recommendable way to get user input with cin:
void main ()
{
char mystr[20];
cout<<"What's your name? ";
cin.getline(mystr , 20);
cout<<"Hello "<<mystr<<".\n";
cout<<"What is your favorite
team? ";
cin.getline(mystr , 20);
cout<<"I like "<<mystr<<"
too!\n";
getch();
}
Notice how in both calls to getline we used the same string identifier (mystr).
What the program does in the second call is simply to replace the previous
content by the new one that is introduced.
A value in any of the built-in types we have seen so far can be converted
(type-cast) to any of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is
122 (unsigned short) 3.14 // gives 3 as an unsigned
short
Exercises