You are on page 1of 106

Introduction To Computer And Programming

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
Information and data processing
Data is a collection of raw facts used to generate information.
Hence information can be defined as data that has been transformed into a meaningful and useful
context for specific end users .i.e. It is a refined or processed data.
Data processing is the manipulation of data into a more useful form (information).
Hence to produce information raw data is collected, the collected data is processed, output is
produced and the output is transmitted to concerned users
Data processing has a cycle consists of three parts
Input Process Output
Data processing consists of a number of operations like Recording, duplicating verifying data,
classifying data, sorting, storing, merging, retrieving, calculating data, summarizing and reporting.
Data processing can be performed manually, mechanically, or electrically

II. Computer System


A computer system is composed of the components that are classified either as hardware or
software i.e. it is composed of two components computer hardware and software
Computer hardware

Page 1
Introduction To Computer And Programming

Computer hardware is
- a physical part of a computer
- a part we can see and touch
- composed of a number of electronic and electromechanical parts, which interact with each other
to perform a given task
- the different parts are interrelated by a cable like device called Bus , which is used to facilitate
communication between parts

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

The central processing unit (CPU) (microprocessor)


- it is most expensive and main component of a computer
- it consists of control unit (CU) , arithmetic and logic unit (ALU) and registers
The purpose of the CPU is
- to fetch instruction ( to read instruction from memory
- interpret instructions and determine actions

Page 2
Introduction To Computer And Programming

- fetch data : the execution of instruction may required reading of data from memory or input
devices
- to process data : the execution of instruction may require performing arithmetic or logic
operations on the data .
- write data : the result of execution may require writing a data to memory or output devices

The control unit (CU)


- is also known as the nerve center of the computer system
- it controls , supervises the overall activities of the computer
- monitors the execution of any program processed
- the CU coordinates and controls the activities of different components of the computer system
in the same way that the brain directs the action of human body
- 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
.

The arithmetic and logic unit (ALU)


- it performs Arithmetic operations ( addition , subtraction , multiplication, division) and logical
operation like comparisons .It performs 90% of your computer job.

Registers
- 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

RAM main (primary) memory


- it referred to random access memory
- it is directly accessible by ALU and CU

Page 3
Introduction To Computer And Programming

- it is possible to write a data to and read data from RAM


- it is a working area of a computer
- every location(cell) with in the RAM has unique address
- it holds temporarily the instructions and data elements that are currently being used in a
process
i.e. it is volatile (when the power is off the data erased )
- it is most expensive
- Semi-conductor memories are most widely used form of memories in today’s computers.
Semi conductor memories are memories with faster access time, lower cost, reduced space
and high density, less power consumption than magnetic storage

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)
- 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.

The commonly known magnetic storage devices are


o magnetic drum
o magnetic tape
o magnetic disk hard disk and floppy disk
Magnetic tapes
- is the earliest form of secondary storages
- is a ½ or ¼ inch ribbon of plastic like material coated with a thin layer of iron oxide material
- a device called a tape drive reads and writes data to tape
Page 4
Introduction To Computer And Programming

- it has an advantage of being able to hold enormous amount of data :for this reason it is used to
store information on the largest computer systems
- is sequential access media
- data access time is slow compared to other forms of storage media

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 Disk
- it is a random access media i.e. it permits direct addressing of data location
- consists of one or more metal plates coated with ferric oxide
- the circular platters sealed in a metal box with associated read/ write heads
- a data is recorded in the form of magnetic spot on the platters
a spot presence indicate a 1’s and its absence indicate a 0
- it remains in the system unit it is removed when damaged or when you want to upgrade it with
a larger capacity
- the surface of a magnetic disk is divided into a number invisible concentric circles called truck.
The truck further subdivided into sectors (blocks). each block or sector have a unique address
- it is possible to read or write a block of data at a time
Floppy Disk
- is a portable(removable ) , inexpensive storage medium
- Consists of a thin, circular, flexible plastic disk with a magnetic coating enclosed in a square –
shaped plastic shell, the disk jacket.
- has different sizes 5 ¼ and 3 ½
- use magnetic patterns to store items
- possible to access data and write data on a magnetic disk any number of times
- They must be inserted into a compatible disk drive in order to be read from or written to.
Page 5
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
- 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

Page 6
Introduction To Computer And Programming

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 intens ive tasks. Num
lock is used to switch the light of numeric keypad to use the pad.
3. Function keys
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 ot her 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.
Page 7
Introduction To Computer And Programming

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
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 multi media 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
hard copy
- 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.

- Examples of output devices Monitor (screen), printers, overhead projectors, (LCD), disk drives
,speakers etc..

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

Page 8
Introduction To Computer And Programming

LCD projector
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 an entire page at a time.

Page 9
Introduction To Computer And Programming

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 t hey 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)

Programming (Knowledge Transfer)


Knowledge can be transferred from
Human to human
Human to computer

Page 10
Introduction To Computer And Programming

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

a. Assume the first number is the smallest number.


b. Compare it with the next number and take the smallest.
c. Repeat comparing until the list is exhausted.

Step 1: 4 => Smallest Number


Step 2: 3 => 3<4 ? True: 3=Smallest

Page 11
Introduction To Computer And Programming

Step 3: -1 => -1<3 ? True: -1= Smallest


Step 4: 6 => 6<-1 ? False: No change
Step 5: -4 => -4<-1 ? True: -4=Smallest
Step 6: 7 => 7<-4 ? False: No change

The list is exhausted and we have -4 as smallest number

2. Given following list, develop an algorithm which searches a number in


the list.

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.
Pseudocode is an artificial and informal language that helps programmers
develops algorithms. Pseudocode is a "text-based" detail (algorithmic) design
tool.
The rules of Pseudocode are reasonably straightforward. All statements showing
"dependency" are to be indented. These include while, do, for, if, switch.
Examples below will illustrate this notion.
Pseudo-code is an informal way to express the design of a computer program or
an algorithm. The aim is to get the idea quickly and also easy to read without
details. It is like a young child putting sentences together without any grammar.
There are several ways of writing pseudo-code; there are no strict rules. But to

Page 12
Introduction To Computer And Programming

reduce ambiguity between what you are required to do and what you express
let‘s base the pseudo code on the few defined conventions and carry out the
exercises.
It represents an algorithm in an English line text.
Some where between formal English and a programming
language.
Must be language independent.
Examples:
1. To get the smallest number from the list for above example.
Start
Let min=the first element
While not the end of list
Do
Compare min with the next element
If min is greater than the compared number
min=the compared number
Else
Do nothing
End Do
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

Page 13
Introduction To Computer And Programming

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.
Enforce programmer to put steps precisely.
Makes an algorithm easier to convert into program.
More readable
Can be easily hand traced.
It uses standard symbols.

Page 14
Introduction To Computer And Programming

Examples:
1. To get the smallest number from the list for above example.

start

a1 , a2 , a3 , a4 , a5 , , ,an

min= a1 i=2

T
i>n Display min stop

ai <min T min= ai

i=i+1

Page 15
Introduction To Computer And Programming

2. Draw a flowchart to add two numbers entered by user.

3. Draw flowchart to find the largest among three different numbers entered by user.

Page 16
Introduction To Computer And Programming

4. Draw a flowchart to find all the roots of a quadratic eq uation ax2+bx+c=0

5. A flowchart which calculates N! :

Page 17
Introduction To Computer And Programming

6. A flowchart which checks if a number is prime :

Page 18
Introduction To Computer And Programming

7. A flowchart which shows all prime numbers smaller or equal to N :

Page 19
Introduction To Computer And Programming

8. A flowchart which calculates all divisors of N :

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.

Page 20
Introduction To Computer And Programming

Evolution of Programming Language


Hardware programming
 Called hard wiring
Software programming
1. Machine Language
 The first programming language.
 Consists of string of 0‘s and 1‘s.
 The one that CPU directly understand
2. Assembly Language
 Consists of symbolic instructions
E.g MOVE, INT, ADD, SUB etc
 It has to be converted into machine language before it is used
by the computer.

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.
 Difficult to learn, write and debug.
 Machine dependent.
3. High level programming Languages
Page 21
Introduction To Computer And Programming

 Consists of convenient letters, symbols or English line text.


