You are on page 1of 31

Chapter 1

Concepts in Computer Programming


1.1 A Brief History in Programming Languages
Although computers appear to be amazingly intelligent machines, they cannot yet think on their own.
Computers still rely on human beings to give them directions. The directions are called programs, and the
people who write programs are called programmers. Programmers make it possible for us to communicate
with out personal computers. Without programmers, we wouldnt be able to use the computer to write a
letter or play a game.
Just as human beings communicate with each other through the use of languages such as English, Spanish,
Hindi, and Chinese, programmers use a variety of special languages called programming languages, to
communicate with the computer. Some popular programming languages are C++, C#, Java, Visual Basic,
PERL (Practical Extraction and Report Language), C, and COBOL (Common Business Oriented
Language).
1.1.1 Machine Languages
Within a computer, all data is represented by microscopic electronic switches that can be either off or on.
The off switch is designated by a 0, and the on is designated with 1. Because computers can understand
these on and off switches, the first programmers had to write the program instructions using nothing but
combinations of 0s and 1s. Instructions written in this format (1s and 0s) are called machine language or
machine code. The machine languages represent the only way to communicate directly with the computer,
thus programming in machine language is very tedious and error prone and require highly trained
programmers.
1.1.2 Assembly Languages
Slightly more advance programming language is called assembly languages. The assembly languages
simplify the programmers job by allowing the programmer to use mnemonics in place of the 0s and 1s in
the program. Mnemonics are memory aids-in this case, alphabetic abbreviations for instructions. Example
assembly language uses the mnemonic ADD to represent and add operation. And example of an
instruction written in assembly language is ADD BX, AX. Program written in and assembly language
require an assembler, which is a program, to covert the assembly instructions into machine code. Although
it is much easier to write programs in assembly language that in machine language, programming in
assembly language is tedious and requires highly trained programmers.
1.1.3 High Level Languages
High level language represent the next major improvement in programming languages. High level
languages are a vast improvement over machine and assembly languages, because they allow the
programmer to use instructions that more closely resemble the English language. An example of an
instruction written in a high level language is grossPay= hours* rate. In addition, high level
languages are more machine independent than machine and assembly languages. As a result, programs
written in a high-level language usually require a compiler, which is a program, to convert the English-like
instructions into 0s and 1s the computer can understand.
First high-level languages were used to create procedure oriented programs. Procedure oriented
programs, requires the programmer to concentrate on the major task the program needs to perform. A
payroll program, for example typically performs several major task, such as inputting the employee data,
calculating the gross pay, calculating the taxes, calculating the net pay, and outputting a pay check. The
programmer must instruct the computer in every step of the way, from the start of the task to its
completion. In a procedure oriented language, the programmer determines and controls the order in which
the computer processes the instructions. In other words, the programmer must determine not only the
proper instruction to give to the computer, but the correct sequence of those instruction as well. Examples
of procedure oriented, high level language include COBOL, BASIC (Beginners All Purpose Symbolic
Instruction Code), and C.
More advance high-level languages can be used to create object-oriented programs in addition to
procedure-oriented ones. An object oriented programming requires the programmer to focus on the objects
that the program can use to accomplish its goal. The objects can take on many different forms. For
example, programs written for the Windows environment typically use object checkboxes, list boxes, and
buttons. A payroll program, on the other hand, might utilize objects found in real world, such as time card
object, an employee object, and a check object. Because each object is viewed as an individual unit, an
object can be used in more than one program, usually with little or no modification. A check object used in
a payroll program, for example, also can be used in a sales revenue program, and an accounts payable
program. The ability to use an object for more than one purpose saves programming time and money-an
advantage that contributes to the popularity of object oriented programming. Examples of high-level
languages that can be used to create both procedure-oriented and object-oriented programs include C++,
Visual Basic, Java and C#.
1

1.2 Control Structures


All computer programs, no matter how simple or how complex, are written using one or more of three basic
structures: sequence, repetition and selection. These structures are called control structures or logic
structures, because they control the flow of a programs logic. You will use the sequence structure in every
program youll write. In most programs, you also will use both the selection and repetition structure. In this
portion we would use the mechanical man named Rob, who will help illustrate the control structures. In the
proceeding chapter these control structures would be implemented in actual C++ programming.
1.2.1 The Sequence Structure
The sequence structure in a computer program directs the computer to process the program instructions;
one after another in the order listed in the program (It is comparable to following a food recipe in the real
world). You will find the sequence structure in every program. The sequence structure works by
programming a mechanical man named Rob. Like a computer, Rob has a limited instruction set, in other
words Rob can understand only a specific number of instructions, also called commands. Robs instruction
set includes the following three commands: walk(means to move 1 step forward), turn(turns to 180
degrees) and sit. In the example below, the instructions would command Rob to sit on the chair 2 steps in
front of him.

2 steps

Algorithm:
1. walk
2. walk
3. turn
4. sit

Figure 1.1 An example of sequence structure


The four instructions shown in Figure 1.1 are called algorithm, which is set of step-by-step instructions
that accomplish a task. Notice that Rob must follow the specific order of instructions in sequence.
1.2.2 Repetition Structure
As with the sequence structure, you are already are familiar with the repetition structure (typically the
same with walk from one building until reaching the other). When used in a program, the repetition
structure directs the computer to repeat one or more instructions until some condition is met, at which time
the computer should stop repeating the instructions. The repetition structure is also referred to as a loop or
as iteration. In the example below, Rob is facing a chair that is 50 steps away from him, instead writing 50
sequential walk instructions; you could use the repeat structure to direct Rob to walk 50 times and then
turn and sit.

50 steps

Algorithm:
1. Repeat 50 times:
walk
2. turn
3. sit

Figure 1.2 An example of repetition structure


Notice that indenting that the walk instruction below the Repeat 50 times instruction is indented, in this
manner the instruction is part of the repetition structure and, therefore needs to be repeated. While the turn
and sit are not part of the repetition structure.
1.2.3 Selection Structure
The last of the three control structures is the selection structure. Like the sequence and repetition structure,
you already are familiar with the selections structure, also called decision structure. The selection structure
makes a decision and then takes appropriate action based on that decision. (normally the same in the real
world with choosing a path in an intersection). When used in a computer program, the selection structure
alerts the computer that a decision needs to be made, and it provides the appropriate action to take based
2

on the result of the decision. On the example below, this illustrates how Rob would decide where he
would drop the ball on a box 20 steps ahead of him

20 Steps

Red

Yellow
Figure 1.3 An example of selection structure
Algorithm:
1. Repeat 20 times
Walk
2. if the balloon is red do this
Drop the balloon in the red box
Otherwise, do this
Drop the balloon in the yellow box.
3. Turn
4. Repeat walk 20 times
Walk
5. Turn
Notice that there are additional instructions that are added to the previous ones. Specifically instruction 2, notice
that this instruction is intended for deciding where Rob would drop the balloon. It is also know as the if and
otherwise instruction, indenting the instructions below either if or otherwise would indicate that when the
condition of the first statement is not met, then it would proceed to the next condition, otherwise it would
proceed to the next instruction.

1.3 Methods for Problem Solving


1.3.1 Analyzing the Problem( Using IPO)
You cannot solve a problem unless you understand it, and you cannot understand a problem unless you
analyze it-in other words, unless you identify its important components. The purpose for analyzing a problem is
to determine the goal of solving the problem and the items that are needed to achieve the goal. Programmers
refer the goal as the output, and they refer the items needed to achieve the goal as the input. When analyzing a
problem, you always search first of the output, and then the input.
Some programmers use an IPO chart to organize and summarize the results of a problem analysis. IPO
stands for Input, Processing, and Output. The figure below shows the format.
Input Processing
Output
Processing items
Algorithm:
Figure 1.4. Format of an IPO chart.

1.3.2 Planning The Algorithm (Using either Psuedocode or Flowchart)


