Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Programming in C++

1.0 Introduction
C++ is a cross-platform language that can be used to create high-performance
applications. C++ was developed as an extension to the C language. C++ gives
programmers a high level of control over system resources and memory.
C++ has borrowed many features from other programming language particularly from C.
Programmers argue that C++ is an extension of C, providing more and powerful
programming techniques. It introduces Object Oriented concepts over C programming
language. Structured programming concepts found in C are found in a more powerful
form in C++. Such features include: function overloading, single line comment and
function template. Generally, Programming in C++ improves productivity of the
programmer.

1.1 Moving from C to C++


In C Programming language, the standard library function printf() statement sends
the output to the standard output device, the console. The function body consists of
statements for creating data storage called local variables and executable statements.
Note that local variables in main() are not visible by any other function. Recall the
traditional C programme called Hello World, in example 1.1.

Example 1.1
#include<stdio.h>
main( )
{
printf(“Hello World”);
}

Running the program it outputs the statement:


Hello World
However, the program could be rewritten using C++ streams. The C++ equivalent of the
Hello World program is listed in example 1.2

Example 1.2
#include <iostream.h>
int main()
{

cout << “Hello World”;


}

Running the program it outputs the statement:


Hello World
The header file iostream.h supports streams programming features by including
predefined stream objects.
1
The character “<<” is called the C++ stream insertion operator. It sends the message
“Hello World” to the predefined console object cout, which in turn prints on the
console. The Hello World program in example 1.2 is again shown below for the purpose
of discussion.

1. #include <iostrem.h> preprocessor directive


2. main() function declarator
3. { beginning of the program
4. cout << “Hello World”; body of the function main
5. } end of the program

Various components of the program hello.cpp, shown above, are interpreted as


follows:

First Line: Preprocessor Directive


The first line is a preprocessor directive. The preprocessor directive
#include<iostream.h> includes all the statements of the header file
iostream.h. It contains instructions and predefined constants that will be used in the
program. It plays a role similar to that of the header file stdio.h of C.
Second Line: Function Declarator
The second line in the program is
main()

Similar to a C program, the C++ program also consists of a set of functions. Every C++
program must have one function with name main, from where the execution of the
program begins. The name main is a special word (not a reserved word) but must not be
invoked anywhere by the user. The names of the functions (except main) are given by
the programmer. The function name is followed by a pair of parentheses which may or
may not contain arguments. In this case, there are no arguments, but still the parentheses
pair is mandatory. Every function is supposed to return a value, but the function in the
example does not return any value. In other compilers, such function names must be
preceded by the reserved word void.
Third Line: Function Begin
The function body in a C/C++ program is enclosed between two flower brackets. The
opening flower bracket ({) marks the beginning of a function. All statements in a
function which are listed after this brace, can either be executable or non-executable
statements.

Fourth Line: Body of a Function


The function body contains a statement to display the message Hello World. The output
statement cout (pronounced "see-out") meaning Console Output. Is an object used

2
together with the insertion operator (<<) to output/print text. It plays a role similar to that
of the printf() in C.
cout << “Hello World”;
prints the message “Hello World” on the standard console output device. It plays the
role of the statement.
printf(“Hello World”);
as in the hello c program.

Fifth Line: Function End


Just like it is in C, the end of a function body in a C++ program is marked by the closing
flower bracket (}). When the compiler encounters this bracket, it knows it has reached the
end of the program and transfers control to a caller. In this program, the last line actually
marks the end of program and control is transferred to the operating system on
termination of the program.
Note: Every C++ statement must ends with a semicolon (;).

Compilation Process
The C++ program in example 1.2 can be entered into the system using any available text
editor. The program coded by the programmer is called the source code. This source
code is supplied to the compiler for converting it into the machine code.
C++ programs make use of libraries. A library contains the object code of standard
functions. The object codes of all functions used in the program have to be combined
with the program written by the programmer. In addition, some start-up code is required
to produce an executable version of the program. This process of combining all the
required object codes and the start-up code is called linking and the final product is
called the executable code.

1.2 Streams Based I/O


C++ supports a rich set of functions for performing input and output operations. The
syntax of using these I/O functions is totally consistent, irrespective of the device with
which I/O operations are performed. C++‟s new features for handling I/O operations are
called streams. Streams are abstractions that refer to data flow. Streams in C++ are
classified into
 Output Streams
 Input Streams.