E.g cout<<endl;
Cout<<‖Hello World‖;

 There are more than 100 high level programming languages.


a. Structured: such as Basic, Pascal, Fortran
b. Object Oriented: such as C++, Java, Smalltalk
c. Windows Programming: Visual Basic, Visual C++,VB.Net

Problem Solving Steps

1. Understanding the Problem


a. Specify the program objects and program users
b. Specify output and input requirement
c. Specify processing requirement
Example:
Given f(x) = ax2+bx+c where a, b, c are real root and a≠0.
Input: a, b, c
Output: real roots
Process: Using Quadratic General Formula
2. Algorithm Development
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

Note:
These are some basic things to apply
I. Exercise the problem by taking several examples
II. Split the problem into manageable pieces
f(x) = ax2+bx+c
a≠0

Page 22
Introduction To Computer And Programming

Discriminator D=b2 - 4ac


D<0 then no real solution
D=0 then –b/2a is the only one solution
D>0 then –b+√( b2 - 4ac)/2a and –b-√( b2 - 4ac)/2a will be
the two solutions
III. Define the algorithm successively
Note: Algorithm should be
 A sequences of finite step
 Unambiguous
 Not designed for a particular case of problem

3. Program Coding (Program Development)


 Select the appropriate programming language.
 Code the program in that language following the syntax carefully.
 Use the programming language.
1. Editor (Editing): to write the source code.
2. Compiler (Compiling): to convert source code into object code.
3. Linker (Linking): convert object file into executable file.
4. Loader (Running): to load the program into RAM.
In C++:
 Start C++
 Write the source code and save it (*.CPP)
 Compile it (*.CPP -> *.OBJ)
 Link it (*.OBJ -> *.EXE)
 Run it (Disk -> RAM)

4. Program Testing
 Check the program to discover errors
 Run the program and debug it.
 Run the program with real-world data.
Errors

Page 23
Introduction To Computer And Programming

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.

2. Logical Error (Run-time error): when the program generates


unexpected result. But there is no error in compilation. It produces
wrong output.

Debugging: is the process of finding out and correcting program error.

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
c. The infrastructure might be changed (Hardware, Operating
system)
 In the above cases maintenance is needed

Page 24
Introduction To Computer And Programming

Chapter Two
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.

#include<iostream.h> and #include<conio.h>

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.

Page 25
Introduction To Computer And Programming

void main ()

This line corresponds to the beginning of the definition of the main


function. The main function is the point by where all C++ programs start
their execution, independently of its location within the source code.

This brace marks the beginning of the body of main.


cout << "Hello World\n";

This line is a statement. A statement is a computation step which may


produce a value. The end of a statement is always marked with a
semicolon (;). This statement causes the string "Hello World\n" to be sent
to the cout output stream. A string is any sequence of characters enclosed
in double-quotes. The last character in this string (\n) is a newline
character which is similar to a carriage return on a type writer. A stream is
an object which performs input or output. Cout is the standard output
stream in C++ (standard output usually means your computer monitor
screen). The symbol << is an output operator which takes an output
stream as its left operand and an expression as its right operand, and
causes the value of the latter to be sent to the former. In this case, the
effect is that the string "Hello World\n" is sent to cout, causing it to be
printed on the computer monitor screen

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.

} This brace marks the end of the body of main.

Page 26
Introduction To Computer And Programming

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

Let us add an additional instruction to our first program:

// my second program in C++ Hello World! I'm a C++ program


#include<iostream.h>
#include<conio.h>
void main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
getch();
}

In this case, we performed two insertions into cout in two different statements.
Once again, the separation in different lines of code has been done just to give
greater readability to the program, since main could have been perfectly valid
defined this way:

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.

C++ supports two ways to insert comments:

// line comment
/* block comment */

We are going to add comments to our second program:

Page 27
Introduction To Computer And Programming

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 pay
4 rate. */
Comment
5 int main (void)
6 {
7 int workDays = 5; // Number of work days per week
8 float workHours = 7.5; // Number of work hours per day
9 float payRate = 33.50; // Hourly pay rate
10 float weeklyPay; // Gross weekly pay
11 weeklyPay = workDays * workHours * payRate;
12 cout << "Weekly Pay = " << weeklyPay << '\n';
13 }

/* my second program in C++ Hello World! I'm a C++


with more comments */ program

#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();
}

Page 28
Introduction To Computer And Programming

Memory

A computer provides a Random Access Memory (RAM) for storing executable


program code as well as the data the program manipulates. This memory can
be thought of as a contiguous sequence of bits, each of which is capable of
storing a binary digit (0 or 1). Typically, the memory is also divided into
groups of 8 consecutive bits (called bytes). The bytes are sequentially
addressed. Therefore each byte can be uniquely identified by its address (see
Figure below).

Figure Bits and bytes in memory.


By te Address

1211 1212 1213 1214 1215 1216 1217


... By te By te By te By te By te By te By te ... 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).

Page 29
Introduction To Computer And Programming

Figure Representation of an integer in memory.


1211 1212 1213 1214 1215 1216 1217
... By te By te By te 10110011 10110011 By te By te ... Memory
salary
(a two-by te integer whose address is 1214)

While the exact binary representation of a data item is rarely of interest to a


programmer, the general organization of memory and use of addresses for
referring to data items (as we will see later) is very important.

Variables and Data Types

Variables

In computer programming, a variable is a storage location and an associated


symbolic name (an identifier) which contains some known or unknown quantity
or information, a value. The variable name is the usual way to reference the
stored value; this separation of name and content allows the name to be used
independently of the exact information it represents. The identifier in computer
source code can be bound to a value during run time, and the value of the
variable may thus change during the course of program execution. Variables in
programming may not directly correspond to the concept of variables in
mathematics. The value of a computing variable is not necessarily part of an
equation or formula as in mathematics. In computing, a variable may be
employed in a repetitive process — assigned a value in one place, then used
elsewhere, then reassigned a new value and used again in the same way (see
iteration). Variables in computer programming are frequently given long names
to make them relatively descriptive of their use, whereas variables in
mathematics often have terse, one- or two-character names for brevity in
transcription and manipulation.

A variable storage location may be referred by several different identifiers, a


situation known as aliasing. Assigning a value to the variable using one of the

Page 30
Introduction To Computer And Programming

identifiers will change the value that can be accessed through the other
identifiers.

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.

We can define a variable as a portion of memory to store a determined value.

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 to
identity, identification (the process of identifying), or an identifier (that is, an
instance of identification).

A valid identifier is a sequence of one or more letters, digits or underscore


characters (_). Neither spaces nor punctuation marks or symbols can be part of
an identifier. Only letters, digits and single underscore characters are valid. In
addition, variable identifiers always have to begin with a letter. They can also
begin with an underline character (_ ), but in some cases these may be reserved
for compiler specific keywords or external identifiers, as well as identifiers
containing two successive underscore characters anywhere. In no case they can
begin with a digit.

Page 31
Introduction To Computer And Programming

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

Very important: The C++ language is a "case sensitive" language. That


means that an identifier written in capital letters is not equivalent to another
one with the same name but written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable or the Result variable.
These are three different variable identifiers.

salary // valid identifier


salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary

Fundamental data types

In computer science and computer programming, a data type or simply type is


a classification identifying one of various types of data, such as real-valued,
integer or Boolean, that determines the possible values for that type; the

Page 32
Introduction To Computer And Programming

operations that can be done on values of that type; the meaning of the data;
and the way values of that type can be stored.

When programming, we store the variables in our computer's memory, but the
computer has to know what kind of data we want to store in them, since it is not
going to occupy the same amount of memory to store a simple number than to
store a single letter or a large number, and they are not going to be interpreted
the same way.

The memory in our computers is organized in bytes. A byte is the minimum


amount of memory that we can manage in C++. A byte can store a relatively
small amount of data: one single character or a small integer (generally an
integer between 0 and 255). In addition, the computer can manipulate more
complex data types that come from grouping several bytes, such as long
numbers or non-integer numbers.

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:

Name Description Size Range*

signed: -128 to 127


char Character or small integer. 1byte
unsigned: 0 to 255
short int signed: -32768 to 32767
Short Integer. 2bytes
(short) unsigned: 0 to 65535

signed: -32768 to 32767