Pseudocode: is a tool programmers use to help them plan an algorithm. It is a compact and informal highlevel description of a computer programming algorithm that uses the structural conventions of a
programming language, but is intended for human reading rather than machine reading. Pseudocode
typically omits details that are not essential for human understanding of the algorithm, such as variable
declarations, system-specific code and subroutines. Psuedocode is no not standardized, every programmer
has his/her own version.
Flowchart: is a common type of diagram that represents an algorithm or process showing the steps as boxes
of various kinds, and their order by connecting these with arrows. Flowcharts are used in analyzing,
designing, documenting or managing a process or program in various fields. Unlike psuedocode flowchart
uses standardized symbols. Some standard flowchart symbols have been established and are accepted by
most programmers. These symbols are called ANSI (American National Standards Institute) symbols.
Some of the most commonly used flowcharting symbols are shown in Figure 1.4.
In a flowchart, every symbol must be connected by at least one in-arrow and exactly one
out-arrow with the exception of the following:
3

The start symbol being the start of every flowchart must have no in-arrow.
The stop symbol being the end of every flowchart must have no out-arrow.
The decision represents branching and thus must have at least two out arrows.

As the names states,


it refers to any process step that is a preparation process flow step, such as a set-up ope
Preparation

Symbol

Figure 1.5 Commonly Used Flowcharting Symbols.

IPO
Example: You are a worker at CalTron oil and gas industries, currently your salary as a Computer analyst is
$4,500 per month. The management proposes a salary increase 5% salary increase for all employees. Write a
program that would calculate the salary increase for a certain employee, if ever the salary increase would be
implemented. Use IPO chart and Pseudocode and Flowchart to solve this problem
Using IPO and Pseudocode
Input
Processing
Output
Old Monthly Pay Processing items:
New Monthly Pay
Monthly Raise, New Monthly Pay
Algorithm:
1. Enter the current monthly pay
2. Calculate the monthly raise by
multiplying the Old monthly
pay by 5%
3. Calculate the new monthly pay
by adding the monthly raise and
the Old monthly pay
4

4. Display the new monthly pay


Using IPO and Flowchart.
Input
Old Monthly Pay

Processing
Processing items:
Monthly Raise, New Monthly Pay
Algorithm:

Output
New Monthly Pay

1.4 Problem Solving Implementation in a C++ Program


After you have planned and built the proper algorithm, now it is time to implement it in a C++ source
code. C++ is a superset of C language. It has features present in C with the addition of Object-oriented
programming features. C++ was designed and implemented by Bjarne Stroustrup at AT&T Bell
Laboratories. The initial version of C++, called C with Classes, was first used in 1980. C++ was
designed to deliver the flexibility and efficiency of C for systems programming.
This means C++ programming more apt and appropriate for serious programmers.
C++ is a general-purpose programming language that support the following features:
supports data abstraction
supports object-oriented programming
supports generic programming
C is by far the most successful language providing the programmer with a programming model that
closely matches the machine model. Working with pointers, bytes, and individual bits, things like
optimization techniques start to make a lot more sense. With these strong features, majority of the system
software today are created using C/C++ programming language. These software include operating
systems, language compilers, assembly, text editors, printer spoolers, network and hardware device
drivers, modern programs, data bases, language interpreters and utilities.
1.4.1 Assigning Names, Data Types, and Initial values to IPO items
Programmers use the information in the IPO chart to code the algorithm. The programmer begins by
assigning descriptive name to each unique input, processing, and output item listed in the IPO chart. Most
programmers use the lower case when declaring the variables, however when the variable would contain
two words, most programmers would use camel case, in which the first character of the first word is lower
case and the succeeding words in uppercase without any spaces. Example: oldMonthlyPay, raiseRate.
The programmer also assigns data type to each input, processing and output item. The day type specifies
the type of data (for example, decimal or integer) each item presents. In this case we would use double as
the data type for each item. Further data types would be introduced next chapter.
In addition to assigning both name and data type to each input, processing and output item, the
programmer also assigns an initial value. This is referred to as initializing the item. The instruction to
declare a variable is considered a statement, and each statement in C++ ends in semi-colon.
Example: This IPO chart information is derived form the example above.
5

IPO Chart Information


Input
Old Monthly Pay
Processing
Monthly Raise, New Monthly Pay
Output
New Monthly Pay
Algorithm
1. Enter the current monthly pay
2. Calculate the monthly raise by multiplying
the Old monthly pay by 5%
3. Calculate the new monthly pay by adding
the monthly raise and the Old monthly pay
4. Display the new monthly pay

C++ Instructions
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;

1.4.2 Translating Algorithm into C++ code


After assigning the name, data type, and initial value to each input, processing and output item, the programmer
then translates each step in the algorithm into one of more C++ instructions. Like most programming language
C++ programming language follows a specific format referred to as its syntax, these syntax is like the
grammatical rules in the English language. Still using the IPO Chart information above, we would convert the
algorithm into C++ instruction.
IPO Chart Information
Input
Old Monthly Pay
Processing
Monthly Raise, New Monthly Pay
Output
New Monthly Pay
Algorithm
1. Enter the current monthly pay

C++ Instructions
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
cout<< Enter current monthly
;
cin>> oldPay;
monthlyRaise=oldPay*0.05;

pay:

2. Calculate the monthly raise by multiplying


the Old monthly pay by 5%
3. Calculate the new monthly pay by adding newPay=oldPay+monthlyRaise;
the monthly raise and the Old monthly pay
cout<<New Pay<<newPay<<endl;
4. Display the new monthly pay
Systematically, the algorithm code conversion is accomplished though the following
Step1: The algorithm would ask for input item which is the oldPay. Thus to guide the user, you would use
streams, which are sequence of characters, to perform standard input and output. The standard output called
cout refers to the computer screen, while the cin refers to the computer keyboard. The instruction cout<< Enter
current monthly pay: prompts the user with the message enclosed in the quotation marks, while the << in this
statement is known as an insertion operator (comparable to sends to). The next statement would ask the user for
an input; cin>>oldPay, thus this tells the user to input the variable and store it on the variable oldPay, on the
other hand >> this statement indicates the extraction operator (comparable to get from).
Step2: The second step is multiplying the stored value in oldPay, with the fixed value which is 5% (0.05). The
syntax in C++ to indicate multiplication uses asterisk, then and after both values are multiplied their product is
stored in the variable monthlyRaise.
Step3: In this step, the value stored in oldPay added to the value stored in monthly raise and stores it in the
variable newPay
Step4: The last step, would command the computer to display New Pay to the computer screen, along with
the contents in the variable newPay. The endl text are known as string manipulators in C++. String manipulators
allows the program to manipulate, or manage, the input and output stream characters in some way. In this case
endl stream manipulator is used to advance the cursor to the next line.

CS 134 - Chapter 2 C++ Program Structure


2.1. Elements of a C++ Program
//Title: Calculating and displaying Caltron salary increase
//Created by: <your name> on <current date>
#include <iostream.h>

int main()
{
//declare variables
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
//enter input items
cout<< Enter current monthly pay: ;
cin>> oldPay;
//calculate raise and new pay
monthlyRaise=oldPay*0.05;
newPay=oldPay+monthlyRaise;
//display output items
cout<<New Pay: <<newPay<<endl;
return 0;
//end of main function
}

Figure 2.1 Shows the C++ program of calculating Caltron salary increase.
All programs can be broken drawn into 3 major sections namely:
a) heading
b) declaration
c) block
The heading section is necessary for documentation and initialization purposes and is required in
some languages. In C or C++, headings are written as simple comments. It is a good programming
practice to put all necessary information about the program. Below, the text prefixed with the symbol //
is an example of a heading if it is used for a single line and /* [code] */ for multiple lines. Based the
source code above
//Title: Calculating and displaying Caltron salary increase
//Created by: <your name> on <current date>

The declaration section includes definitions for variables, constants, labels, types and userdefine functions. The declaration section must be in the specific order that follows: constants, types,
variables. The only requirement is that any identifier or variable must be declared before using it. The
declaration section also contains at least one pre-defined system or user libraries/headers so that
functions will work properly. This done using the define statement. Most common libraries are
iostream.h, stdlib.h, stdio.h, string.h, math.h, conio.h . C++ Standard Library is a collection of classes and
functions, which are written in the core language and part of the C++ ISO Standard itself. The C++
Standard Library provides several generic containers, functions to utilize and manipulate these
containers, function objects, generic strings and streams (including interactive and file I/O), support for
some language features, and everyday functions for tasks such as finding the square root of a
number.
#include <iostream.h>

//declare variables
double oldPay = 0.0;
double monthlyRaise=0.0;