1.2.1 Output Streams


The output streams allow performing write operations on output devices such as screen,
disk, etc. Output on the standard stream is performed using the cout object. The syntax
for the standard output stream operation is as follows:
cout << variable;

3
The word cout is followed by the symbol <<, called the insertion or put-to operator,
and then with the items (variables/constants/expressions) that are to be output. Variables
can be of any basic data type.

More than one item can be displayed using a single cout output stream object. Such
output operations in C++ are called cascaded output operations. For example, output of
the age of a person along with some message can be performed by cout as follows:

cout << “Age = “ << age;

The cout object will display all the items from left to right. Hence, in the above case, it
prints the massage string “Age =” first, and then prints the value of the variable age. C++
does not enforce any restrictions on the maximum number of items to output. The
complete syntax of the standard output streams operation is as follows:

cout << variable1 << variable2 << .. << variableN;

The object cout must be associated with at least one argument. Like printf( ), a
constant value can also be sent as an argument to the cout object.

You can add as many cout objects as you want. However, note that it does not insert a
new line at the end of the output. The program in example 1.3, demonstrates various
methods of using cout for performing output operation.

Example 1.3
#include <iostream.h>
int main()
{
char sex;
int age;
float number;
sex = „M‟;
age = 20;
number = 420.5;
cout << sex;
cout << “ “ << age << “ “ << number;
cout << “ \n” << "I am learning C++"<< endl;
cout << number +1;
cout << “\n” << 99.99;
}

The item endl in the statement serves the same purpose as “\n” (linefeed and carriage
return) and is known as a manipulator. It may be noticed that there is no mention of the
data types in the I/O statements as in C. Hence, I/O statements of C++ are easier to code
and use. C++, as a superset of C, supports all functions of C, however, they are not used
in the above C++ program.

4
1.2.2 Input Streams
The input streams allow performing read operation with input devices such as keyboard,
disk, etc. Input from the standard stream is performed using the cin object. The syntax
for the standard input stream operation is as follows:
cin >> variable;
The word cin is followed by the symbol >> (extraction operator) and then with the
variable, into which the input data is to be stored. The use of cin in performing input
operation is shown in example 1.4 below.

Example 1.4
int x;
cout << "Type a number: "
cin >> x;
cout << "Your number is: " << x;

Similarly, input of more than one item can also be performed using the single cin input
stream object. Such input operations in C++ are called cascaded input operations. For
example, reading the name of a person followed by the age, can be performed by the cin
as follows:
cin >> name >> age;
C++ does not impose any restrictions on the number of items to be read. The complete
syntax of the standard input streams operation is as follows:

cin >> variable1 >> variable2 >> .. >> variableN;

The object cin must be associated with at least one argument. Like scanf(),
constant values cannot be sent as an argument to the cin object. Following are some
valid input statements:

cin >> i >> j >> k;


cin >> name >> age >> address;

The program in example 1.5, demonstrates various methods of using cin for performing
input operation.

5
Example 1.5
#include <iostream.h>
int main()
{
char name[25];
int age;
char address[25];
// read data
cout << “Enter Name: ”;
cin >> name;
cout << “Enter age: “;
cin >> age;
cout << “Enter Address: “;
cin >> address;
//Output data
cout << “The data entered are:” << endl;
cout << “Name is “ << name << endl;
cout << “Age is “ << age << endl;
cout << “Address is “ << address;
}
Performing I/O operations through the cout and cin are equivalent to the printf()
and scanf() of the C language, but with different syntax specifications. Two important
points to be noted about the streams operations.
(i) Streams do not require explicit data types specification in I/O statement.
(ii) Streams do not require explicit address operator prior to the variable in the input
statement.
Format-free input and output are special features of C++, which make I/O operations
easier for beginners. Furthermore, the input stream cin accepts both numbers and
characters, when the variables are given in the normal form.
In C++, operators can be overloaded, i.e. the same operator can perform different
activities depending on the context (types of data-items with which they are associated).
The cout is a predefined object in C++ which corresponds to the output stream, and
cin is an object in the input stream. Example 1.6 illustrates the use of cin and cout
streams.