int Integer. 2bytes
unsigned: 0 to 65535

signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)

Double precision floating point


double 8bytes 1.7e +/- 308 (15 digits)
number.

Page 33
Introduction To Computer And Programming

long Long double precision floating


10bytes 1.7e +/- 308 (15 digits)
double point number.
A literal character is written by enclosing the character between a pair of single quotes (e.g., 'A').
Nonprintable characters are represented using escape sequences. For example:
'\n' // new line
'\r' // carriage return
'\t' // horizontal tab
'\v' // vertical tab
'\b' // backspace
'\f' // formfeed
Single and double quotes and the backslash character can also use the escape notation:
'\'' // single quote (')
'\"' // double quote (")
'\\' // backslash (\)
Literal characters may also be specified using their numeric code value. The general escape sequence
\ooo (i.e., a backslash followed by up to three octal digits) is used for this purpose. For example
(assuming ASCII):
'\12' // newline (decimal code = 10)
'\11' // horizontal tab (decimal code = 9)
'\101' // 'A' (decimal code = 65)
'\0' // null (decimal code = 0)

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data
type we want it to be. The syntax to declare a new variable is to write the
specifier of the desired data type (like int, bool, float...) followed by a valid
variable identifier. For example:
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

Page 34
Introduction To Computer And Programming

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
commas. For example:

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:

// operating with variables 4

#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;

// print out the result:


cout << result;

Page 35
Introduction To Computer And Programming

// terminate the program:


getch();
}

Do not worries if something else than the variable declarations themselves look
a bit strange to you. You will see the rest in detail in coming sections.

Scope of variables

A variable can be either of global or local scope. A global variable is a variable


declared in the main body of the source code, outside all functions, while a
local variable is one declared within the body of a function or a block.

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.

Page 36
Introduction To Computer And Programming

Initialization of variables

When declaring a regular local variable, its value is by default undetermined.


But you may want a variable to store a concrete value at the same moment that
it is declared. In order to do that, you can initialize the variable.

For example, if we want to declare an int variable called a initialized with a


value of 0 at the moment in which it is declared, we could write:

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.

Although a constant's value is specified only once, a constant may be referenced


many times in a program. Using a constant instead of specifying a value
multiple times in the program can not only simplify code maintenance, but it can
also supply a meaningful name for it and consolidate such constant bindings to a
standard code location (for example, at the beginning).

Constants are expressions with a fixed value.

Declared constants (const)

With the const prefix you can declare constants with a specific type in the same
way as you would do with a variable:
const int pathwidth = 100;

Page 37
Introduction To Computer And Programming

const char tabulator = '\t';

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

1. Write a program which inputs a temperature reading expressed in Fahrenheit and outputs
its equivalent in Celsius, using the formula:
5
C ( F 32)
9
Compile and run the program. Its behaviour should resemble this:
Temperature in Fahrenheit: 41
41 degrees Fahrenheit = 5 degrees Celsius
2. Which of the following represent valid variable definitions?
int n = -100;
unsigned int i = -100;
signed int = 2.9;
long m = 2, p = 4;
int 2k;
double x = 2 * m;
float y = y * 2;
unsigned double z = 0.0;
double d = 0.67F;
float f = 0.52L;
signed char = -1786;
char c = '$' + 2;
sign char h = '\111';
char *name = "Peter Pan";
unsigned char *num = "276811";
3. Which of the following represent valid identifiers?
identifier

Page 38
Introduction To Computer And Programming

seven_11
_unique_
gross-income
gross$income
2by2
default
average_weight_of_a_large_pizza
variable
object.oriented

Page 39
Introduction To Computer And Programming

Operators

Assignment (=)

The assignment operator assigns a value to a variable.


a = 5;

This statement assigns the integer value 5 to the variable a.

a = b;

Here also assign the value of b into a.

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:

// assignment operator a:4 b:7


#include<iostream.h>
#include<conio.h>
void main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
getch();
}

The following expression is also valid in C++:

Page 40
Introduction To Computer And Programming

a = b = c = 5;

It assigns 5 to the all the three variables: a, b and c.

Arithmetic operators (+, -, *, /, %)

C++ provides five basic arithmetic operators (+, -, *, /, %).


Except for remainder (%) all other arithmetic operators can accept a mix of
integer and real operands. Generally, if both operands are integers then the
result will be an integer. However, if one or both of the operands are reals then
the result will be a real (or double to be exact).
When both operands of the division operator (/) are integers then the division is
performed as an integer division and not the normal division we are used to.
Integer division always results in an integer outcome (i.e., the result is always
rounded down). For example:
9/2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
To obtain a real division when both operands are integers, you should cast one
of the operands to be real:
Int cost = 100;
Int volume = 80;
Double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns
the remainder of integer-dividing the operands. For example 13%3 is calculated
by integer dividing 13 by 3 to give an outcome of 4 and a remainder of 1; the
result is therefore 1.
It is possible for the outcome of an arithmetic operation to be too large for
storing in a designated variable. This situation is called an overflow. The
outcome of an overflow is machine-dependent and therefore undefined. For
example:
unsigned char k = 10 * 92; // overflow: 920 > 255

Page 41
Introduction To Computer And Programming

It is illegal to divide a number by zero. This results in a run-time division-by-


zero failure which typically causes the program to terminate.

The five arithmetical operations supported by the C++ language are:

+ addition

- subtraction

* multiplication

/ division

% modulo

Operations of addition, subtraction, multiplication and division literally


correspond with their respective mathematical operators. The only one that you
might not be so used to see may be modulo; whose operator is the percentage
sign (%). Modulo is the operation that gives the remainder of a division of two
values. For example, if we write:

a = 11 % 3;

the variable a will contain the value 2, since 2 is the remainder from dividing 11
between 3.

Compound assignment (+=, -=, *=, /=)

When we want to modify the value of a variable by performing an operation on


the value currently stored in that variable we can use compound assignment
operators:

expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;

Page 42
Introduction To Computer And Programming

a /= b; a = a / b;
price = price * (units +
price *= units + 1;
1);
Operator Example Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4

// compound assignment operators 5


#include<iostream.h>
#include<conio.h>
void main ()
{
int a, b=3;
a = b;
a+=2; // equivalent
cout << a; to a=a+2
getch();
}

An assignment operation is itself an expression whose value is the value stored


in its left operand. An assignment operation can therefore be used as the right
operand of another assignment operation. Any number of assignments can be
concatenated in this fashion to form one expression. For example:

int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));

Page 43
Introduction To Computer And Programming

m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;


This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
Multiple expressions can be combined into one expression using the comma
operator. The comma operator takes two operands. It first evaluates the left
operand and then the right operand, and returns the value of the latter as the
final outcome. For example:
int m, n, min;
int mCount = 0, nCount = 0;
//...
min = (m < n ? mCount++, m : nCount++, n);
Here when m is less than n, mCount++ is evaluated and the value of m is stored
in min. Otherwise, nCount++ is evaluated and the value of n is stored in min.

Increase and decrease (++, --)

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
B=3; B=3;
A=++B; A=B++;
// A contains 4, B // A contains 3, B contains
contains 4 4

Page 44
Introduction To Computer And Programming

In Example 1, B is increased before its value is copied to A. While in Example 2,


the value of B is copied to A and then B is increased.

int k = 5;

Increment and decrement operators.

Operator Name Example


++ Auto Increment ++k + 10 // gives 16
(prefix)
++ Auto Increment k++ + 10 // gives 15
(postfix)
-- Auto Decrement --k + 10 // gives 14
(prefix)
-- Auto Decrement k-- + 10 // gives 15
(postfix)
Both operators can be used in prefix and postfix form. The difference is
significant. When used in prefix form, the operator is first applied and the
outcome is then used in the expression. When used in the postfix form, the
expression is evaluated first and then the operator applied.

Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the


relational and equality operators. The result of a relational operation is a
Boolean value that can only be true or false, according to its Boolean result.

== Equal to

!= Not equal to

> Greater than

< Less than

Greater than or equal


>=
to

Page 45
Introduction To Computer And Programming

<= Less than or equal to

Here there are some examples:

(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,

(a == 5) // evaluates to false since a is not equal to 5.


(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or 6.3 >= 5 // gives 1
Equal

Logical operators ( !, &&, || )

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:

Page 46
Introduction To Computer And Programming

!(5 == 5) // evaluates to false because the expression in (5 ==


5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 1
|| Logical Or 5 < 6 || 6 < 5 // gives 1

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

false false false

The operator || corresponds with Boolean logical operation OR. This operation
results true if either one of its two operands is true, thus being false only when
both operands are false themselves. Here are the possible results of a || b :

Page 47
Introduction To Computer And Programming

|| OPERATOR

a b a || b

true true true

true false true

false true true

false false false

For example:

( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).


( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).

Conditional operator ( ? )

The conditional operator evaluates an expression returning a value if that


expression is true and a different one if the expression is evaluated as false. Its
format is:

condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return
result2.

7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.


7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is
greater than 3.
a>b ? a : b // returns whichever is greater, a or b.

Page 48
Introduction To Computer And Programming

// conditional operator 7

#include<iostream.h>
#include<conio.h>
void main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
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 value specified 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.

Examle2

int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
Note that of the second and the third operands of the conditional operator only
one is evaluated. This may be significant when one or both contain side -effects
(i.e., their evaluation causes a change to the value of a variable). For example,
in
int min = (m < n ? m++ : n++);
m is incremented because m++ is evaluated but n is not incremented because
n++ is not evaluated.
Because a conditional operation is itself an expression, it may be used as an
operand of another conditional operation, that is, conditional expressions may
be nested. For example:

Page 49
Introduction To Computer And Programming

int m = 1, n = 2, p =3;
int min = (m < n ? (m < p ? m : p)
: (n < p ? n : p));

Basic Input/output

Standard Output (cout)

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).

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

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:

cout << "Hello"; // prints Hello


cout << Hello; // prints the content of Hello variable

The insertion operator (<<) may be used more than once in a single statement:

Page 50
Introduction To Computer And Programming

cout << "Hello, " << "I am " << "a C++ 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:

cout << "Hello, I am " << age << " years old and my zipcode is " <<
zipcode;

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:

Hello, I am 24 years old and my zipcode is 90064

In order to perform a line break on the output we must explicitly insert a new-
line character into cout. In C++ a new-line character can be specified as \n
(backslash, n):

cout << "First sentence.\n ";


cout << "Second sentence.\nThird sentence.";

This produces the following output:

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;

Page 51
Introduction To Computer And Programming

would print out:

First sentence.
Second sentence.

Standard Input (cin).

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.

// i/o example Please enter an integer value:


702
#include<iostream.h> The value you entered is 702 and
#include<conio.h> its double is 1404.

void main ()
{
int i;
cout << "Please enter an integer
value: ";
cin >> i;
cout << "The value you entered is
" << i;
cout << " and its double is
"<<i*2<<".\n";

Page 52
Introduction To Computer And Programming

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.

cin and strings

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:

// cin with strings What's your name? Juan Souli�


#include<iostream.h> Hello Juan Souli�.

Page 53
Introduction To Computer And Programming

#include <string.h> What is your favorite team? The


#include <iostream.h> Isotopes
#include<conio.h> I like The Isotopes too!

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.

Simple Type Conversion

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

Page 54
Introduction To Computer And Programming

As shown by these examples, the built-in type identifiers can be used as type
operators. Type operators are unary (i.e., take one operand) and appear
inside brackets to the left of their operand. This is called explicit type
conversion. When the type name is just one word, an alternate notation may
be used in which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This happens
when values of different types are mixed in an expression. For example:
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
In the last example, i + d involves mismatching types, so i is first converted to
double (promoted) and then added to d. The result is a double which does not
match the type of i on the left side of the assignment, so it is converted to int
(demoted) before being assigned to i.
The above rules represent some simple but common cases for type conversion.
More complex cases will be examined later in the book after we have discussed
other data types and classes.

Exercises

1. Write expressions for the following:


To test if a number n is even.
To test if a character c is a digit.
To test if a character c is a letter.
To do the test: n is odd and positive or n is even and negative.
To give the number of characters in a null-terminated string literal s.
2. Add extra brackets to the following expressions to explicitly show the
order in which the operators are evaluated:
(n <= p + q && n >= p - q || n == 0)
(++n * q-- / ++p - q)

Page 55
Introduction To Computer And Programming

(n | p & q ^ p << 2 + q)
(p < q ? n < p ? q * n - 2 : q / n + 1 : q - n)
3. What will be the value of each of the following variables after its
initialization:
double d = 2 * int(3.14);
long k = 3.14 - 3;
char c = 'a' + 2;
char c = 'p' + 'A' - 'a';
4. Write a program which inputs a positive integer n and outputs 2 raised
to the power of n.
5. Write a program which inputs three numbers and outputs the message
sorted if the numbers are in ascending order, and outputs Not sorted
otherwise.

Page 56
Introduction To Computer And Programming

Chapter Three

Control Structures

Conditional structure:

The if Statement
The if keyword is used to execute a statement or block only if a condition is

fulfilled. Its form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is


true, statement is executed. If it is false, statement is ignored (not executed)
and the program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value
stored in the x variable is indeed 100:

if (x == 100)
cout << "x is 100";

If we want more than a single statement to be executed in case that the


condition is true we can specify a block using braces { }:

if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want to happen if the condition is not


fulfilled by using the keyword else. Its form used in conjunction with if is:

Page 57
Introduction To Computer And Programming

if (expression)
statement1 ;

else
statement2 ;

For example:

if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -
and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a


range of values. The following example shows its use telling if the value
currently stored in x is positive, negative or none of them (i.e. zero):

A frequently-used form of nested if statements involves the else part consisting


of another if-else statement. For example:
if (ch >= '0' && ch <= '9')
kind = digit;
else {
if (ch >= 'A' && ch <= 'Z')
kind = upperLetter;
else
{
if (ch >= 'a' && ch <= 'z')
kind = lowerLetter;
else
kind = special;

Page 58
Introduction To Computer And Programming

}
}
For improved readability, it is conventional to format such cases as follows:
if (ch >= '0' && ch <= '9')
kind = digit;
else if (cha >= 'A' && ch <= 'Z')
kind = capitalLetter;
else if (ch >= 'a' && ch <= 'z')
kind = smallLetter;
else
kind = special;
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

The selective structure


The switch Statement
The switch statement provides a way of choosing between a set of alternatives,
based on the value of an expression. The general form of the switch statement
is:
switch (expression) {
case constant1:
statements;
...
case constantn:

statements;
default:
statements;
}

Page 59
Introduction To Computer And Programming

First expression (called the switch tag) is evaluated, and the outcome is
compared to each of the numeric constants (called case labels), in the order
they appear, until a match is found. The statements following the matching case
are then executed. Note the plural: each case may be followed by zero or more
statements (not just one statement). Execution continues until either a break
statement is encountered or all intervening statements until the end of the
switch statement are executed. The final default case is optional and is exercised
if none of the earlier cases provide a match.
For example, suppose we have parsed a binary arithmetic operation into its
three components and stored these in variables operator, operand1, and operand2.
The following switch statement performs the operation and stored the result in
result.
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
As illustrated by this example, it is usually necessary to include a break
statement at the end of each case. The break terminates the switch stateme nt
by jumping to the very end of it. There are, however, situations in which it
makes sense to have a case without a break. For example, if we extend the
above statement to also allow x to be used as a multiplication operator, we will
have:
switch (operator) {
case '+': result = operand1 + operand2;

Page 60
Introduction To Computer And Programming

break;
case '-': result = operand1 - operand2;
break;
case 'x':
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Because case 'x' has no break statement (in fact no statement at all!), when this
case is satisfied, execution proceeds to the statements of the next case and the
multiplication is performed.
It should be obvious that any switch statement can also be written as multiple
if-else statements. The above statement, for example, may be written as:
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
switch example if-else equivalent
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";

Page 61
Introduction To Computer And Programming

cout << "x is 2"; }


break; else {
default: cout << "value of x unknown";
cout << "value of x unknown"; }
}

Iteration structures (loops)

Loops have as purpose to repeat a statement a certain number of times or while


a condition is fulfilled.

The while loop

The while statement (also called while loop) provides a way of repeating a
statement while a condition holds. It is one of the three flavors of iteration in
C++. The general form of the while statement is:

while (expression)
statement;
First expression (called the loop condition) is evaluated. If the outcome is
nonzero then statement (called the loop body) is executed and the whole
process is repeated. Otherwise, the loop is terminated.
For example, suppose we wish to calculate the sum of all numbers from 1 to
some integer denoted by n. This can be expressed as:
i = 1;
sum = 0;
while (i <= n)
sum += i++;
For n set to 5, Table 5.Error! Bookmark not defined. provides a trace of the
loop by listing the values of the variables involved and the loop condition.
While loop trace.

Page 62
Introduction To Computer And Programming

Iteration i n i <= n sum += i++


First 1 5 1 1
Second 2 5 1 3
Third 3 5 1 6
Fourth 4 5 1 10
Fifth 5 5 1 15
Sixth 6 5 0

It is not unusual for a while loop to have an empty body (i.e., a null statement).
The following loop, for example, sets n to its greatest odd factor.
while (n % 2 == 0 && n /= 2)
;

Here the loop condition provides all the necessary computation, so there is no
real need for a body. The loop condition not only tests that n is even, it also
divides n by two and ensures that the loop will terminate should n be zero.

For example, we are going to make a program to countdown using a while-loop:


// custom countdown using while Enter the starting number > 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
#include<iostream.h>
#include<conio.h>

void main ()
{
int n;
cout << "Enter the starting
number > ";
cin >> n;

while (n>0) {
cout << n << ", ";
--n;

Page 63
Introduction To Computer And Programming

}
cout << "FIRE!\n";
getch();
}

The do-while loop

The do statement (also called do loop) is similar to the while statement, except
that its body is executed first and then the loop condition is examined. The
general form of the do statement is:
do
statement;
while (expression);
First statement is executed and then expression is evaluated. If the outcome of
the latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
The do loop is less frequently used than the while loop. It is useful for situations
where we need the loop body to be executed at least once, regardless of the
loop condition. For example, suppose we wish to repeatedly read a value and
print its square, and stop when the value is zero. This can be expressed as the
following loop:
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);