double newPay=0.0;
#include <iostream.h>
are directives for the preprocessor
they are not regular code lines with expressions but indications for the compiler's
preprocessor
the directive #include <iostream> tells the preprocessor to include the iostream
standard file
this specific file (iostream) includes the declarations of the basic standard input-output
library in C++, and it is included because its functionality is going to be used later in the
program.

The block section can be a program block, function block, etc. It consists of the actual C++
statements which starts with the reserved symbol { and finishes with the reserved symbol }. This
contains either/or input process and output of the program. And also this section actual human logic is
implemented in a language that is understood by the C++ compiler. The example below shows the
block section of the C++ example shown above.
7

//enter input items


cout<< Enter current monthly pay: ;
cin>> oldPay;
//calculate raise and new pay
monthlyRaise=oldPay*0.05;
newPay=oldPay+monthlyRaise;
//display output items
cout<<New Pay: <<newPay<<endl;
return 0;
//end of main function

int main ()
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
It does not matter whether there are other functions with other names defined before or
after it - the instructions contained within this function's definition will always be the first
ones to be executed in any C++ program.
it
is
essential
that
all
C++
programs
have
a
main
function.
The word main is followed in the code by a pair of parentheses (()). That is because it is
a function declaration: In C++, what differentiates a function declaration from other
types of expressions are these parentheses that follow its name. Optionally, these
parentheses
may
enclose
a
list
of
parameters
within
them.
Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.

cout << "Enter current monthly pay:";


This line is a C++ statement.
A statement is a simple or compound expression that can actually produce some effect.
In fact, this statement performs the only action that generates a visible effect in our first
program.
cout represents the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters (in this case the Hello World sequence
of characters) into the standard output stream (which usually is the screen).
cout is declared in the iostream standard file , so that's why we needed to include that
specific file and to declare that we were going to use this specific namespace earlier in
our code.
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 (one of the most common syntax errors is
indeed to forget to include some semicolon after a statement).

return 0;
This statement causes the main function to finish. return may be followed by a return
code (in our example is followed by the return code 0).
A return code of 0 for the main function is generally interpreted as the program worked
as expected without any errors during its execution.
This is the most usual way to end a C++ console program.

2.2. Named Constants, Variables and Data Types


Variables and named constants are location (within the computers internal memory) where a
program can temporarily store data while the program is running. The user at the keyboard may enter
the data; or the data may be read from a file or be the result of calculation made by the computer. In
the program in Figure 2.1, the user input (current monthly pay) will be stored in memory location
named oldPay. The program also will store the results of raise and new pay to memory location
named currentPay and raiseRate. Therefore to completely visualize the memory location, think of it as
small containers (or boxes) inside the computer, which may hold fixed or changeable items. The fixed
items are known as named constants and changeable items are known as variables.
8

2.2.1. Named Constants


These are items that would remain constant each time the program is executed. For example, instead
of using 5% or (0.05) multiplied to oldPay (as shown in figure 2.1), you could use percentIncr as a
named constant because the value would remain constant each time the program is executed.
2.2.2. Identifiers
You should assign a descriptive name to each variable and named constant used in a
program. These names are also called identifiers; reserved words are also not allowed to be used for
naming variables. Reserved words are words that are used exclusively by the language. They cannot
be used for any the other purpose, thus, never attempt to create an identifier with the same name as
a reserved word. An identifier, on the other hand is a word that you use name something on your
program. Technically is a reference to a location in memory. Practically speaking, it is the name of a
variable, user defined type, function, parameters etc.
All identifiers in Turbo C++ must start with a letter or underscore (but in some cases these may
be reserved for compiler specific keywords or external identifiers) and can be followed by any number
of letters, numbers and underscores. It has unlimited length. Moreover, C++ identifiers are case
sensitive therefore, identifier such as rate, Rate, RATE are all not the same. Many programmers use
uppercase letters when naming named constants and camel case when naming variables. This practice
allows them to easily distinguish named constant and variables in a program.

letter

Identifier
Underscore

letter

digit

underscore

Figure 2.2 : Syntax diagram for identifier e.g.


Correct Indentifiers
interest
final_
x9991
a_very_long_identifier
computeInterestRate

Incorrect Identifiers
4thDigit

if
id number
(age)
pre-paid

2.2.3. Memory location Data Types


In addition to selecting an appropriate name for each variable and name constant the program
uses, you must also determine the appropriate data type. The data type controls the type of data the
memory location can store. All the data types listed below are known as fundamental data type, this
means that these are the basic data types built into C++ language.
Name
Char

Description
Character

Size*
1byte

Short int

Integer.

2bytes

Range*
signed: -128 to 127
unsigned: 0 to 255
signed: -32768 to 32767
unsigned: 0 to 65535
9

Long int or
int

Long integer.

float
Floating point number
double
Double precision floating point number.
long double
Long double precision floating point number.
Table 2.1: Fundamental Data Types

4bytes

4bytes
8bytes
10bytes

signed:
-2147483648
to
2147483647
unsigned:
0 to 4294967295
3.4e +/- 38 (7 digits)
1.7e +/- 308 (15 digits)
1.7e +/- 4932

C++ programming language contains one or more data types for storing integers (whole
numbers), floating-point numbers (numbers with decimal place), and characters (letters, symbols, and
numbers that will not be used in calculations). The appropriate data type to use for a memory location
depends on the values the memory location will store. For example, memory locations assigned
either the short or int data type can store integers only, with its specific range. However, keep in mind
that memory usage is not the only important factor in determining the program efficiency. We could
compare that the short int uses lesser memory that long int, but a calculation containing int memory
location takes less time to process than a calculation containing short locations. That is because
computers coverts short memory location to int data type when a calculation is being performed. On
the other hand floating point number store data in approximation, the number enclosed in the
parenthesis (in Table 2.1), thus a repeating number 2.3333333333 stored in a single precision would
only be approximated up to 7 digits max.
2.2.4. Initializing a Memory location
In addition to assigning an appropriate name and data type for each variable and named
constant, you should also assign an initial value to each. You typically initialize a memory location by
assigning a literal constant to it. Unlike variables and named constant, a literal constant is an item of
data that can appear in a program instruction, and that can be stored in a memory location. It is
classified into two:
Numeric literal constant: That is simply a number. It can consist of a (+) sign, (-) sign, (.)
decimal point and either the letter e or E (used for exponential notation). It cannot contain comma,
space, special character, dollar sign and percent sign. Numeric literal constant is only applicable for int
and float data types. Numeric literal constant can also be specified in base 8 or base 16 (octal or
hexadecimal); this is done by prefixing an extra 0 (zero) for octal or 0x for hexadecimal: the constants
100, 0144, and 0x64 all represent the same number.
Character literal constant: Is one character enclosed in single quotation marks. The letter X is
a character constant, and so are the dollar sign $and a space. Character Literal constant is only
applicable for the char memory location
2.2.5. Type Conversion
When a program instructs the computer to assign a value to a memory location, the computer
first compares the values data type with the memory locations data type. The comparison is made to
verify the value is appropriate for the memory location. If the values data type does not match the
memory locations data type, the computer uses a process called implicit type conversion to convert
the value to fit the memory location. For example you declared a float data type, if you would initialize
it with a 10 integer value, the compiler would automatically convert it to 10.0, in this case the value is
promoted. However if an int data type is assigned with a floating value of 13.42343, because this is
not supported in int data type, thus the compiler would convert it into 13, in this case the value is
demoted. Implicit conversion is also applicable when processing calculation statements having
different data types.
To prevent the computer from making implicit type conversion, you could either declare the
same data type for all variables in a program. Another is you could use explicit type conversion, also
called type casting, to explicitly convert an item of data from one data type to another.
Syntax:
(data type) variablename

Example:
int a = 100;
float b,c,d;
c=a/8;
//c yields 12.0 because int a over int 8 results to int
b = (float)a/8;
//b yields 12.5 note that 100/8 is 12.
d=a/8.0;
//d yields 12.5 because int a over double d results to double

10

2.2.6. Assignment Statement