Example 1.6
#include <iostream.h>
int main()
{
int x, y, z;
cout << “Please enter an integer: “;
cin >> x;
cout << “Please enter a second number: “;
cin >> y;
z = x + y;
cout << “Total is “ << z << endl;
}

6
1.3 C++ Comments
Comments can be used to explain C++ code and to make it more readable. It can also be
used to prevent execution when testing alternative code. C++ has borrowed the new
commenting style from Basic Computer Programming Language (BCPL), the
predecessor of the C language. In C, comment(s) is/are enclosed between /* and */
character pairs. Comments can be singled-lined or multi-lined.
1.3.1 Single Line Comment
Single line comment runs across only one line in a source program. The statement below
is an example of single line comment:
/* I am a single line comment */
Apart from the above style of commenting, C++ supports a new style of commenting. It
starts with two forward slashes i.e., // (without separation by spaces) and ends with the
end-of-line character. The syntax for the new style of C++ comment is as shown below:
int acc; // Account Number
acc = acc + 1; // adding new account number for new customer

In C, the above two statements are written as


int acc; /* Account Number */
acc = acc + 1; /* adding new account number for new customer */

The above examples of comments indicate that, C++ commenting style is easy and
quicker for single line commenting. Although, C++ supports C style of commenting, it is
advisable to use the C style for commenting multiple lines and the C++ style for
commenting a single line.

Some typical examples of commenting are listed below:


// this is a new style of comment in C++
/* this is an old style of comment in C++ */
// style of comment runs to the end of a line
Large programs become hard to understand even by the original author (programmer),
after some time has passed. Comments will always restate the nature of a line of code.
Comments which explain the algorithm are the mark of a good programmer.

The compiler completely ignores comments; therefore they neither slow down the
execution speed, nor increase the size of the executable program. Comments should be
used liberally in a program and they should be written during the program development,
but not as an after-thought activity. The program in example 1.7 is for computing the
simple interest. It intends to demonstrate how comments aid in the understanding and
improving readability of the source code.

7
Example 1.7
#include <iostream.h>
int main()
{
// data structure definition
int principle; //principle amount
int time; //time in years
int rate; //rate of interest
int SimpInt //simple interest
int total; /* total amount to be paid back after
„time‟ years */

// Read all the data required to compute simple interest


cout << “Enter Principal Amount: “;
cin >> principle;
cout << “Enter Time (in years): “ ;
cin >> time;
cout << “Enter Rate of Interest: “;
cin >> rate;

//compute simple interest and display the results


SimpInt = (principle * rate)/100 * time;
cout << “Simple interest = “;
cout << SimpInt;

// total amount = principle amount + simple interest


total = principle + SimpInt;
cout << “\n Total Amount = “;
cout << total;
}

1.3.2 Multi-Line Comments


Multiple line comment runs across two or more lines in a source program. Multi-line
comments start with /* and ends with */. Any text between /* and */ will be ignored by
the compiler. The statement below is an example of multi-line comment.
/* I am a multiple line comment.
Hope you got it */

/* The code below will print the words Hello World! to the
screen, and it is amazing */
cout << "Hello World!";

8
2.0 DATA TYPES, OPERATORS AND EXPRESSIONS IN C++
2.1 Data Types
The kind of data that variables may hold in a programming language is called data types.
Data types in C++ can be broadly classified in three categories as depicted in figure 1.
a) User-defined data type
b) Built-in data type
c) Derived data type

Figure 1: Hierarchy of C++ Data Types

User-defined data types are the data types created by the user/programmer. They enable
the programmer to invent his/her own data types and define what values it can take on.

Derived data types are constructed from the basic data types. The array data type is an
example of derived data types. An array can hold several values of the same type, under
one variable name.

Built-in Data Type


Built-in data types are the most basic data-types in C++. The term built-in means that
they are pre-defined in C++ and can be used directly in a program.
There are three built-in data types available in C++
a) Integral type
b) Floating type
c) Void

Integral Type
This can be further classified into
i. int
ii. char
int is the basic data type. It is treated as an integer in that cannot hold fractional values.
char is a data type which can hold both the character data or the integer data. For
example after making the declaration

9
char c;
you can make either of the following assignments:
c = „A‟;
c = 65;

In both cases the decimal value 65 is loaded into the character variable c.