Example

// number echoer Enter number (0 to end): 12345


You entered: 12345
#include<iostream.h> Enter number (0 to end): 160277
#include<conio.h> You entered: 160277
void main () Enter number (0 to end): 0

Page 64
Introduction To Computer And Programming

{ You entered: 0
unsigned long n;
do {
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
getch();
}

The do-while loop is usually used when the condition that has to determine the
end of the loop is determined within the loop statement itself, like in the
previous case, where the user input within the block is what is used to
determine if the loop has to end. In fact if you never enter the value 0 in the
previous example you can be prompted for more numbers forever.

The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like
the while loop. But in addition, the for loop provides specific locations to contain
an initialization statement and an increase statement. So this loop is
specially designed to perform a repetitive action with a counter which is
initialized and increased on each iteration.

It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a


counter variable. This is executed only once.

Page 65
Introduction To Computer And Programming

2. condition is checked. If it is true the loop continues, otherwise the loop


ends and statement is skipped (not executed).

3. statement is executed. As usual, it can be either a single statement or a


block enclosed in braces { }.

4. finally, whatever is specified in the increase field is executed and the loop
gets back to step 2.

Here is an example of countdown using a for loop:

// countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,


#include<iostream.h> FIRE!
#include<conio.h>
void main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
getch();
}

The initialization and increase fields are optional. They can remain empty,
but in all cases the semicolon signs between them must be written. For example
we could write: for (;n<10;) if we wanted to specify no initialization and no
increase; or for (;n<10;n++) if we wanted to include an increase field but no
initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one
expression in any of the fields included in a for loop, like in initialization,
for example. The comma operator (,) is an expression separator, it serves to
separate more than one expression where only one is generally expected. For
example, suppose that we wanted to initialize more than one variable in our
loop:
Page 66
Introduction To Computer And Programming

for ( n=0, i=100 ; n!=i ; n++, i-- )


{
// whatever here...
}

This loop will execute for 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not
equal to i). Because n is increased by one and i decreased by one, the loop's
condition will become false after the 50th loop, when both n and i will be equal
to 50.

Jump statements.

The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled.
It can be used to end an infinite loop, or to force it to end before its natural end.
For example, we are going to stop the count down before its natural end (maybe
because of an engine check failure?):

// break loop example 10, 9, 8, 7, 6, 5, 4, 3,


countdown aborted!
#include<iostream.h>
#include<conio.h>

void main ()
{
int n;
for (n=10; n>0; n--)

Page 67
Introduction To Computer And Programming

{
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
getch();
}

The continue statement

The continue statement causes the program to skip the rest of the loop in the
current iteration as if the end of the statement block had been reached, causing
it to jump to the start of the following iteration. For example, we are going to
skip the number 5 in our countdown:

// continue loop example 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!


#include<iostream.h>
#include<conio.h>

void main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
getch();
}

Page 68
Introduction To Computer And Programming

The goto statement

goto allows to make an absolute jump to another point in the program. You
should use this feature with caution since its execution causes an unconditional
jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an argument
for the goto statement. A label is made of a valid identifier followed by a colon
(:).

Generally speaking, this instruction has no concrete use in structured or object


oriented programming aside from those that low-level programming fans may
find for it. For example, here is our countdown loop using goto:

// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,


FIRE!
#include<iostream.h>
#include<conio.h>

void main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
getch();
}

The exit function

exit is a function defined in the cstdlib library.

Page 69
Introduction To Computer And Programming

The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:

void exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling
programs. By convention, an exit code of 0 means that the program finished
normally and any other value means that some error or unexpected results
happened.

Exercises
1. Write a program which inputs a person’s height (in centimeters) and weight (in
kilograms) and outputs one of the messages: underweight, normal, or overweight,
using the criteria:
Underweight: weight < height/2.5
Normal: height/2.5 <= weight <= height/2.3
Overweight: height/2.3 < weight
2. Assuming that n is 20, what will the following code fragment output when executed?
if (n >= 0)
if (n < 10)
cout << "n is small\n";
else
cout << "n is negative\n";
3. Write a program which inputs a date in the format dd/mm/yy and outputs it in the format
month dd, year. For example, 25/12/61 becomes:
December 25, 1961
4. Write a program which inputs an octal number and outputs its decimal equivalent. The
following example illustrates the expected behavior of the program:
Input an octal number: 214
Octal(214) = Decimal(532)
5. Write a program which produces a simple multiplication table of the following format for
integers in the range 1 to 9:
1 x 1 = 1

Page 70
Introduction To Computer And Programming

1 x 2 = 2
...
9 x 9 = 81

Page 71
Introduction To Computer And Programming

Chapter Four
Functions
Using functions we can structure our programs in a more modular way,
accessing all the potential that structured programming can offer to us in C++.

A function is a group of statements that is executed when it is called from some


point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements }

where:

type is the data type specifier of the data returned by the function.

name is the identifier by which it will be possible to call the function.

parameters (as many as needed): Each parameter consists of a data type


specifier followed by an identifier, like any regular variable declaration (for
example: int x) and which acts within the function as a regular local
variable. They allow to pass arguments to the function when it is called.
The different parameters are separated by commas.

statements is the function's body. It is a block of statements surrounded


by braces { }.

Here you have the first function example:

// function example The result is 8


#include<iostream.h>
#include<conio.h>

int addition (int a, int b)


{
int r;

Page 72
Introduction To Computer And Programming

r=a+b;
return (r);
}

void main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
getch();
}

In order to examine this code, first of all remember something said at the
beginning of this tutorial: a C++ program always begins its execution by the
main function. So we will begin there.

We can see how the main function begins by declaring the variable z of type
int. Right after that, we see a call to a function called addition. Paying
attention we will be able to see the similarity between the structure of the call to
the function and the declaration of the function itself some code lines above:

The parameters and arguments have a clear correspondence. Within the main
function we called to addition passing two values: 5 and 3, that correspond to
the int a and int b parameters declared for function addition.

At the point at which the function is called from within main, the control is lost
by main and passed to function addition. The value of both arguments passed
in the call (5 and 3) are copied to the local variables int a and int b within the
function.

Page 73
Introduction To Computer And Programming