When an assignment statement is encountered in a program, the computer assigns the value of
the expression appearing on the right side of the assignment operator (=) to the variable whose
variableName appears on the left side of the assignment operator (=). The data type of the expressionwhich can include literals, named constants, variables, and arithmetic operators-must match the data
type of the variable to which it is assigned. Note that the assignment statement is only applicable for
primitive data type. Strings are not primitive because it has more than 1 character; it is an array of
characters hence it is invalid to assign strings to variables using the = symbol during runtime (except
when initializing characters arrays). \
syntax:
variablename = expression

example:
int num = 5;
my_char= '5';
x= y + z;
i = sqrt (j) - i * k;

Named Constant

Variables

const double PI=3.1416;


const int AGE=65;
const char YES=Y;
const float PAY=(float) (15.10);

int age = 0;
float rate=0.0;
double sale=(float) 0.0;
char grade=;

Table 2.3: Examples for Declaring Named Constant & Variables

2.3. Arithmetic and Logical Operations and Standard Math Functions


The capacity for logic and mathematical computations has long been associated with
computers. Mathematical computations are carried out using different operators listed below.
The Logic computations allow a computer to perform decision making process, these operators
are also listed here. Note that those in bold face are the most common operators that
beginners in programming use.

Operator Description
()
[]
.
->
++ -++
+
!
(type)
*
&

Associativity

Parentheses
(function
call)
(see
Note
1)
Brackets
(array
subscript) left-to-right
Member
selection
via
object
name
Member
selection
via
pointer
Postfix increment/decrement (see Note 2)
-- Prefix
- Unary
~ Logical
Cast
Dereference
Address

increment/decrement right-to-left
plus/minus
negation/bitwise
complement
(change
type)

* / %

Multiplication/division/modulus

left-to-right

+ -

Addition/subtraction

left-to-right

<< >>

Bitwise shift left, Bitwise shift right

left-to-right

<
> >=

<= Relational less than/less than or equal


Relational greater than/greater than or equal to

to left-to-right

== !=

Relational is equal to/is not equal to

left-to-right

&

Bitwise AND

left-to-right

Bitwise exclusive OR

left-to-right

Bitwise inclusive OR

left-to-right

&&

Logical AND

left-to-right

||

Logical OR

left-to-right

?:

Ternary conditional

right-to-left

=
+=
*=

Assignment
-= Addition/subtraction
/= Multiplication/division

right-to-left
assignment
assignment
11

%=
&= Modulus/bitwise
AND
^=
|= Bitwise
exclusive/inclusive
<<= >>= Bitwise shift left/right assignment

OR

assignment
assignment
left-to-right

Comma (separate expressions)

Table 2.4: Arithmetic and Logic Operators

Note 1:
Parentheses are also used to group expressions to force a different order of evaluation;
such parenthesized expressions can be nested and are evaluated from inner to outer
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or
decrement of the operand is delayed (to be accomplished sometime before the
statement completes execution)
e.g.

float a = 6 * 4 + 4 * 2;
float a = 6 * (4+4) * 2;

// answer is 32
// answer is 96

// expression is incomprehensible
float a = b+c * 2/d + 3 + b/c + d - b *c/d;
// same as
float a = b + ((c*2)/d)+3)+(b/c)+d)-((b*c)/d);
Name
Description of
Argument
Computation
abs
The absolute value of double/integer
the argument
exp
The value of e(2.71828) double/integer
raised to the power of
the argument
log
The logarithm (to the double/integer
base e) of the argument
sqrt
The positive square root double/integer
of the argument
(positive)
pow
pow(x, y) raises x to y
double
atan
The arc tangent of the double/integer
argument
cos
The cosine of the double/integer
argument
sin
The
sine
of
the double/integer
argument

Result
same
argument
double

as

double
double
double
double (radians)
double (radians)
double (radians)

Table 2.5: Some mathematical functions


Note: You could only use these mathematical functions if you would include the library <math.h>

2.4. I/O Statements


2.4.1. Input Statements
Information cannot be manipulated by a computer unless it is first stored in memory. There are 3
ways to place a data value in memory. These are through any of the following:
1. constant declaration
2. assignment statement; or
3. reading from an input device into the memory
Cin:The first two ways can be done using the equals sign or using #define statement as in the case
of constants. To store different information each run, it must be read in as the program executes
using a cin statement. As mentioned in chapter 1 it cin needs the >> or extraction operator to get the
data from keyboard.
syntax:

12

cin >> variablename ;


e.g. cin >> age;
cin
>>
variablename
>>
anothervariable
e.g. cin >> rate >> discount ;

Gets statement: Gets statement is found in the <stdio.h> library. It collects a string of characters
terminated by a new line from the standard input stream and puts it into s. The new line is replaced by a
null character (\0) in s.
example:

char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);

Getchar() and Getche():This macros are found in stdio and conio.h libraries. They are designed to
capture single characters from the standard input stream except for the follow differences:
getchar():getchar reads from stdin and is line buffered; this means that it will not return until the user
press ENTER.
getche() gets character from the keyboard, echoes to screen.Reads a single character from the
keyboard and echoes it to the current text window and returns the character read from the keyboard.

2.4.2. Output statements


Output statement is used to print values to the console. There are two useful output statements
available: cout and printf(found in the iostream.h and stdio.h library respectively)
Note: libraries must be placed in the header using the include statement.
Cout: This is the standard output statement for C++. It would need the << (insertion) operator
which place the data in the source code to the monitor.
syntax:
cout << expression;

e.g.
cout << age;
cout << This is a simple text output;
cout << expression << expressions

e.g.
cout<<x is equals to <<x;
cout<<100+100\n<<(100+100);

Printf: (found in the stdio.h library) is useful for format specification which is not found in cout.
The format specification feature uses % symbol as format specifiers
syntax:
printf(string_expression, variablenames);

Example
printf(my name is %s, name)
printf(your age is \n %d, age);
printf(%s %s, firstname, lastname);

of
the
must correspond to the number of variablenames.

Note that the number


format specifiers in
string_expression

List of useful format specifiers


%s
used for string
13

%d
%o
%f
%0.2f
%x

used for decimal integer number


used for octal integer number
used for floating point value
used for floating point value with 2 decimal place
used for hexadecimal number