Floating Type
Floating type can further be classified into:
i. float
ii. double
float means floating data-type and represent fractions such as
0.356
0.000001
To declare a variable capable of holding one of these values you use float or double
keywords.
double stands for double precision. It is capable of holding a real number ranging from
1.7 x 10 –308 to 1.7 x 10 308 which gives twice as much precision as presented by a
float. The precision refers to the number of decimal places that can be represented.

Void Type
Void data type has two important purposes:
i. To indicate that the function does not return a value
ii. To declare a generic pointer

For example you may see a function such as:


void func(a, b)
This indicates that a function does not return any useful value.

2.2 Declarations
Every variable must be declared before being used. Declaration provides the compiler
with about how many bytes should be allocated and how those bytes should be
represented. Usually declarations of the same data types are grouped together.
For example
int j, k;
float x, y, z;

The word int and float are reserved words specifying the integer data type and real
data type. There are nine reserved words for data types in C++ as given below:
int char float double short signed void
long unsigned

Typical range and size of these data types are given in table 1.
10
Table 1: Typical Range and Size of Basic Data Types.
Type Range Byte Represents
From To
char -128 128 1 characters
unsigned char 0 225 1 characters
int -32,768 32,768 2 whole numbers
unsigned int 0 65,535 2 whole numbers
long -2,147,438,648 2,147,438,648 4 whole numbers
unsigned long 0 4,294,967,295 4 whole numbers
-38
float 3.4 x 10 3.4 x 1038 4 fractional numbers
double 1.7 x 10-308 1.7 x 10308 8 fractional numbers
long double 3.4 x 10-4932 3.4 x 104932 10 fractional numbers

To declare j as short int and k as long int we write


short int j;
long int k;

If you wish to store integer values less than –32,768 or grater that 32,768, you should use
declaration
long int;
If you need to store integer values in the range of –32,768 and 32,768, then you can use
short int.

Unsigned integers
In a situation where a variable is to hold non-negative values such as counting things,
such variables are restricted to non-negative numbers (or unsigned), thereby doubling its
positive range. Looking at table 1 we note that signed short int has a range of
-32,767 to 32,767 whereas an unsigned short int has a range from 0 to 65,535.
To declare an integer variables as being non-negative only, use the unsigned qualifier
as shown below:
unsigned int k;
unsigned short k;
unsigned long n;

Characters and integers


C++ makes a distinction between numeric and character data. The data type char can be
used to hold either characters or numbers. For example, after you make the declaration
char = c;
You can make either of the following assignments:
c = „A‟;
or
c = 65;
11
Note that character constants are enclosed in single quotes. The quotes tell the compiler
to get the numeric code (ASCII code value) of the character.

2.3 Constants
C++ supports three types of constants namely:
i. Integer constants
ii. Floating-point constants
iii. String constants

Integer constants
Integer constants are values which are mostly used by programmers and computer users.
A computer can also uses octal and hexadecimal constants. Octal constants are written by
preceding the octal value with the digit zero. A hexadecimal constant is written by
preceding the value with zero and an x or X. Table 2 illustrates integer constants in octal
and hexadecimal equivalences.

Table 2: Integer constants


Decimal Octal Hexadecimal
3 003 0x3
8 010 0x8
15 017 0xf
16 020 0x10
21 025 0x15
-87 -0127 -0x57

Floating-point constants
Because an integer data type is inadequate for presenting very large or very small
numbers, floating point data types are therefore necessary. Table 3 illustrates valid and
invalid floating-point constants.

Table 3: Valid and invalid floating-point constants

Floating Comment Remarks


point
Constants
3.1429 Valid
.4444444 Valid
0.4 Valid
5E-2 Valid
3.7123e2 Valid
35 Invalid No decimal point or exponent
3,500.25 Invalid Commas are illegal
6E Invalid The exponent must be followed by a number
3e2.5 Invalid The exponent value must be an integer

12
String constants
A sequence of zero or more characters enclosed by double quotes is called a string
constant. An example of a string is:

“My name is Juma”

A blank string constant is simply represented by “ ”

C++ support one more special character constant called Backslash character constant

The backslash character (\) alters the meaning of the character that follows it. Thus the
character „n‟ when typed after the backslash, i.e. \n, will mean to print a new line. Table 4
gives a list of backslash character strings and the action they produce.

Table 4: List of Backslash Character Strings and Action they Produce