Function addition declares another local variable (int r), and by means of the
expression r=a+b, it assigns to r the result of a plus b. Because the actual
parameters passed for a and b are 5 and 3 respectively, the result is 8.

The following line of code:

return (r);

finalizes function addition, and returns the control back to the function that
called it in the first place (in this case, main). At this moment the program
follows it regular course from the same point at which it was interrupted by the
call to addition. But additionally, because the return statement in function
addition specified a value: the content of variable r (return (r);), which at
that moment had a value of 8. This value becomes the value of evaluating the
function call.

So being the value returned by a function the value given to the function call
itself when it is evaluated, the variable z will be set to the value returned by
addition (5, 3), that is 8. To explain it another way, you can imagine that the
call to a function (addition (5,3)) is literally replaced by the value it returns
(8).

The following line of code in main is:

cout << "The result is " << z;

That, as you may already expect, produces the printing of the result on the
screen.

And here is another example about functions:


Page 74
Introduction To Computer And Programming

// function example The first result


#include<iostream.h> is 5
#include<conio.h> The second result
is 5
int subtraction (int a, int b) The third result
{ is 2
int r; The fourth result
r=a-b; is 6
return (r);
}

void main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction
(7,2)<< '\n';
cout << "The third result is " << subtraction
(x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
getch();
}

In this case we have created a function called subtraction. The only thing that
this function does is to subtract both passed parameters and to return the
result.

Nevertheless, if we examine function main we will see that we have made


several calls to function subtraction. We have used some different calling
methods so that you see other ways or moments when a function can be called.

Page 75
Introduction To Computer And Programming

In order to fully understand these examples you must consider once again that
a call to a function could be replaced by the value that the function call itself is
going to return. For example, the first case (that you should already know
because it is the same pattern that we have used in previous examples):

z = subtraction (7,2);
cout << "The first result is " << z;

If we replace the function call by the value it returns (i.e., 5), we would have:

z = 5;
cout << "The first result is " << z;

As well as

cout << "The second result is " << subtraction (7,2);

has the same result as the previous call, but in this case we made the call to
subtraction directly as an insertion parameter for cout. Simply consider that
the result is the same as if we had written:

cout << "The second result is " << 5;

since 5 is the value returned by subtraction (7,2).

In the case of:

cout << "The third result is " << subtraction (x,y);

The only new thing that we introduced is that the parameters of subtraction
are variables instead of constants. That is perfectly valid. In this case the values
passed to function subtraction are the values of x and y, that are 5 and 3
respectively, giving 2 as result.

Page 76
Introduction To Computer And Programming

The fourth case is more of the same. Simply note that instead of:

z = 4 + subtraction (x,y);

we could have written:

z = subtraction (x,y) + 4;

with exactly the same result. I have switched places so you can see that the
semicolon sign (;) goes at the end of the whole statement. It does not
necessarily have to go right after the function call. The explanation might be
once again that you imagine that a function can be replaced by its returned
value:

z = 4 + 2;
z = 2 + 4;

Functions with no type. The use of void.

If you remember the syntax of a function declaration:

type name ( argument1, argument2 ...) statement

you will see that the declaration begins with a type, that is the type of the
function itself (i.e., the type of the datum that will be returned by the function
with the return statement). But what if we want to return no value?

Imagine that we want to make a function just to show a message on the screen.
We do not need it to return any value. In this case we should use the void type
specifier for the function. This is a special specifier that indicates absence of
type.

// void function example I'm a function!


#include<iostream.h>

Page 77
Introduction To Computer And Programming

#include<conio.h>

void printmessage ()
{
cout << "I'm a function!";
}

void main ()
{
printmessage ();
getch();
}

void can also be used in the function's parameter list to explicitly specify that
we want the function to take no actual parameters when it is called. For
example, function printmessage could have been declared as:

void printmessage (void)


{
cout << "I'm a function!";
}

Although it is optional to specify void in the parameter list. In C++, a


parameter list can simply be left blank if we want a function with no parameters.

What you must always remember is that the format for calling a function
includes specifying its name and enclosing its parameters between parentheses.
The non-existence of parameters does not exempt us from the obligation to
write the parentheses. For that reason the call to printmessage is:

printmessage ();

Page 78
Introduction To Computer And Programming

The parentheses clearly indicate that this is a call to a function and not the
name of a variable or some other C++ statement. The following call would have
been incorrect:

printmessage;

Arguments passed by value and by reference.

Until now, in all the functions we have seen, the arguments passed to the
functions have been passed by value. This means that when calling a function
with parameters, what we have passed to the function were copies of their
values but never the variables themselves. For example, suppose that we called
our first function addition using the following code:

int x=5, y=3, z;


z = addition ( x , y );

What we did in this case was to call to function addition passing the values of x
and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

This way, when the function addition is called, the value of its local variables a
and b become 5 and 3 respectively, but any modification to either a or b within
the function addition will not have any effect in the values of x and y outside it,
because variables x and y were not themselves passed to the function, but only
copies of their values at the moment the function was called.

But there might be some cases where you need to manipulate from inside a
function the value of an external variable. For that purpose we can use
arguments passed by reference, as in the function duplicate of the following
example:
Page 79
Introduction To Computer And Programming

// passing parameters by reference x=2, y=6, z=14


#include<iostream.h>
#include<conio.h>

void duplicate (int& a, int& b, int& c)


{
a*=2;
b*=2;
c*=2;
}

void main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ",
z=" << z;
getch();
}

The first thing that should call your attention is that in the declaration of
duplicate the type of each parameter was followed by an ampersand sign (&).
This ampersand is what specifies that their corresponding arguments are to be
passed by reference instead of by value.

When a variable is passed by reference we are not passing a copy of its value,
but we are somehow passing the variable itself to the function and any
modification that we do to the local variables will have an effect in their
counterpart variables passed as arguments in the call to the function.

Page 80
Introduction To Computer And Programming

To explain it in another way, we associate a, b and c with the arguments passed


on the function call (x, y and z) and any change that we do on a within the
function will affect the value of x outside it. Any change that we do on b will
affect y, and the same with c and z.

That is why our program's output, that shows the values stored in x, y and z
after the call to duplicate, shows the values of all the three variables of main
doubled.

If when declaring the following function:

void duplicate (int& a, int& b, int& c)

we had declared it this way:

void duplicate (int a, int b, int c)

i.e., without the ampersand signs (&), we would have not passed the variables
by reference, but a copy of their values instead, and therefore, the output on
screen of our program would have been the values of x, y and z without having
been modified.

Passing by reference is also an effective way to allow a function to return more


than one value. For example, here is a function that returns the previous and
next numbers of the first parameter passed.

// more than one returning value Previous=99, Next=101


#include<iostream.h>
#include<conio.h>

void prevnext (int x, int& prev, int&


next)
{

Page 81
Introduction To Computer And Programming

prev = x-1;
next = x+1;
}

void main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ",
Next=" << z;
getch();
}

Default values in parameters.

When declaring a function we can specify a default value for each parameter.
This value will be used if the corresponding argument is left blank when calling
to the function. To do that, we simply have to use the assignment operator and
a value for the arguments in the function declaration. If a value for that
parameter is not passed when the function is called, the default value is used,
but if a value is specified this default value is ignored and the passed value is
used instead. For example:
// default values in functions 6
#include<iostream.h> 5
#include<conio.h>

int divide (int a, int b=2)


{
int r;
r=a/b;
return (r);
}

Page 82
Introduction To Computer And Programming

void main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
getch();
}

As we can see in the body of the program there are two calls to function divide.
In the first one:

divide (12)

we have only specified one argument, but the function divide allows up to two.
So the function divide has assumed that the second parameter is 2 since that is
what we have specified to happen if this parameter was not passed (notice the
function declaration, which finishes with int b=2, not just int b). Therefore the
result of this function call is 6 (12/2).

In the second call:

divide (20,4)

there are two parameters, so the default value for b (int b=2) is ignored and b
takes the value passed as argument, that is 4, making the result returned equal
to 5 (20/4).

Exercises
1. Given the following definition of a Swap function
void Swap (int x, int y)
{

Page 83
Introduction To Computer And Programming

int temp = x;
x = y;
y = temp;
}
what will be the value of x and y after the following call:
x = 10;
y = 20;
Swap(x, y);
2. Write a function which outputs all the prime numbers between 2 and a given positive
integer n:
void Primes (unsigned int n);
A number is prime if it is only divisible by itself and 1.
3. Define a recursive version of the Power function described in this chapter.
4. Write a function which returns the sum of a list of real values
double Sum (int n, double val ...);
where n denotes the number of values in the list