examples
printf(" %d\n%o\n%x", 255, 255, 255);
printf(" Interest = %0.2f", x);
printf(vital statistics %d \t%d \t %d", 36, 24,
64);
printf("%s %d years old", "VSU, 83);

Puts:

Puts
statement
copies
the
nullterminated string s to the standard output stream stdout and appends a newline character.
Example:
char string[] = "This is an example output string\n";
puts(string);

2.5. Some useful functions


2.5.1. Setprecision() Function
In most programs, especially business programs, numeric output is displayed either with no
decimal place or two decimal places. Rarely does a program require numbers to be displayed with six
decimal places. You can use a set precision stream manipulator to control the number of decimal
places that appear when a floating point number is displayed. To use setprecision manipulator, you
must include <iomanip.h>.
Syntax: cout<<setprecision (number of digits to display);
e.g. double X=11.2342;
cout <<setprecision (4);//displays 11.23
cout<<X<<endl;

2.5.2. gotoxy() Function


The gotoxy function moves the cursor to the given position in the current text window. If the
coordinates are in any way invalid the call to gotoxy is ignored. An example of this is a call to
gotoxy(40,30) when (35,25) is the bottom right position in the window. The gotoxy function is found in
the <conio.h> library
Note: Do not use this function for Win32s or Win32 GUI applications. 0, 0 coordinates are invalid
Syntax: gotoxy(x, y);
Where in X is the desired column number, from 1 to 80, and Y is the desired line number, from 1 to 25.
e.g. gotoxy(40, 12); // moves the cursor to the center of the screen.
2.5.3. clrscr() Function
clrscr function (found in conio.h library) clears the text-mode window and places
upper left corner (at position 1,1). Simply place the function clrscr();

the cursor in the

2.6. The Turbo C++ IDE


We will be using Turbo C++ for Windows (TC++4.5) which comes with an integrated
development environment (IDE) that allows users to edit, compile, run and debug programs
without having to go back to the DOS prompt. When invoked, the IDE startup will be displayed
which contains, at the top of the screen, the main menu, and at the bottom line the status bar.
The main menu offers ten choices: File, Edit, Search, Run, Compile, Options, Window and
Help. To select an item from this menu, one can simply click on the item with the left button of
the mouse, or, press F10 and the arrow keys to highlight the item desired and press <ENTER>,
or press <Alt> and the first letter of the item. A submenu, corresponding to the item selected will
then be displayed and the user can further select the option desired.
The status bar keeps the user informed about the various options at any given time. Most of the
time, it contains hot keys, or shortcuts to menu items. Some of the hot keys for the standard
screens are given in Table below.
14

The rest of the screen is the desktop , which contains one or more windows. One of them is the
active window which most commands act upon. Whenever one types in a character, it goes into
the active window. Each window in the desktop is a work area, either for editing a file, watching
debug information, or examining the output area. The window that appears in the initial screen
is an editor window for the file NONAME1.cpp. Inside this window, one can enter all the text for
a C++ program. Some of the commonly used hot keys in the editor window are given in
------------------------------------------------------------------------------------------------------------------Hot Key
Equivalent Menu Option
Description
------------------------------------------------------------------------------------------------------------------F1
Help| Help
Display the help screen
Alt-F9
Compile | Compile
Compile program in the active window
Ctrl-F9
Run | Run
Execute program in the active window
Alt-X
File | Exit
Exit Turbo C++
---------------------------------------------------------------------------------------------------------------Table 2.6: Commonly Used Hot Keys on the Standard Screen
---------------------------------------------------------------------------------------------------------------Hot Key
Function
---------------------------------------------------------------------------------------------------------------Ctrl-KB
mark the start of a block
Ctrl-KK
mark the end of a block
Ctrl-KC
copy a highlighted block
Ctrl-KH
unhighlight a block
Ctrl-QY
delete characters starting from cursor position up to the end of the line
Ctrl-Y
delete the whole line
Ctrl-KY
delete a block
Ctrl-KW
write block to a file
Ctrl-KR
insert a file
---------------------------------------------------------------------------------------------------------------Table 2.7: Commonly Used Hot Keys on the Window Editor

Chapter 3
Program Control Structures
3.1.

Introduction to Selection Structures


In the previous chapter, the programs that you are creating is built from a sequence programming
structure only, where the program instructions are processed, one after the another, in the order in which
each appears in the program. In many programs, however, the next instruction processed depends on the
result of a decision or comparison that the program must make. Take for example an employee, the basis
in which s/he would receive an overtime pay depends if s/he has more than 8 hours of work. Therefore
based on the comparison if s/he exceeds 8 hours of work, then one path must be selected (either true or
false) and an answer would depend of the selected path. You may use selection structure or decision
structure, when you want a program to make a decision or comparison on then select one of two paths,
depending on the result of that decision or comparison. Although the concept of selection structure is
quite new, yet in most of our daily lives we are performing these tasks, take for example the shown in
the figure below
If (hungry)
Eat meal
Eat snacks

If (there is an exam tomorrow)


Study lessons
Otherwise
Watch movie

Figure 3.1
In the example above, the portion enclosed in a parenthesis is called the condition, which
specifies the decision you are making and is phrased so that it results in either true or false only.
Like you, the computer also can evaluate a condition and then select the appropriate task to perform
based on that evaluation. When using the selection structure, the programmer must be sure to phrase the
condition so that it results in either true or false only. The programmer also must specify the tasks to be
performed when a condition is true, or if necessary if the condition is false. Most programming language
offers three forms of selection structure, the if, if/else, and the switch (also called case).

3.2.

if/else Conditional Statement


An if selection structure contains only one set of instructions, which are processed when the
condition is true. An if/else selection structure, on the other hand contains sets of instructions; one
15

set is processed when the condition is true and the other set is processed when the condition is false.
Written in the figure below is an example of a pseudocode for an if and if/else statement.
If selection structure:
1. Enter the product serial number and price
2. If (the serial number is equal to 39301)
Calculate the price by multiplying the price by 1.2
Display Product price has increased
End if
3. Display the serial number and price
If/else selection structure:
1. Enter Sales amount
2. If (the amount is greater than 1500)
Calculate the commission by multiplying the sales amount by .02
Else
Calculate the commission by multiplying the sales amount by .01
End if
3. Display the commission

Figure 3.2
In the example shown above, the instruction that is following a condition is known as the true
path. The true path ends when you come to the else or, if there is no else, when it come to the end of
the selection structure. The false path depends on whether the selection structure contains an else
statement, if there is no else statement then it would automatically go to the end of the selection
structure, but is an else exist, it would process the contents of that statement. The flowchart on figure
below would further illustrate the selection structure psuedocode.
if selection structure

if/Else selection structure


Start

Start

Enter the sales


Enter the serial number and price

Sales>1500

Part number is 39301


Price =price*1.2
Commission =sales*.01

Commission =sales*.02

Display the commission


Display Price increase message

Stop
Display Serial number and price

Stop

Figure 3.3

16

In C++, you can use the if statement to code if and if/else forms selection structure. The syntax of
an if and else if statement is shown below.
//this is for if statement
if (boolean_expression){
statements;
}
//this statement is for if/else
or

if (boolean_expression){
statements;
} else {
statements;
}

Note: { } (Open and close bracket) is optional, for single statements you may not use the { }
3.2.1. Comparison Operators
Comparison operators are often referred as relational operators The figure below shows the precedence of these
operators. The precedence numbers indicate the order in which the computer performs the comparisons in C++
expression. Comparisons of precedence 1 are performed first; 2 second, but a parenthesis overrides the order of
precedence.
Operator
<
<=
>
>=
==
!=

Operation
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to

Precedence number
1
1
1
1
2
3

Figure 3.4
Examples:

int quality, age, onHand, target;


(quality<50)
(age>=25)
(onHand == target)
(quality!= 7500)
In the first example, if (quality<50),evaluates to true when the quality is lesser than 50,
otherwise it returns false. In the second example, if (age>=25)the contents of the age variable if it is greater
if
if
if
if

than or equal to 25, then the if statement would evaluate true, otherwise, it evaluates false. The third example,
if (onHand == target),would evaluate a true if both onHand and target variables are equal,
otherwise it evaluates false. The fourth if (quality!= 7500), would compare quality and 7500 and
evaluate true if quality is not equal to 7500, if they are equal then it would evaluate false.
It is easy to confuse the equality operator (= =) with the assignment statement operator (=). Please take
note that the equality operator would compare 2 values and determine which whether they are equal, on the
other hand the assignment operator would assign a value to a memory location.

3.2.2. Logical Operators


Logical operators allow you to combine two or more conditions into the compound condition. Logical
operators are sometimes called as Boolean operators, because the compound condition in which they are
contained always evaluates to either true or false only. The figure below shows the summary of the
logical operators.
Operator
Operation
Precedence Number
And (&&) All conditions connected by the And operator must 1
be true for the compound condition to be true
Or (| |)
Only one of the conditions connected by the Or
2
operator needs to be true for the compound
condition to be true.
Figure 3.5
17

For example:
int quantity, age;
float price;

if (quantity>0 && quality <50)


if (age<21 | | age>55)
if (quantity <100 && price <10.35)

The first if statement would determine whether the number of stored in the quantity variable is
greater than zero and, at the same time, less than 50. When the number falls within range, the compound
condition evaluates to true, otherwise it evaluates false. In the second example, the condition compare
the age variable with the numbers 21 and 55, the compound condition evaluates true when the number
stored in the age variable is either less than 21 or greater than 55, otherwise it evaluates false. The third
example compare the contents of the quantity with the number 100 and the price with the number
10.35. The compound condition evaluates to true when the quantity variables value is less than 100
and, at the same time, the price variable is less than 10.35, otherwise it would be false. The truth table
below summarizes on how the computer evaluates logic expressions.
Logical AND (&&) truth table
Left hand expression
Right hand expression
Truth value of expression
1 (true)
1 (true)
1 (true)
1 (true)
0 (false)
0 (false)
0 (false)
1 (true)
0 (false)
0 (false)
0 (false)
0 (false)
Figure 3.6
Logical OR (||) truth table
Left hand expression
Right hand expression
Truth value of expression
1 (true)
1 (true)
1 (true)
1 (true)
0 (false)
1 (true)
0 (false)
1 (true)
1 (true)
0 (false)
0 (false)
0 (false)
Figure 3.7
When you use the && (And) operator to combine two condition in C++ expression, the computer does
not evaluate the second condition when the first condition is false. Because the && statements needs all
of the statements to be true. On the other hand the, when the | | (Or) operator is used to combine two
conditions, the computer does not evaluate the second condition if the first condition is true. Because
only one of the conditions combined with the | | operator needs to be true for the compound for the
condition to be true. Thus the concept of evaluating condition 2 based on the result of condition 1 is
referred to as short circuit evaluation.

3.3.

Nested if/else Statements


When either a selection structures true path or its false path contains another selection structure, the
inner selection structure is referred to as nested selection structure, because it is contained (nested)
within the outer selection structure. You use nested selection structure when more than one decision
must be made before the appropriate action is taken. For example, assume you want to create a program
that determines voter eligibility and displays one of three messages as follows:
Message
Criteria
You are too young to vote
Person is younger than 18yrs old
You can vote
Person is at least 18 yrs old and is a registered
voter
You must register before you can vote
Person is at least 18 yrs old but is not registered to
vote.
You can think of the decision regarding the age as the primary decision and the decision regarding the
registration status as the secondary decision. The primary decision is made by the outer selection
structure, and the secondary decision in the inner selection structure. The pseudocode and flowchart are
show in the figure below
Pseudocode:
1. Enter the age
2. If(the age is greater than or equal to 18)
Enter the registration status
If (the registration status is Y)
Display You can vote. message
Else You must register before you can vote. message
End if
Else
Display You are too young to vote message
18

End if

Flowchart

Start

Enter Age

Age less than 18

Display You are too young to vote

Enter Registration status

Registration status is Y
F

Display You must register before you can vote

Display You can vote

Stop

Figure 3.8
The source code below is the C++ implementation of the flowchart above.
#include <iostream.h>
#include <ctype.h>
int main()
{
int age=0;
cout<<"Enter your age: ";
cin>>age;
if (age>=18)

19

char registered = ' ';


cout<<"Are you registered to vote? (Y/N): ";
cin>>registered;
if (toupper(registered)=='Y')
cout<<"You can vote: "<<endl;
else
cout<<"You must register before you can vote."<<endl;
//end if
}
else
cout<<"You are too young to vote."<<endl;
//end if
return 0;
}