Backslash Character Meaning
\a (alert) Produce an alert (or a bell)
\b (backspace) Move the cursor back one space
\f (form feed) Move the cursor to the next page
\n (new line) Print a new line
\r (carriage return) Print a carriage return
\t (horizontal tab) Prints a horizontal tab
\v (vertical tab) Prints a vertical tab

13
3.0 OPERATORS AND OPERANDS
An operator is a high-level computer language specifying an operation to be performed
that yields a value. An operand on the other hand is an entity on which an operator acts.
In an expression.
A + B
The sign + is an operator specifying the operation of addition on two operands A and B.

C++ language operators are classified into four types.


i. Arithmetic operators
ii. Relational operators
iii. Logical/Boolean operators
iv. Assignment operators

They can be further categorized as:


i. Unary operator - Requiring one operand
ii. Binary operator - Requiring two operands
iii. Ternary operator - Requiring three operands

Operators can associate operators are, increment and decrement operators and
conditional operators.

3.1 Arithmetic Operators


Arithmetic operators are those that perform arithmetic (numeric) operations.

3.2 Unary Operators


Unary arithmetic operators need only one operand for example +a, –b, namely
– (negative) or +(positive).

3.3 Binary Operators


Binary arithmetic operators requires two operands and these include
+ (addition)
- (subtraction or minus)
+ (multiplication)
/ (division)
% (modulus) - For reminder and it is applied only when both operands are
integers.

3.4 Ternary Operators


Ternary arithmetic operators take three operands. For example, the assignment:

max = a > b ? a : b;

It means that if a > b then max is equal to a otherwise max is equal to b

14
3.5 Relational Operators
Relational operators are used to test the relation between two values. All C++ relational
operators are binary operators and hence require two operands. A relation expression is
made up of two arithmetic expressions connected by a relation operator. It returns a zero
when the relation is FALSE and a non-zero when a relation is TRUE. The table below
summarizes relational operators. The relational operators are summarized in table 5

Table 5: Relational operators

Operator Symbol Form Result


Grater than > a>b 1 if a is grater than b, else 0
Less than < a<b 1 if a is less than b, else 0
Greater than or >= a >= b 1 if a is grater than or equal to b, else 0
equal to
Less than or <= a <= b 1 if a is less than or equal to b, else 0
equal to
Equal to == a==b 1 if a is equal to b, else 0
Not equal to != a != b 1 if a is not equal to b, else 0

Note that all relational operators have lower precedence than the arithmetic operators.

3.6 Logical or Boolean Operators


A logical operator combines the result of one or more expressions and the resultant
expression is called the logical expression. After testing the condition, they return logical
status TRUE or FALSE as net result.

Logical operators are unary or binary operators. The operand may be constants, variables
or expressions.

In algebra, the expression

x < y < z

it is true if y is greater x or less than z. In c++ however, the expression has a different
meaning since it is evaluated from left to right as follows.

(x < y) < z

The result of x < y is either 0 or 1. The expression is therefore true in c++ is x is less than
y and z is greater 1, or if x not less than y and z is greater than zero.

15
4.0 EXPRESSIONS AND THEIR DEFINITIONS
An expression consist of one or more operands, zero or more operators linked together to
compute value.

Examples of expressions

a
a + 2
a + b
x = y
15/20

There are four types of expressions


i. Constant Expression
ii. Integral expression
iii. Float Expressions
iv. Pointer Expressions

4.1 Constant Expression.


Constant expressions contain constant values. Examples of constant expressions are:
5
5 + 6 + 13/3.0
„a‟

4.2 Integral Expressions


Integral expressions that offer all the arithmetic and explicit type conversions produce
results that have one of the integer types. If j and k are integers then the following are all
integral expressions.

j
j + k
j/k + 3
k – „a‟
3 + (int)5.0

4.3 Float Expressions


These are the expressions that offer the entire automatic and explicit type conversions,
produce a result that has one of the floating types. If x is a float or double, then the
following are floating-point expressions:

x
x + 3
x / y * 5
3.0
3.0 - 2
3 + (float)4