Page 84
Introduction To Computer And Programming

Chapter Five
Arrays, Strings and Pointer
Arrays

An array is a series of elements of the same type placed in contiguous memory


locations that can be individually referenced by adding an index to a unique
identifier.

That means that, for example, we can store 5 values of type int in an array
without having to declare 5 different variables, each one with a di fferent
identifier. Instead of that, using an array we can store 5 different values of the
same type, int for example, with a unique identifier.

For example, an array to contain 5 integer values of type int called billy could
be represented like this:

where each blank panel represents an element of the array, that in this case are
integer values of type int. These elements are numbered from 0 to 4 since in
arrays the first index is always 0, independently of its length.

Like a regular variable, an array must be declared before it is used. A typical


declaration for an array in C++ is:

type name [elements];

Page 85
Introduction To Computer And Programming

where type is a valid type (like int, float...), name is a valid identifier and the
elements field (which is always enclosed in square brackets []), specifies how
many of these elements the array has to contain.

Therefore, in order to declare an array called billy as the one shown in the
above diagram it is as simple as:

int billy [5];

NOTE: The elements field within brackets [] which represents the number of
elements the array is going to hold, must be a constant value, since arrays are
blocks of non-dynamic memory whose size must be determined before
execution. In order to create arrays with a variable length dynamic memory is
needed, which is explained later in these tutorials.

Initializing arrays.

When we declare an array, we have the possibility to assign initial values to


each one of its elements by enclosing the values in braces { }. For example:

int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:

Accessing the values of an array.

In any point of a program in which an array is visible, we can access the value
of any of its elements individually as if it was a normal variable, thus being able
to both read and modify its value. The format is as simple as:

name[index]

Page 86
Introduction To Computer And Programming

Following the previous examples in which billy had 5 elements and each of
those elements was of type int, the name which we can use to refer to each
element is the following:

For example, to store the value 75 in the third element of billy, we could write
the following statement:

billy[2] = 75;

and, for example, to pass the value of the third element of billy to a variable

// arrays example 12206


#include<iostream.h>
#include<conio.h>

int billy [] = {16, 2, 77, 40,


12071};
int n, result=0;

void main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
getch();
}

called a, we could write:

Page 87
Introduction To Computer And Programming

a = billy[2];

Therefore, the expression billy[2] is for all purposes like a variable of type
int.

Multidimensional arrays

Multidimensional arrays can be described as "arrays of arrays". For example, a


bidimensional array can be imagined as a bidimensional table made of elements,
all of them of a same uniform data type.

jimmy represents a bidimensional array of 3 per 5 elements of type int. The


way to declare this array in C++ would be:

int jimmy [3][5];

and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:

jimmy[1][3]

(Remember that array indices always begin by zero).

Page 88
Introduction To Computer And Programming

Pointers

The memory of your computer can be imagined as a succession of memory


cells, each one of the minimal size that computers manage (one byte). These
single-byte memory cells are numbered in a consecutive way, so as, within any
block of memory, every cell has the same number as the previous one plus one.

This way, each cell can be easily located in the memory because it has a unique
address and all the memory cells follow a successive pattern. For example, if we
are looking for cell 1776 we know that it is going to be right between cells 1775
and 1777, exactly one thousand cells after 776 and exactly one thousand cells
before cell 2776.

Declaring variables of pointer types

The declaration of pointers follows this format:

type * name;

where type is the data type of the value that the pointer is intended to point to.
This type is not the type of the pointer itself! but the type of the data the pointer
points to. For example:

int * number;
char * character;
float * greatnumber;

Reference operator (&)

int * ted;
int andy,fred;

Page 89
Introduction To Computer And Programming

The address that locates a variable within memory is what we call a reference to
that variable. This reference to a variable can be obtained by preceding the
identifier of a variable with an ampersand sign (&), known as reference operator,
and which can be literally translated as "address of". For example:
ted = &andy;

This would assign to ted the address of variable andy, since when preceding the
name of the variable andy with the reference operator (&) we are no longer
talking about the content of the variable itself, but about its reference (i.e., its
address in memory).

For now on we are going to assume that andy is placed during runtime in the
memory address 1776. This number (1776) is just and arbitrary assumption we
are inventing right now in order to help clarify some concepts in this tutorial, but
in reality, we cannot know before runtime the real value the address of a
variable will have in memory.

Consider the following code fragment:

andy = 25;
fred = andy;
ted = &andy;

The values contained in each variable after the execution of this, are shown in
the following diagram:

Page 90
Introduction To Computer And Programming

First, we have assigned the value 25 to andy (a variable whose address in


memory we have assumed to be 1776).

The second statement copied to fred the content of variable andy (which is 25).
This is a standard assignment operation, as we have done so many times
before.

Finally, the third statement copies to ted not the value contained in andy but a
reference to it (i.e., its address, which we have assumed to be 1776). The
reason is that in this third assignment operation we have preceded the identifier
andy with the reference operator (&), so we were no longer referring to the
value of andy but to its reference (its address in memory).

Dereference operator (*)

We have just seen that a variable which stores a reference to another variable is
called a pointer. Pointers are said to "point to" the variable whose reference they
store.

Using a pointer we can directly access the value stored in the variable which it
points to. To do this, we simply have to precede the pointer's identifier with an
asterisk (*), which acts as dereference operator and that can be literally
translated to "value pointed by".

Therefore, following with the values of the previous example, if we write:

beth = *ted;

Page 91
Introduction To Computer And Programming

(that we could read as: "beth equal to value pointed by ted") beth would take
the value 25, since ted is 1776, and the value pointed by 1776 is 25.

You must clearly differentiate that the expression ted refers to the value 1776,
while *ted (with an asterisk * preceding the identifier) refers to the value stored
at address 1776, which in this case is 25. Notice the difference of including or
not including the dereference operator (I have included an explanatory
commentary of how each of these two expressions could be read):

beth = ted; // beth equal to ted ( 1776 )


beth = *ted; // beth equal to value pointed by ted ( 25 )

Notice the difference between the reference and dereference operators:

& is the reference operator and can be read as "address of"

* is the dereference operator and can be read as "value pointed by"

Thus, they have complementary (or opposite) meanings. A variable referenced


with & can be dereferenced with *.

Earlier we performed the following two assignment operations:

andy = 25;
ted = &andy;

Page 92
Introduction To Computer And Programming

Right after these two statements, all of the following expressions would give
true as result:

andy == 25
&andy == 1776
ted == 1776
*ted == 25

The first expression is quite clear considering that the assignment operation
performed on andy was andy=25. The second one uses the reference operator
(&), which returns the address of variable andy, which we assumed it to have a
value of 1776. The third one is somewhat obvious since the second expression
was true and the assignment operation performed on ted was ted=&andy. The
fourth expression uses the dereference operator (*) that, as we have just seen,
can be read as "value pointed by", and the value pointed by ted is indeed 25.

So, after all that, you may also infer that for as long as the address pointed by
ted remains unchanged the following expression will also be true:

*ted == andy

Now have a look at this code:

// my first pointer firstvalue is 10


#include<iostream.h> secondvalue is 20
#include<conio.h>

void main ()
{
int firstvalue, secondvalue;
int * mypointer;

Page 93
Introduction To Computer And Programming

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue <<
endl;
cout << "secondvalue is " << secondvalue
<< endl;
getch();
}

String (Character Sequences)


As you may already know, the C++ Standard Library implements a powerful
string class, which is very useful to handle and manipulate strings of characters.
However, because strings are in fact sequences of characters, we can represent
them also as plain arrays of char elements.

For example, the following array:

char jenny [20];

is an array that can store up to 20 elements of type char. It can be represented


as:

Therefore, in this array, in theory, we can store sequences of characters up to


20 characters long. But we can also store shorter sequences. For example,
jenny could store at some point in a program either the sequence "Hello" or
the sequence "Merry christmas", since both are shorter than 20 characters.

Page 94
Introduction To Computer And Programming