3.4.

Multiple Paths Selection Structure


At times, you may need to create a selection structure that can choose from several alternatives. Such
selection structures are commonly referred to as multiple-path selection structure or extended selection
structure. Example you are tasked to create a program that would test the valid grades and their
corresponding messages shown in the chart below.
Letter Grade Message
A
Excellent
B
Above Average
C
Average
D
Below Average
E
Below Average
3.4.1. Using if/else Statements
Using the if/else statement it can be accomplished by
#include <conio.h>
#include <ctype.h>
#include <iostream.h>
int main()
{
char grade = ' ';
cout<<"Letter Grade: ";
cin>>grade;
grade=toupper(grade);
//Enter input items
if (grade=='A')
cout<<"Excellent"<<endl;
else if(grade=='B')
cout<<"Above
Average"<<endl;
else if (grade=='C')
cout<<"Average"<<endl;
else if (grade=='D' || grade=='F')
cout<<"Below
Average"<<endl;
else
cout<<"Input Error";
//end ifs
//end main function
getch();
}
3.4.2. Using Switch Statements
In addition to using if/else form to create multiple paths you can also use the switch forms.
In situations where the selection structure has many paths from which to choose, it is often
simpler and clearer to use the switch from the selection structure rather than the if/else
form. The pseudocode and the flowchart for the Letter grade problem are shown below.
Pseudocode:
1. Enter Grade
2. Grade value
A
display Excellent
B
display Above Average
20

C
D,F
Other
Flowchart

display Average
display Below Average
display Error
Start

Enter Grade

grade

D, E

Other

C
Display
Excellent

Display Above Average


Display
Average

Display Below Average


Display
Error

Stop

Figure 3.9
In C++, you use the switch statement to code the switch form of the selection structure. The syntax is
shown below.
switch (selectorExpression)
{
case value1:
one or more statements
case value2:
one or more statements
case value3:
one or more statements
case value4:
one or more statements
[default:
One or more statements
match any of the values]
}
//end switch

[break;]
[break;]
[break;]
[break;]
processed when the selectorExpression does not

The switch statement starts and with open braces and end with open braces. The selector
expression in enclosed in parenthesis can contain any combination of variables, constants, functions, and
operators, as long as the combination results to whose data type is char, short, int, or long. Notice that
there are individual case clauses within a switch statement contains a value followed by a colon. The
value can be literal constant, a named constant or an expression composed of either literal or named
constant. The data type of value should be compatible with the data type of the selectorExpression.
The break statement tells the computer to leave (break out of) the switch statement at that
point. If you do not use the break statement to leave the switch statement, the computer continues to
process the remaining in the switch statement.
#include <iostream.h>
#include <ctype.h>
int main()
{
char grade = ' ';
cout<<"Letter Grade: ";
cin>>grade;
grade=toupper(grade);
//Enter input items
switch (grade)
{
case 'A':
cout<<"Excellent"<<endl;
break;
case 'B':
cout<<"Above Average"<<endl;
break;
case 'C':
cout<<"Average"<<endl;

21

break;
case 'D':
case 'F':
cout<<"Below Average"<<endl;
break;
default:
cout<<"Input error"<<endl;
}//end switch
return 0;
//end main function
}

3.5.

Introduction to Repetition Structure


Programmers use the repetition structure, referred to more simply as a loop, to repeatedly process one or
more program instructions until some condition is met. For example, you may want to process the
instructions to calculate the net pay for each employee in the company. As with the sequence and
selection structure, you already are familiar with repetition structure, example: gulp the water until
thirst is quenched.
A repetition structure can either be pretest and posttest loop. In a pretest loop the evaluation occurs
before the instructions within the loop are processed. In a posttest loop, the evaluation occurs after the
instructions within the loop are processed. The instruction in a posttest loop will be processed at least
once. Of the two types, the pretest loops is the most commonly used.

3.6.

Pretest Loops
In a pretest loop, the loop condition appears at the beginning of the loop and determines the number of
times the instructions within the loop are processed. The instructions within the loop are referred to as
the loop body. Similar to a selection structure condition, a loop condition must result in either true of
false only. The flowchart of a pretest loop is shown below. Some loops, require the user to enter a
special value to end the loop. Values that are used to end loops are referred to as sentinel values.
3.6.1. Using while Statement
The syntax of a while statement and flowchart are shown below:
while (boolean_expression) {

Statement/s, to be processed as long as the loop condition is true.

}
While expression

Example:
int age=0;
cout<<"Enter age: ";
cin>>age;
while (age>0)
{
cout<<"Age:"<<age<< endl;
cout<< "Enter age:";
cin>> age;
}//end while

T
Statements

In this example, the while (age>0) clause tells the computer to repeat the loop body instructions as
long as (or while) the value of the age variable is greater than zero.
3.6.2. Accumulators and Counters for Loop Control
In most loops a counter is a numeric variable used for counting something. While an accumulator is a
numeric variable used for accumulating (adding together) something. Two tasks are associated with
counter and accumulators, initializing and updating. Initializing means to assign a beginning value to
the counter or accumulator variable. Typically, counter and accumulator variables are initialized to zero.
However, they can be initialized to any formed before the loop is processed, because it needs to be
performed only once. Updating also called incrementing means adding a number to the value stored in
the counter or accumulator. The number can either be positive or negative, integer or non-integer. A
counter is always incremented by a constant value-whereas an accumulator is incremented by a value
that varies. The assignment statements that updates a counter or an accumulator is placed within the loop
in a program, because the update task must be performed each time the loop instruction are processed.
See the example below
int salesMan=0;
float totalSales=0.0;
int sales=0;

while (sales>=0.0)
{
salesMan=salesMan+1;
totalSales=totalSales + sales;
cout<< "Next sales amount: ";
cin>> sales;
}//end while

// a counter
//an accumulator

22

The program above illustrates that as long as the sales is a non-negative number, the number of
salesMan would increase by 1 and the totalSales would accumulate each time a non negative sales
is made
Another use of a counter is to control the loop operation, see the example below:
int salesMan=0;
float totalSales=0.0;
int sales=0;