16
5.0 CONTROL STATEMENTS IN C++
Control statements define the way or flow in which the execution of a program should
take place to achieve the required result. Control statements also implement decisions
and repetitions in programs.
There are four types of control structures supported by C++. These are:
(a) Conditional control (if ) and Bi-directional control (if else)
(b) Multidirectional conditional control (switch)
(c) Unconditional control (goto)
(d) Loop control
(i) while
(ii) do while
(iii) for

5.1 if and if else statements


The if statement tests a particular condition. Whenever that condition evaluated true an
action or a set of actions are taken or executed. Otherwise the actions are ignored. The
syntax form of the if statement is as follows:
if (expression)
statement;

Note that the expression must be enclosed within parentheses. If it evaluates to a non-
zero value, the condition is considered as true and the statement is executed. The if
statement also allows answer for the kind of either or condition by using the else
clause. The syntax for the if–else clause is as follows:
if (expression)
statement-1;
else
statement-2;
If the expression evaluates to none zero value, the condition is considered to be true and
statement-1 is executed; otherwise statement-2 is executed. Note that
statements are terminated by semicolon.

Examples 5.1
// A program illustrating amount limit to be withdrawn.
#include <iostream.h>
int main()
{
int amount;
cout << ”\n Enter the amount: “;
cin >> amount;
if (amount <= 1000)
cout << “Your request is accepted.”;
else
cout << “The amount exceeds the account balance”;
}

17
Example 5.2

// The program to print the lager and smaller numbers


#include <iostream.h>
int main()
{
double x, y, temp;
cout << “Enter two numbers: “ << endl;
cin >> x >> y;
if (x > y)
{
cout << “The larger number is: “ << x << endl;
cout << “The smaller number is: “ << y << endl;
}
else
{
cout << “The larger number is: “ << y << endl;
cout << “The smaller number is: “ << x << endl;
}
}

Exercises
Correct the program given below

#include <iostream.h>
int main()
double number1,number2,number3;
double sum, product;
cout << “Enter three numbers: “ << endl;
cin >> number1 >> number2 >> number3;
if (num < 0)
{
product = num1 * num2 * num3;
cout << “product is ” << product << endl;
}
else
{
sum = num1 + num2 + num3;
cout << “ sum is “ << sum <<endl;
}
cout << “ Data: “ << num1 << “ “ << num2 << “ “
<< num3;

18
Example 5.3
#include <iostream.h>
int main()
{
float amount;
cout << “\n Enter any amount” ;
cin >> amount;
if (amount <= 1000)
{
cout << “Your request is accepted.”;
cout << “\n Your balance plus interest is “ << amount*
(1.05) << endl;
}
else
{
cout << “The amount exceeds the account balance.”;
cout << “Sorry the withdraw can‟t be granted.”;
}
cout << “Thank you for using CRDB ATM services.”;
cout << “\n We look forward for doing business with you.”;
}

Note that if you enter the amount like 100, the first block after the statement if is
executed. If you enter an amount exceeding the account balance like 2000, you will
notice that the block after the else statement is executed.

In both cases however, the last two statements in the program are always executed, as
they are outside the condition blocks.

5.2 if … else if ladder

The condition and their associated statements can be arranged in a construct that takes the
form:
if (condition1)
statement-1;
else if (condition2)
statement-2;
else if (condition3)
statement-3;
. . .
else
statement-N;

19
Example 5.4

// A program to demonstrate if-else-if ladder


// It test if the character is an upper-case lower-case or none.

#include <iostream.h>
#include <conio.h>
int main()
{
char a;
cout << “\n Please Enter an alphabetic character: “;
cin >> a;
if (a > 64 && a <91)
cout << “\n The character is an Upper-Case letter”;
else if (a > 96 && a < 123)
cout << “\n The character is a Lower-Case letter”;
else
cout << “\n This is not an alphabetic character!”;
}

5.3 The Switch Statement


Just like with C, the switch statement in C++ is used to select one of several
alternatives based on a value of a single variable or simple expression. The value of this
expression may be int or char but not of type double. Switch statement is
particularly used instead of if…else ladder, when there are multiple choices such as
menu options. The general form of switch structure is:

switch (variable)
{
case constant1:
statement(s);
break;
case constant2:
statement(s);
break;
case constant1:
statement(s);
break;
default:
statement(s);

The switch structure starts with the keyword switch followed by one block which
contains the different cases. Each case handles the statements corresponding to an option

20
(a satisfying condition) and ends with a break statement which transfers the control out
of the switch structure in the original program.

The variable inside the parentheses following the switch keyword is called the control
variable and is used to test the condition. If the value of the variable matches
“constant1”, the “case constant1” is executed. If the match is “constant2”, the “case
constant2” is executed, and so on. If the value of the variable does not correspond to any
case, the default case is executed. Example 5.5 demonstrates the use of the switch
statements.

Example 5.5
//A simple calculator using switch statement
#include <iostream.h>
#include <conio.h>
int main()
{
char op;
float num1, num2;
cout << "Enter operator either + or - or * or / : ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;

switch(op)
{
case '+':
cout << (num1+num2);
break;
case '-':
cout << (num1-num2);
break;
case '*':
cout << (num1*num2);
break;
case '/':
cout << (num1/num2);
break;
default:
cout << "Error! Operator is not correct";
break;
}
}

21
5.4 Unconditional control ( goto)
The unconditional goto is used in situations, a programmer want to transfer the flow of
control to another part of the program without testing for any condition. The goto
should be followed by a label name and the C++ program should have only one statement
having that label qualifier in the block, in which goto is used.

The syntax for goto is:


goto Label;
Label:
statement;
The label is a valid C++ identifier followed by a colon.

You can, for example, make a loop to repeat the program execution infinitely. This is
done by adding a goto statement and a label, as in Example 5.8 below the label “START”
at the vary beginning to repeat executing the program.

Goto START;
The Program in example 5.6 demonstrates use of unconditional control (goto) and bi-
condition if else. Not that the program will not stop unless you enter the character “0”
and the function exit() terminates the program.

Example 5.6

/* Program to demonstrate if-else-if ladder */

#include <iostream.h>
#include <conio.h>
int main()
{
char a;
START:
cout<<”\n Please enter an alphabetic character:“;
cin >> a;
if (a == „0‟)
exit(0);
else if (a > 64 && a < 91)
cout<<“\n The character is an upper-case letter”;
else if (a > 96 && a < 123)
cout <<“\n The character is a lower-case letter”;
else
cout <<“\n This is not an alphabetic character!”;
goto START;
}

22
6.0 LOOPS
Many jobs that required to be done with the help of a computer are repetitive in nature.
For example, calculation of salary of different workers in a factory is given by the (No. of
hours worked) x (wage rate). This calculation will be performed by an accountant for
each worker every month. Such types of repetitive calculations can easily be done using
a program that has a loop built into the solution of the problem.

6.1 What is a Loop?


A loop is defined as a block of processing steps repeated a certain number of times.

6.2 The while Statement


When we do not know the exact number of loop repetitions before the loop execution
begins, then we use while loop control statement.

Examples on while loop


Example 6.1
This program displays the string “Hello World” five times using the while loops.

#include <iostream.h>
int main()
{
int c = 0;
while (c <= 4)
{
cout <<”\n Hello World”;
c++;
}
count <<”\n Done”;
}

Example 6.2
This program computes and displays gross pay for seven employees. The loop body (the
steps that are repeated) is the compound statements that start on the seventh line i.e. after
the statement while (count <= 7). The loop body gets an employee‟s payroll data
and computes and displays pay. After seven pay amounts are displayed the last statement
calls the cout function to display the message:

23
#include <iostream.h>
int main()
{
int count;
double hours, rate, pay;
count = 0;
while (count < 7)
{
count << “\n Enter Hours”;
cin >> hours;
cout << “/n Enter Rate”;
cin >> rate;
pay = hours * rate;
cout << “pay is Tsh. “ << pay << endl;
count = count + 1;
}
cout << ”\n All employees processed”;
}

Example 6.3
In the following program, the while loop is used to calculate the factorial of a number.
In this program, the number is received from the keyboard using the cin function and is
assigned to the variable “number”. The variable “factorial” is declared as long
int to hold the expected large number and is initialized with the value “1”. The final
value of the factorial is reached through the iterative process:

#include <iostream.h>
int main()
{
int number;
long int factorial = 1;
cout << ”\n Enter the number:”;
cin >> number;
while(number > 1)
factorial = factorial * number-- ;
cout <<”\n The factorial is “ << factorial;
}
Note:
factorial = factorial * number--;
This statement is equivalent to two statements:
factorial = factorial * number;
number = number -1;

24

You might also like