Therefore, since the array of characters can store shorter sequences than its
total length, a special character is used to signal the end of the valid sequence:
the null character, whose literal constant can be written as '\0' (backslash,
zero).

Our array of 20 elements of type char, called jenny, can be represented storing
the characters sequences "Hello" and "Merry Christmas" as:

Notice how after the valid content a null character ('\0') has been included in order to indicate the
end of the sequence. The panels in gray color represent char elements with undetermined values.

String Variables
There are two types of string variable declaration:

1. a string as an array of characters


char <idf>[<size>] ;
Description: Reserve <size>+1 byte of memory of which one character for
the null character, i.e ‗\0‘.
Example: char name[10] ;

2. a string as a pointer of characters


char *<idf> ;
Description: idf is a pointer to characters.
Example: char *name ;

Two Dimensional Arrays of Characters

Declaration: char <idf> [<row size> ] [<column size> ] ;

Page 95
Introduction To Computer And Programming

Example:
char name[5][10] ;
for (int i=0 ; i<5 ; i++ )
cin>>name[i] ;
The above fragment of code accept five name each with ten characters

String Library Functions

Note: In order to use a string library function you must include a header file:
#include<string.h>

1. strlen(S1) : returns the length of string S1.


int leng;
leng= strlen(―Hello‖);
cout<<leng; //displays 5

2. strcpy(S1,S2) : copies S2 to S1.


char name[20];
strcpy(name, ‗Abebe Kebede‖ );
cout<< name; //displays Abebe Kebede
Note: strcpy (S1, S2, n) : copies the first n characters of source to
destination.

3. strcat(S1,S2) : concatenates S2 at the end of S1.


char X[20] ,D[20] ;
strcpy( S1, ―Micro‖ );
strcpy( S2, ―Link ) ;
strcat (X,D) ;
cout<< X ; //displays MicroLink

4. strlwr(S1) : converts all characters in S1 into lower case.

Page 96
Introduction To Computer And Programming

char *Y;
strcpy(Y, ―MICROLINK‖);
strlwr(Y);
cout<<Y; //displays microlink

// string Example

5. strlupr(S1) : converts all characters in S1 into upper case.


char *Y;
strcpy(Y, ―microlink‖);
strlwr(Y);

Page 97
Introduction To Computer And Programming

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main ()
{
char name[100][15] , key[15];
int n,m=0;
cout<<”Hopw many names : “;
cout<<”\nEnter all names one by one:”;
cin>>n;
for(int i=0 ; i<n ; i++)
cin>>name[i];
cout<<”Enter the name you are looking for:”;
cin>>key;

for(int i=0 ; i<n ; i++)


if(strcmp(name[i],key)==0)
m++;

cout<<”There are “<<m<<” “<<key;


getch();
}

cout<<Y; //displays MICROLINK

6. strcmp(S1,S2) : return any positive number if S>S2, any negative


number if S1<S2 or zero if S1=S2 by comparing with ASCII code.
Note: strcmpi(S!,S2) : compares of S1 and S2 without case sensitivity.
Exercise:
Write a program to read n list of student name and stored in an array and
search and displays the name entered by the user.

Chapter Six
Data Structure
Page 98
Introduction To Computer And Programming

We have already learned how groups of sequential data can be used in C++. But
this is somewhat restrictive, since in many occasions what we want to store are
not mere sequences of elements all of the same data type, but sets of different
elements with different data types.

Data structures

A data structure is a group of data elements grouped together under one name.
These data elements, known as members, can have different types and different
lengths. Data structures are declared in C++ using the following syntax:

struct structure_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

where structure_name is a name for the structure type, object_name can be a


set of valid identifiers for objects that have the type of this structure. Within
braces { } there is a list with the data members, each one is specified with a
type and a valid identifier as its name.

The first thing we have to know is that a data structure creates a new type:
Once a data structure is declared, a new type with the identifier specified as
structure_name is created and can be used in the rest of the program as if it
was any other type. For example:

struct product {
int weight;

Page 99
Introduction To Computer And Programming

float price;
} ;

product apple;
product banana, melon;

Let's see a real example where you can see how a structure type can be used in
the same way as fundamental types:

// example about structures Enter title: Alien


#include <iostream.h> Enter year: 1979
#include <string.h>
#include <fstream.h> My favorite movie is:
#include <conio.h> 2001 A Space Odyssey (1968)
And yours is:
struct movies_t { Alien (1979)
char title[20];
int year;
} mine, yours;

void printmovie (movies_t movie);

void main ()
{
char mystr[20];

strcpy(mine.title,"2001 A Space
Odyssey");
mine.year = 1968;

cout << "Enter title: ";


cin.getline(yours.title , 20 );
cout << "Enter year: ";

Page 100
Introduction To Computer And Programming

cin.getline (mystr,20);

cout << "My favorite movie is:\n


";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
getch();
}

void printmovie (movies_t movie)


{
cout << movie.title;
cout << " (" << movie.year <<
")\n";
}

The example shows how we can use the members of an object as regular
variables. For example, the member yours.year is a valid variable of type int,
and mine.title is a valid variable of type string.

Page 101
Introduction To Computer And Programming

Chapter Seven
Input/output with Files
C++ provides the following classes to perform output and input of characters
to/from files:

ofstream: Stream class to write on files

ifstream: Stream class to read from files

fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and
ostream. We have already used objects whose types were these classes: cin is
an object of class istream and cout is an object of class ostream. Therfore, we
have already been using classes that are related to our file streams. And in fact,
we can use our file streams the same way we are already used to use cin and
cout, with the only difference that we have to associate these streams with
physical files. Let's see an example:

// basic file operations [file example.txt]


#include <iostream.h> Writing this to a file
#include <fstream.h>
#include <conio.h>

void main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a
file.\n";
myfile.close();
getch();
}

Page 102
Introduction To Computer And Programming

This code creates a file called example.txt and inserts a sentence into it in the
same way we are used to do with cout, but using the file stream myfile
instead.

But let's go step by step:

Open a file

In order to open a file with a stream object we use its member function open():

open (filename, mode);

Where filename is a null-terminated character sequence of type const char *


(the same type that string literals have) representing the name of the file to be
opened, and mode is an optional parameter with a combination of the following
flags:

ios::in Open for input operations.

ios::out Open for output operations.

All output operations are performed at the end


of the file, appending the content to the current
ios::app
content of the file. This flag can only be used in
streams open for output-only operations.

All these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could do
it by the following call to member function open():

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app );

Page 103
Introduction To Computer And Programming

Each one of the open() member functions of the classes ofstream, ifstream
and fstream has a default mode that is used if the file is opened without a
second argument:

default mode
class
parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically
and respectivelly assumed, even if a mode that does not include them is passed
as second argument to the open() member function.

Closing a file

When we are finished with our input and output operations on a file we shall
close it so that its resources become available again. In order to do that we
have to call the stream's member function close(). This member function takes
no parameters, and what it does is to flush the associated buffers and close the
file:
myfile.close();

Text files

Text file streams are those where we do not include the ios::binary flag in
their opening mode. These files are designed to store text and thus all values
that we input or output from/to them can suffer some formatting
transformations, which do not necessarily correspond to their literal binary
value.

Page 104
Introduction To Computer And Programming

Data output operations on text files are performed in the same way we operated
with cout:

// writing on a text file [file example.txt]


#include <iostream.h> This is a line.
#include <fstream.h> This is another line.
#include <conio.h>

void main () {
ofstream myfile
("example.txt");

myfile << "This is a


line.\n";
myfile << "This is another
line.\n";
myfile.close();

getch();
}

Data input from a file can also be performed in the same way that we did with
cin:

// reading a text file This is a line.


#include <iostream.h> This is another line.
#include <fstream.h>
#include <string.h>
#include <conio.h>

void main () {

Page 105
Introduction To Computer And Programming

string line;
ifstream myfile
("example.txt");

while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();

getch();
}

This last example reads a text file and prints out its content on the screen.
Notice how we have used a new member function, called eof() that returns true
in the case that the end of the file has been reached. We have created a while
loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the
file has been reached).

References Books

1. Website: WWW.cplusplus.com
2. Jess Liberity, C++ An Introduction to Programming. Prentice Hall, 1996

Page 106

You might also like