while (salesMan<5)
{
cout<< "Next sales amount: ";
cin>> sales;
salesMan=salesMan+1;
totalSales=totalSales + sales;
}//end while

// a counter
//an accumulator

In this code snippet, this indicates that the number loop would depend on the number of salesMan that
would key in their sales, in this case only 5 salesMan are allowed.

3.6.3. Using for Statement


The most common use for the for statement is to code pretest loops whose processing is
controlled by a counter. This is because the for statement provides a more compact way of writing that
type of loop. The syntax, flowchart and an example is shown below.
for (initialization; condition; update) {
statement/s;
}

Example:
int salesMan=0;
float totalSales=0.0;
int sales=0;

for (salesMan=0;salesMan<5;salesMan++)
{
cout<< "Next sales amount: ";
cin>> sales;
totalSales=totalSales + sales;
}

This example has similar logic to the example in a counter controlled loop using while, but as you can
see the entire loop statement is one line lesser than the while counterpart.

3.7.

Posttest Loops
As is true of the condition in a pretest loop, the condition in a posttest loop is evaluated with each
repetition, or iteration, of the loop. However, unlike the evaluation in a pretest loop, the evaluation in a
posttest loop occurs after the instructions within the loop are processed, rather than before the instruction
are processed.

3.7.1. Using do while Statement


Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of statement/s
even if condition of true is never fulfilled. See the syntax below.
do{

statement/s

} while (Boolean_expression)

23

Statements

For example:
int salesMan=0;
float totalSales=0.0;
int sales=0;

do
{
cout<< "Next sales amount: ";
cin>> sales;
salesMan=salesMan+1;
// a counter
totalSales=totalSales + sales;
//an accumulator

While expression

}while (salesMan<5); //end while

This operates on a similar way the while loop operates in the example on counter controlled loop, but if
we would have salesMan<0, the loop would still execute once.

3.8.

Nested Loops
A nested repetition structure, one loop (referred to as the inner loop) is placed entirely within another
loop (called the outer loop). Although the idea of nested loops may sound confusing, you already are
familiar with the concept. Such as a clock, for instance uses nested loops to keep track of the time.
Consider that the second hand of the clock being the inner loop and the minute hand as the outer loop.
We all know that in order to move minute hand into one position the second hand should move 60
position, then the second hand begin its journey once again. Example
int salesMan=0;
float totalSales=0.0;
int sales=0;
int region=0

while (region<3)
{
region=region+1;
cout<<"Enter Sales for region" <<region<<":";
for (salesMan=0;salesMan<10;salesMan++)
{
totalSales=totalSales + sales;
cout<< "Next sales amount: ";
cin>> sales;
}//end for
}//end while

This is a modified example in the example found in pretest for statement. The added items is that when
there are many regional sales group and each region has 10 salesMan, so to accommodate this
needed problem a nested while and for statement accomplishes the task.

Chapter 4
Functions
5.1.

Introduction to Functions

A function is a block of code that performs a task. Every C++ program contains at least one function
main() and most contain many more. Programmers use function for two reasons, First, function allows
programmer to avoid duplicating code in different parts of a program. If different sections of a program need to
perform the same task, it is more efficient to enter the appropriate code once, in a function, and then call the
function to perform its task when needed. Second, functions allow large and complex programs, which typically
are written by a team of programmers, to be broken into small and manageable task. Each member of the team
can be assigned one of the tasks to code as a function. Typically, the main() function is the program responsible
for calling (or invoking) each of the other function when needed; however, any function can call another
function.

5.2.

Predefined Functions

C++ comes with libraries of predefined functions that you can use in your programs.
There are two kinds of functions in C++: functions that return (produce) a value and
functions that do not return a value. Functions that do not return a value are called Void
functions. Always include the specific libraries which contain the function/s so that your
program would not be erroneous.

5.2.1. Value returning functions


24

We will use the sqrt function to illustrate how you use a predefined function that returns
a value. The sqrt function calculates the square root of a number. The function sqrt starts
with a number, such as 9.0, and computes its square root, in this case 3.0.The value the
function starts out with is called its argument . The value it computes is called the
value returned. Some functions may have more than one argument, but no function
has more than one value returned.
Syntax:
Function_Name(Argument_List)
Where the Argument_List is a comma-separated list of arguments:
Argument_Last)

(Argument_1, Argument_2,. . .,

Example:
side=sqrt (area);
cout << "2 to the power 3 is "<<pow(2,3);

5.2.2. Void functions


A void function performs some action, but does not return a value. Since it
performs an action, a void function invocation is a statement. The function call for a void
function is written similar to a function call for a function that returns a value, except
that it is terminated with a semicolon and is used as a statement rather than as an
expression. Predefined void functions are handled in the same way as predefined
functions that return a value. Thus, to use a predefined void function, your program must
have an include directive that gives the name of the library that defines the function.
Syntax:
Function_Name(Argument_List if any)
Where the Argument_List is a comma-separated list of arguments:
Argument_Last)
Example:
clrscr();
gotoxy(argument1, argument2);

5.3.

