Professional Documents
Culture Documents
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
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
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
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
Page 3
Introduction To Computer And Programming
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.
- 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)
Page 10
Introduction To Computer And Programming
4 3 -1 6 -4 7
Page 11
Introduction To Computer And Programming
7 2 -1 8 10 8 Sn=11
Compare the search key with the element of the list one by one starting
from first element until a match is found or the list is exhausted.
Expressing Algorithm
There are two ways by which you can express or describe your algorithm.
A. Using Pseudo code
An algorithm is a procedure for solving a problem in terms of the actions to be
executed and the order in which those actions are to be executed. An algorithm
is merely the sequence of steps taken to solve a problem. The steps are
normally "sequence," "selection,‖ "iteration," and a case-type statement.
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
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
3. Draw flowchart to find the largest among three different numbers entered by user.
Page 16
Introduction To Computer And Programming
Page 17
Introduction To Computer And Programming
Page 18
Introduction To Computer And Programming
Page 19
Introduction To Computer And Programming
Though, flowchart is useful in efficient coding, debugging and analysis of a program, drawing
flowchart in very complicated in case of complex programs and often ignored.
Page 20
Introduction To Computer And Programming
Note:
Machine language and assembly languages are called low level
programming language.
The computer (CPU) can understand directly or with little
translator, so that they are very fast.
They require less resource (Memory).
You can get the power of the machine.
Disadvantages:
Much closer to the machine so that you need to know the architecture of
the machine.
Difficult to learn, write and debug.
Machine dependent.
3. High level programming Languages
Page 21
Introduction To Computer And Programming
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
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
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.
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 ()
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.
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
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.
// line comment
/* block comment */
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 }
#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
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
Variables
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.
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).
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
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.
Next you have a summary of the basic fundamental data types in C++, as well
as the range of values that can be represented with each one:
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
Page 33
Introduction To Computer And Programming
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:
#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;
Page 35
Introduction To Computer And Programming
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
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
int a = 10;
Constants
In computer programming, a constant is an identifier whose associated value
cannot typically be altered by the program during its execution (though in some
cases this can be circumvented, e.g. using self-modifying code). Many
programming languages make an explicit syntactic distinction between constant
and variable symbols.
With the const prefix you can declare constants with a specific type in the same
way as you would do with a variable:
const int pathwidth = 100;
Page 37
Introduction To Computer And Programming
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 (=)
a = b;
For example, let us have a look at the following code - I have included the
evolution of the content stored in the variables as comments:
Page 40
Introduction To Computer And Programming
a = b = c = 5;
Page 41
Introduction To Computer And Programming
+ addition
- subtraction
* multiplication
/ division
% modulo
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11
between 3.
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
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
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
Page 43
Introduction To Computer And Programming
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
int k = 5;
Relational and equality operators ( ==, !=, >, <, >=, <= )
== Equal to
!= Not equal to
Page 45
Introduction To Computer And Programming
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use any valid
expression, including variables. Suppose that a=2, b=3 and c=6,
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
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
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
For example:
Conditional operator ( ? )
If condition is true the expression will return result1, if it is not it will return
result2.
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
By default, the standard output of a program is the screen, and the C++ stream
object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as <<
(two "less than" signs).
The << operator inserts the data that follows it into the stream preceding it. In
the examples above it inserted the constant string Output sentence, the
numerical constant 120 and variable x into the standard output stream cout.
Notice that the sentence in the first instruction is enclosed between double
quotes (") because it is a constant string of characters. Whenever we want to
use constant strings of characters we must enclose them between double quotes
(") so that they can be clearly distinguished from variable names. For example,
these two sentences have very different results:
The insertion operator (<<) may be used more than once in a single statement:
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:
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):
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For
example:
Page 51
Introduction To Computer And Programming
First sentence.
Second sentence.
The standard input device is usually the keyboard. Handling the standard input
in C++ is done by applying the overloaded operator of extraction (>>) on the
cin stream. The operator must be followed by the variable that will store the
data that is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second
one waits for an input from cin (the keyboard) in order to store it in this integer
variable.
void main ()
{
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:
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and another one
for variable b that may be separated by any valid blank separator: a space, a
tab character or a newline.
We can use cin to get strings with the extraction operator (>>) as we do with
fundamental data type variables:
cin >> mystring;
However, as it has been said, cin extraction stops reading as soon as if finds
any blank space character, so in this case we will be able to get just one word
for each extraction. This behavior may or may not be what we want; for
example if we want to get a sentence from the user, this extraction operation
would not be useful.
In order to get entire lines, we can use the function getline, which is the more
recommendable way to get user input with cin:
Page 53
Introduction To Computer And Programming
void main ()
{
char mystr[20];
cout << "What's your name? ";
cin.getline(mystr , 20);
cout << "Hello " << mystr <<
".\n";
cout << "What is your favorite
team? ";
cin.getline(mystr , 20);
cout << "I like " << mystr << "
too!\n";
getch();
}
Notice how in both calls to getline we used the same string identifier (mystr).
What the program does in the second call is simply to replace the previous
content by the new one that is introduced.
A value in any of the built-in types we have seen so far can be converted (type-
cast) to any of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short
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
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
if (condition) statement
if (x == 100)
cout << "x is 100";
if (x == 100)
{
cout << "x is ";
cout << x;
}
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.
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";
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
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
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.
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 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
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.
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.
Page 65
Introduction To Computer And Programming
4. finally, whatever is specified in the increase field is executed and the loop
gets back to step 2.
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
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.
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?):
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 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:
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
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
(:).
void main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
getch();
}
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:
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++.
where:
type is the data type specifier of the data returned by the function.
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.
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).
That, as you may already expect, produces the printing of the result on the
screen.
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.
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
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:
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);
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;
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.
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:
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;
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:
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
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
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.
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.
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();
}
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>
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).
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
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.
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:
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.
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
void main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
getch();
}
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
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
jimmy[1][3]
Page 88
Introduction To Computer And Programming
Pointers
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.
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;
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.
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
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).
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".
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):
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
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();
}
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:
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
Note: In order to use a string library function you must include a header file:
#include<string.h>
Page 96
Introduction To Computer And Programming
char *Y;
strcpy(Y, ―MICROLINK‖);
strlwr(Y);
cout<<Y; //displays microlink
// string Example
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;
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;
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:
void main ()
{
char mystr[20];
strcpy(mine.title,"2001 A Space
Odyssey");
mine.year = 1968;
Page 100
Introduction To Computer And Programming
cin.getline (mystr,20);
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:
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:
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.
Open a file
In order to open a file with a stream object we use its member function open():
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
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:
void main () {
ofstream myfile
("example.txt");
getch();
}
Data input from a file can also be performed in the same way that we did with
cin:
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