(Argument_1, Argument_2,. . .,

User 0-Defined Functions

The function that the user would create are referred to as value user defined functions. The syntax is
shown below
Syntax:
returnDataType Function_Name(parameter_List) {statements}

Wherein:
returnDataType: is the data type specifier of the data returned by the function. Note that void returns
nothing
function_name: is the identifier by which it will be possible to call the function. The rules for naming
functions are the same as for naming variables, however, it is a common practice to begin a function
name with a verb.
parameter_list: (or also known a formal parameters) store the information passed to the function when
the function is invoked (called)
statements: (or also known as function body) consists of declarations and executable
statements enclosed within a pair of braces. When the function is called, the
argument values are plugged in for the formal parameters, and then the
statements in the body are executed. The value returned by the function is
determined when the function executes a return statement.
Most C++ implementation require definition of function prototypes at the declaration section.
Function prototypes are simple function declaration without a block. You usually place function
prototypes at the beginning of a program, after the #include directives. It may help to think of function
prototypes of a program being similar to the table contents in a book. Creating function prototypes are
standard programming practice.
Example:
float average(int a, int b);
void main()
{
int x,y;
cout<<Enter first number: ;
cin>>x;
25

cout<<Enter second number: ;


cin>>y;
cout<<Average is: <<average(x,y);
}
float average(int a, int b)
{
return ((a+b)/2);
}

5.4.

Passing Parameters

The parameter allows the programmer to send values to the function for its internal operations. When
you call the function the parameters passed are called actual parameters. When the function starts executing the
actual parameter are placed in its parameter block. This is called the formal parameters.
int addition (int a, int b){
Formal Parameters

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

void main (){


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

Actual parameters

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:

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 this case, main)
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.
5.4.1. Pass by Value
Value Parameters are those parameters follows the standard variable declared like the example
above. When this type of parameter is used, changes made to the values of the variables within the
functions are not reflected in the calling program or function. The changes are temporary because
temporary copies of the variables are made in the memory and the copies are used while the function is in
execution. Think of it as passing copies of the contents of a container to a function, the function uses a
different container. Any changes to this copy will not affect the original.

26

5.4.2. Pass by Reference


Reference parameters are those parameters whose datatype are succeeded by & - meaning the
address is passed. When this type of parameter is used, changes that were made to the variables within
the procedure remain even after the procedure has ended. These changes are permanent because C++
passes to the function not the copies of variables' values but the variables' addresses in the memory.
Think of it as passing the container itself to the function. Any changes inside the container always
remain the same.
Example:
void duplicate (int& a, int& b, int& c){
a=a*2;
b=b*2;
c=c*2;
}
void main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
}

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 will have an effect in their counterpart variables passed as arguments in the call to the
function.

5.4.3. Pass by Constant


Constant Parameters combine the benefit of Reference Parameters by address sharing and value
parameter by disallowing changes to its contents. A constant parameter is declared in the parameter list by
preceeding the datatype with the word by const. Think of it as passing the container itself to a function but
the container is marked as sealed, so that its contents cannot be changed.
Example
void display(const int x){
cout<<x;
}
void main(){
int a = 10;
display(a);
}

To avoid programming errors, the following rules for parameter list correspondence are given:

5.5.

There must be the same number of actual parameters or formal parameters.


The type of each actual parameter must match the type of its corresponding formal parameter.
An actual parameter corresponding to a variable formal parameter must be a variable. An actual
parameter corresponding to a value parameter may be a variable, constant or expression.

Scope and Lifetime of a Variable


A variables scope indicates where in the program the variable is used; the scope can either be local or
global. A variables lifetime on the other hand, indicates how long the variable remains in the computers
internal memory. The scope and lifetime typically are determined by where you declare the variable in
the program. Variables declared within a function, and those that appear in a functions parameterList,
have a local scope and are referred to as local variables. Local variables remain in the computers
internal memory until the function ends. Unlike local variables, global variables are declared outside of
any function in the program, and they remain in memory until the program ends. Declaring a variable as
global rather than local allows unintentional errors to occur when a function that should not have access
to the variable inadvertently changes the variables contents.
Example:
double z=0.0;
double sumsqr(int x)
{

Global variable

27

Local variable

int y=0;
double tss=0;
while(y<5)
{
tss=tss+(x*x);
y++;
}
return tss;
}

int main()
{
int x=0;
cout<<"Enter a positive integer: ";
cin>>x;
z= sumsqr(x);
cout<<"The sum of square is: "<<z;
return 0;
}

Chapter 5
Arrays
5.1.Introduction to Arrays
All of the other variables you have used so far have been simple variable. A simple variable also called
a scalar variable is one that is unrelated to any other variable in the computers internal memory. In
many programs, however you may reserve a block of variables, referred to as an array. An array is a
group of variables that have the same name and data type and are related in some way. Each variable in
the array might contain inventory quantity, or might contain a state name, or each might contain an
employee record. It might be helpful to the boxes and you can read information from the boxes, you
just cannot see the boxes. Programmers use arrays to temporarily store related data in the internal
memory of the computer.

5.2.One Dimensional Arrays


You can visualize a one-dimensional array as a column of variables. A unique number called a
subscript identifies each variable in a one dimensional array. The computer assigns the subscript to the
array variables when the array is created. The subscript indicates the variables position in the array. The
first variable in a one dimensional array is assigned a subscript of 0, the second a subscript of 1, and so on.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:
Syntax:
dataType arrayName [numberOfElements];
dataType:is the type of
store.
arrayName:is the syntax
array
numberOfElements: is an
words, it specifies the

data the array variables, referred to as elements will


name of the array, you use the same rules for naming an
integer that specifies the size of the array. In other
number elements you want in array. Notice that you enclose the
brackets([]) and the number you specify must be a constant value, since

numberOfElements in square
arrays are blocks of non-dynamic memory whose size must be determined before execution.

5.2.1. Initializing the values of an array


When declaring a regular array of local scope (within a function, for example), if we do not specify
otherwise, its elements will not be initialized to any value by default, so their content will be undetermined
until we store some value in them. The elements of global and static arrays, on the other hand, are
automatically initialized with their default values, which for all fundamental types this means they are
filled with zeros.
In both cases, local and global, when we declare an array, we have to assign initial values to each one of its
elements by enclosing the values in braces { }. For example:
int number [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:


number[0]=16;
number[1]=2;
number[2]=77;
number[3]=40;
number[4]=12071;

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty []. In this case, the compiler will assume a size for the array that matches the number of
values included between braces { }:
28

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

After this declaration, array number would be 5 ints long, since we have provided 5 initialization values.
number [0]
16

number [1]
2

number [2]
77

number [3]
40

number [4]
12071

Strings are considered arrays because it is composed of individual character grouped together hence
array initialized with strings are perfectly ok.
5.2.2. Accessing and Manipulating Data in a one Dimensional 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 syntax is:
name[index]
For example, to store the value 75 in the third element of number, we could write the following statement:
number[2] = 75;
and, for example, to pass the value of the third element of number to a variable called a, we could write:
a = number[2];
Therefore, the expression number[2] is for all purposes like a variable of type int.
At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to
arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second
one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with
arrays.
int number[5];
number[2] = 75;

// declaration of a new array


// access to an element of the array.

If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never
precedes an access.
Some other valid operations with arrays:
number[0] = a;
number[a] = 75;
b = number [a+2];
number[number[a]] = number[2] + 5;

Example:
// array example - that would calculate
//the summation of all value in an array
#include <iostream.h>
int number [5] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result = result + number[n];
}
cout << result;
return 0;
}

5.2.3. Passing Data in a One Dimensional Array to a function


At times you may need to pass one-dimensional array to a function. As you know, data can be
passed to a function either by value or by reference. Recall that, unless specified otherwise, scalar
variables in C+ + are passed by value. To pass a scalar variable by reference in C++, you need to
include the address-of(&) operator in the receiving functions prototype. Unlike scalar variables,
arrays in C++ are automatically passed by reference rather than pass by value. Passing an array by
reference is more efficient than passing by value. Because many arrays are large, passing an array
by value would consume a great deal of the computers memory and time; this is because the
computer would need to duplicate the array in the receiving functions formal parameters. When
you pass an array to a function, the computer passes the address of only the first array element.
Because array elements are stored in contiguous locations in the memory the receiving function
needs to only know where the first element is located; form there, the function can easily locate the
other elements. Because arrays are passed automatically by reference, you do not include the
address-of (&) operator before the formal parameters name in the function header, as you do when
passing scalar variables by reference.
29

To pass an array to a function, you need to simply enter the data type and name of the formal
parameter, followed by an empty set of square brackets in the receiving functions header. You also
enter the data type and an empty set of square brackets in the receiving function s prototype.
Example:
// array example that would pass an array to
a //function using pass by reference and locate the
//largest variable
#include <iostream.h>
int getLarge(int number[]);
void main ()
{
int number [5] = {16, 2, 77, 40, 12071};
cout<<getLarge(number);
}
int getLarge(int number[])
{ int large=number[0];
for ( int n=0 ; n<5 ; n++ )
{
if (large<number[n])
large=number[n];
}
return large;
}

5.3.Two Dimensional Arrays


A two dimensional array, on the other hand, resembles a table in that the variables are in rows and
columns. Each variable (element) is a two dimensional array is identified by a unique combination of
two subscripts, which the computer assigns to the variable when the array is created. The subscripts
specify the variables row and column position in the array. Variables located in the first row in a twodimensional array are assigned a tow subscript 0 (zero). Variables located in the second row are
assigned a column subscript of 1, and so on. You refer each variable in a two-dimensional array by the
arrays name and the variables row and column subscript. The syntax for declaring a 2 dimensional
array is as follows:
dataType arrayName [numberOfRows] [numberOfColumns];

To determine the number of elements in a two-dimensional array, you simply multiply the number of
rows by the number of columns. You can initialize the array elements in a two-dimensional array by
entering a separate initial values separated in braces, for each row in the array. If the array has two
rows , then the statement that declares and initializes the array can have a maximum of two initial
values section.
Example
int nums [2][4]= {{1,2,3,4},{5,6,7,8}}
int nums1 [2][4]= {0}
int nums2 [2][4]= {{0},{1}}
//the first declaration initializes the array
column 0 //with 1-4 and column 1 with 5-8
//initializes columns 0&1 with 0
//initializes column 0 with 0 and column 1 with 1
5.3.1. Storing & Accessing Data in Two Dimensional Array
As with one-dimensional arrays, you generally use an assignment statement to enter data into a
two-dimensional array. The syntax is dataType
arrayName
[RowsSubscript]
[ColumnsSubscript], is the name of and subscript of the array variable to which
you want the value(data) assigned. In addition to showing the syntax, you can
use two loops to access every element in a two dimensional array. One of the
loops keeps track of the row subscript, while the other loop keeps track of the
column subscript. Examine the example below:

int nums [2][4];


for (int row=0;row<2;row++)
{
30

for (int col=0;col<4;col++)


{
cout<<Enter values for the array:
;
cin>>nums[row] [col];
}//end col
}//end row
In addition to using an assignment statement to enter data into a two-dimensional
array, you can also use the extraction operator (cout<<) to display the values
inside the array[row][col]. Examine the example below:

int nums [2][4];


for (int row=0;row<2;row++)
{
for (int col=0;col<4;col++)
{
cout<<The values on the array are: ;
cin>>nums[row] [col];
cout<<,;

}//end col
cout<<endl;
}//end row

31

You might also like