0% found this document useful (0 votes)
51 views

Lecture - Notes C++-2

C++ is an extension of C that adds object-oriented programming capabilities. It allows high-level control over system resources and memory. The Hello World program can be rewritten in C++ using stream input/output rather than standard C printing functions. Key differences include using the #include <iostream.h> directive rather than stdio.h, and using cout and cin objects to output and input text rather than printf() and scanf(). C++ programs are compiled into executable machine code like C programs.

Uploaded by

Kelvin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Lecture - Notes C++-2

C++ is an extension of C that adds object-oriented programming capabilities. It allows high-level control over system resources and memory. The Hello World program can be rewritten in C++ using stream input/output rather than standard C printing functions. Key differences include using the #include <iostream.h> directive rather than stdio.h, and using cout and cin objects to output and input text rather than printf() and scanf(). C++ programs are compiled into executable machine code like C programs.

Uploaded by

Kelvin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

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
6.3 The do . . . while Loop
One important characteristic to the while statement is that the test condition is at the top
of the loop. This means that if the condition is false (or zero) the first time, the while
body will never be executed. But there are certain situations where you need to execute
the body at least once. These situations are not common, but when they do occur, you
should use the do while statement.

The only difference between a do while and a regular while loop is that the test
condition is at the bottom of the loop. This means that the program always executes the
compound statement at least once (the first time through). Then, depending on the value
of expression, it may loop back to do, or it may continue with the next statement.

Example 6.4
The following program uses the do while statement to print the statement Hello World
four times. Compare this program with the while loop program in example 6.1 above.

/* Demonstration of do while statement */


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

Example 6.5
The following program uses the do while statement to compute the factorial of a
number. Compare this program with the while loop program in example 6.3 above.

/* Calculation of factorial using do while loop */


#include <iostream.h>
int main()
{
int number; long int factorial;
factorial = 1;
count << ”\n Enter the number:”;
cin >> number;
do {
factorial = factorial * number--;
} while (number > 1);
cout << ”\n The factorial is “ << factorial;
}

25
6.4 The for Statement
C++ provides the for statement as another form for accomplishing loops. The for loop
statement is used to repeat a statement or block of statements a specified number of
times. The general form of the for loop is:

for (initialization; test expression; increment expression)


body of the loop

The parentheses following the keyword for contain what we call as the loop expression.
The loop expression is divided by semicolons into three separate expressions: the
“initialize expression” (or initialization), the “test expression,” and the “increment
expression.”

The Initialize Expression


The initialize expression, initializes the variable and it is always executed as soon as the
loop is entered.

Typical example of a loop expression is like:


for (number = 0; number < 10; number++ )
cout << “\n number = “ << number;

The initialize expression, number = 0, initializes a variable number to 0. The test


expression, number < 10, test the loop variable. Each time through the loop, to see if
number is less then 10. If the test expression is true, (i.e. number < 10), the loop will be
executed. If the expression becomes false (number is 10 or more), the loop will be
terminated and control will pass to the statements following the loop.

The increment expression, number++, increments the loop variable each time the loop
is executed. To do this, it uses the increment operator (++), described earlier. Note that
the loop variable in a for loop can be increased by 1, or changed by some other number,
using an expression such as:

number = number + 3

The Body of the Loop, this is a statement or statements that follow the keyword for and
the loop expression: They are executed each time round the loop. In the typical example
above, there is only one statement:

cout << “\n number = “ << number;

Note that this statement is terminated with a semicolon, whereas the for with the loop
expression is not. This is because the entire combination of the for keyword, the loop
expression, and the statement constituting the body of the loop, are considered to be a
single C++ statement.

26
Example 6.6
#include <iostream.h>
int main()
{
int number, total = 0;
for (number = 0; number < 10; number ++)
{
total += number;
cout << “\n number”<<number << “ total = “ <<
total;
}
}

6.5 Nested Loops


In programming, nesting is locating a loop within a loop. The fundamental structure of
all programs is a series of loops, which are sets of instructions, repeated certain number
of times. When an if then or while loop is placed within the beginning and end of
another loop, it is said to be nested. For example, the program to calculate the factorial of
number given in Example 6.5 can be modified and written with nested loops as seen in
Example 6.7 below:

Example 6.7
#include <iostream.h>
#include <stdlib.h>
int main()
{
int number;
long int factorial;
for(;;)
{
factorial = 1;
cout << ”\n Enter the number: ”;
cin >> number;
if (number == 0)
exit(0);

do {
factorial = factorial * number --;
} while (number > 1);
cout <<”\n Factorial of “ << number << ” = “ <<
factorial;
}
}

27
Things to note:
1. The factorial program of Example 6.7 is included into an infinite for loop, which
ends only if you enter the number 0. In this case, the for loop is called the outer
loop and the do while loop is called the inner loop.

2. The expression (;;) after the keyword for in example 6.7 above is used to create
an infinite for loop which can be terminated by pressing the keys [ctrl] + [c]
together. You can end the run of the program by entering 0.

Example 6.8
This program demonstrates the nesting of two for loops inside each other in order to draw
the graph shown in Figure 6.1

#include <iostream.h>
int main()
{
int x, y;
for (x = 1; x <= 5; ++x)
{
cout << ”\n”;
for (y = 1; y < 8; ++y)
{
cout << “$”;
}
}
}

When this program is run, the output will be as follows:

Figure 6.1: Output Drawn by Program 6.8


in
Example 6.9
Modify example 6.8 to print asterisks as shown in figure 6.2 below.

Figure 6.2: Asterisks in right-angled


pattern
28
Solution:
#include <iostream.h>
int main()
{
int x, y;
for (x = 1; x <= 5; ++x)
{
cout << ”\n”;
for (y = 1; y <= x; ++y)
{
cout << “*”;
}
}
}

Example 6.10
A program to generate multiplication table using nested for loop
#include <iostream.h>
int main( )
{
int cols, rows, product;
for (rows = 1; rows < 4; rows++)
{
for (cols = 1; cols < 4; cols++)
cout << cols * rows << “ “;
cout << endl;
}
}

When this program is run, the output will be as follows:

Figure 6.3: Multiplication Table

6.6 The Break Statement


Break statements transfers controls out of while, do while, for or switch
statements. You can also use the break statement to separate case labels in switch
statements. The break statement exits the current loop and transfers control to the
statement immediately following the control structure. The program in example 6.11
shows the use of the break statement.

29
Example 6.11
#include <iostream.h>
int main( )
{
int i = 1;
while (i > 0)
{
cout << "count = " << ++i << endl;
/* Break out of the while statement when i > 5 */
if (i > 5)
break;
}
cout << "End of program";
}

6.7 The exit() function


The exit() function is a runtime library routine that causes the program to end,
returning control to the operating system. If argument to exit() is zero, it means that
the program is ending normally without errors. Nonzero arguments indicate abnormal
termination of the program.
The function exit() found in the header file stdlib.h, is used to terminate the
execution of the program. In this case you do not need the second condition, because if
the condition is false the control is transferred to the last statement skipping the if block.
This is illustrated by example 6.12 below:

Example 6.12
#include <iostream.h>
#include <stdlib.h>
int main()
{
float amount;
cout << “\n Enter the amount” ;
cin >> amount;
if (amount <= 1000)
{
cout << “Your request is accepted.”;
cout << “\n Your balance plus interest is “ << amount
* (1.05);
cout << “\n Thank you for using NMB ATM services. “;
exit(0);
}
else
cout << “The amount exceeds the account balance.”;
}

30
6.8 Flowchart
A flowchart is simply a graphical representation of steps. It shows steps in sequential
order and is widely used in presenting the flow of algorithms; workflow or processes. It
makes use of symbols which are connected among them to indicate the flow of
information and processing. The flowchart uses special geometric figures to represent the
actions taken by the computer and the logical flow of the actions that take place. Below
are symbols commonly used in flow charts.

Figure 6.4 : Symbols Used in a Flowchart


Steps to Create Flowchart
Though it may seem complicated to create a programming flowchart, online flowchart
maker tools can quickly help the designs create a programming flowchart. Here are some
easy steps that the designers and engineers can follow to create their flowcharts.
1. Find Out the Purpose of the Programming Flowchart
At first, the programmers need to find out the purpose of the programming flowchart they
are creating. When they decide the topic, they need to check the symbols useful for the
programming flowchart.
2. Pick Proper Symbols
The programmer needs to know the meaning of the symbols properly. Without the proper
symbol, the programmer may fail to produce the whole programming flowchart. They
also need to decide the chronological order of the working process by reviewing any pre-
existing documentation of the step.
3. Plan the Shapes
The programmers can include shorter texts and single keywords to make the flowchart
look more concise and efficient. They also need to sort the shapes by their type and use.
For example, they can use symbols of input/ output or process, and for that, they need to
plan the shapes.
4. Place the Shapes and Symbols
The programmer can now place the shapes and symbols while working on the logic flow
in a programming flowchart. There are some specific symbols to express a particular

31
thing or function. Once the programmer has finished lining out the program or applying
the symbols, they must place the arrows to connect the shapes.
5. Check the Logical Structure of the Flowchart
After finishing the whole flowchart, the programmer must carefully go through the
programming flowchart to determine if they have skipped any step that can disturb the
programming flowchart's overall logic.

Example 6.13
Draw a flowchart for adding two numbers entered by the user
Solution

Example 6.14
Figure 6.5 is a flowchart for printing numbers 1, 2, 3, …., 20 using do... while loop
concept.

Figure 6.5: Flowchart for Printing Numbers 32


In step 5 of the flowchart above, the current value of A is compared with 21. If the
current value of A is less than 21, steps 3 and 4 are repeated. As soon as the current
value of A is not less than 21, the path corresponding to “NO” is followed and the
repetition process stops.

Terms used in Looping


Initialization: It is the preparation required before entering a loop. In the
flowchart above, step 2 initializes the value of A as 1.
Increment: It is the numerical value added to the variable each time one goes
round the loop. Step 4 of the flowchart shows the increment of A by 1.
The Loop Variable. It is an active variable in a loop. In the flowchart above, A
is the active variable.
Loop Exit Test. This is a method or technique of leaving the loop after it has
circled the requisite number of times. In the flowchart above, step 5 is the
decision diamond, where the value of A is compared with 21. As soon as the
condition is satisfied, control comes out of the loop and the process stops.

Example 6.15
Draw a Flowchart for calculating the salary of 100 workers using while loop concept
Solution

Figure 6.6: A Flowchart to Calculate the Salary of 100 Workers


Explanation:
33
Example 9.16
Figure 6.7 is a flowchart that illustrate the operation of the for loop

Figure 6: Operations of the for Loop

Exercise
How many times the value of I will be read in the flowchart shown in figure 6.8 below

(a) (b)

Figure 6.8: A Flowchart to Read a Value a Number of Times


34
7.0 FUNCTIONS
7.1 What is a function?
A function can be equated to a “Blackbox” to which one or more input values are passed,
some processing done, and output value(s) are then returned automatically.
Figure 7.1 illustrates this sequence when a function named sqrt is called. The value of x
(16.0) is the function input, and the function result or output is the square root of 16.0,

Figure 7.1: Function sqrt as a Black Box

Functions as Program Building Blocks


Programmers use functions like building blocks to construct large programs. Arguments
of a function are used to pass information into the function subprogram from the main
function and to return to the calling function multiple results computed by the function
subprogram. Arguments that carry information from the main function into the function
subprogram are called input arguments or parameters. Arguments that return results to
the main function are called output arguments.

7.2 C++ Function


A C++ function is a grouping of program statements into a single unit to carry out tasks
at a given level. Each C++ function can be activated through the execution of a function
call.
Why Use a Function?
a) The use of functions enables us to write our program in logical independent
sections in the same way as we develop the solution algorithm.
b) Functions may be executed more than once in a program. Also if you have
written and tested a function subprogram, you may use it in other created sub
programmes.

7.3 Classification of Functions


Functions are of two types. These are
a) Built-in Functions or Library functions
b) User Defined Functions
7.3.1 Built-in Functions
The C++ compiler contains a number of standard library functions. Such functions are
included in header file called (math.h). Operations that are frequently used by in a
programme like determining the square root of a number, sine value of a number etc, are
programmed in the form of standard functions and stored in C++ library, so that they can
be called in any program when needed by the programme. These functions are called
library function or built-in functions. Table 7.1 shows some of the commonly used
mathematical built-in library functions. Example 7.1 illustrate the use of the function
sqrt().
35
Table 7.1: Mathematical Built-in Library Functions
Function Library File Return value Argument Result
Abs(x) <stdlib.h> Returns the absolute value of its int int
integer Argument
if x is -5, abs(x) is 5
ceil(x) <math.h> Returns the smallest whole number that double double
is not less than x:
If x is 45.23, ceil(x) is 46.0
cos(x) <math.h> Returns the cosine of angle x: double double
If x is 0.0. cos(x) is 1.0 (radians)
exp(x) <math.h> Returns ex where e = 2.71828 double double
fabs(x) <math.h> Returns the absolute value of its type double double
double Argument:
If x is -8.432,fabs(x) is 8.432
floor(x) <math.h> Returns the largest whole number that double double
is not greater than x:
If x is 45.23, floor (x) is 45.0
log(x) <math.h> Returns the natural logarithm of x for double double
x > 0.0
If x is 2.71828, log(x) is 1.0
log10(x) <math.h> Returns the base 10 logarithm of x for double double
x> 0.0
pow(x,y) <math.h> Returns xy. If x is negative, y must be double double
a whole Number:
If x is 0.16 and y is 0.5, pow(x,y) is
0.4
sin(x) <math.h> Returns the sine of angle x: if x is double double
1.5708, sin(x) is 1.0 (radians)
sqrt(x) <math.h> Returns the non-negative square root double double
 
of x x .
If x is 2.25, sqrt(x) is 1.5
tan(x) <math.h> If x is 0.0, tan(x) is 0.0 Double double

Example 7.1
#include <iostream.h>
#include <math.h> /* Include function for square root */
int main()
{
double num;
cout << ”\n Enter a non-negative number: “ << endl;
cin >> num;
if (num < 0)
cout << ”\n Input Error: Number is negative“ << endl;
else
cout << “The Square root is “ <<sqrt(num) << endl;
}

36
Question
Write a program to compute the quadratic equation
ax 2  bx  c  0
Not that the roots of the quadratic equation are given by:

 b  (b 2  4ac)
root _ 1 
( 2a )

 b  (b 2  4ac)
root _ 2 
( 2a )
The discriminate (disc) is defined as b2 – 4ac
When the value of the discriminant is greater or equal to zero, the roots of the quadratic
equation exist, otherwise the roots are imaginary (complex).

Solution
#include<iostream.h>
#include<math.h>
int main()
{
double disc, root_1, root_2;
double a, b, c;
cout << "\n input the values of a, b and c: ";
cin >> a >> b >> c;
disc = pow(b, 2) - 4 * a * c;
if (disc >= 0)
{
root_1 = (-b + sqrt(disc))/(2*a);
root_2 = (-b -sqrt(disc))/(2*a);
cout << "\n Root1 = " << root_1 << endl;
cout << "\n Root2 = " << root_2 << endl;
}
else
{
cout << "\n No real root exists \n";
}
}

7.3.2 User Defined Functions


A part from the built in C++ library functions, users can also define their own functions
to do a task relevant to their programs. Such functions are called user-defined
functions. These functions are codified by the user, so that such functions can perform
the task as desired by the user.

37
Types of User Defined Functions
The user defined functions may be classified in three types. Each type is based on the
formal arguments or parameters passed to the functions and the usage of return statement.
These types are:
i. A function is invoked or called without passing any formal argument from the
calling portion of a program and also the function does not return any value to the
called function.
ii. A function is invoked by the calling program and formal arguments are passed from
the calling program but the function does not return any values to the calling
program.
iii. A function is invoked with formal arguments from the calling portion of a program
which returns value(s) to the calling program.

Advantages of Functions
The following are some advantages of using functions:
a) The complexity of the entire program can be divided into simple subtasks and
function subprogram can be written for each subtasks.
b) The subprograms are easier to write, understand and debug.
c) A function can be shared by other programs by compiling it separately and
loading them together.
d) In C++, a function can call itself again. It is called recursiveness. Many
calculations can be done easily using recursive process such as calculation of
factorial of a number.
e) The functions such as cout, cin, the numerical computation functions sin, cos, sqrt
etc, are used very frequently. Hence these are kept in C++ library and compiler is
written in such a way that any C++ program can call any of the library functions.

7.4 Defining A Function


A function definition has a name, a parentheses pair containing zero or more parameters
and a body. For each parameter, there should be a corresponding declaration that occurs
before the body. Any parameter not declared is taken to be an int by default. For good
programming, one should declare all parameters. Turbo C++ compiler permits including
the argument declaration with the parentheses.

The general format of the function definition is as follows:


function_type function_name(datatype
argument1,datatype argument2, . . .)
{
.
.
. Body of the function

return statement;
}

38
7.5 Declaring the type of a Function
The function declaration denotes the type of value it would returned to the calling portion
of the program. Any of the basic data types such as int, float, char etc, may appear in the
function declaration. In case, when a function is not supposed to return any value, it may
be declared as type void.
For example:
int func_name(int a);
void func_nam(float b);
7.6 Function Name
The function name can be any name conforming to the syntax rules of the variables.
However, you should normally use a function name relevant to the function operation.

For Example:
void show (void)
void square (int a, int b)

Example 7.2 illustrates the definition of a user defined line() function. Notice that the
function definition is at the beginning of the function itself, and the semicolon is not used
after the name of the function.

Example 7.2
// A program to print a line
#include<iostream.h>
#include<stdio.h>
void line(void)
{
int j;
for (j = 1; j < 20; j++)
cout << "-";
cout << "\n";
}
int main()
{
line ( );
}

7.7 Formal Arguments


Any variable declared in the body of a function is said to be local to that function. Other
variables that are not declared within the body of the function are assumed to be global to
the function and must be defined externally.
Consider the following code:
int counter (float x1, int x2, char c)
{
return (int value);
}

39
In this code segment, x1, x2, and c are formal arguments applicable to the function only.
The function returns an int value to the calling program.

The program listed in example 7.2 uses a line ( ) function to draw a line containing 20
asterisks (-). We can draw any number of such lines by calling the line ( ) function. Thus
there is no need to write a program every time. You need to define the function once and
call the user defined function any number of times to perform the desired function.
The variable j used in line( ) function in example 7.2 is only known to line ( ). It is
invisible to the main ( ) function. If we used this variable in function main ( ) without
declaring it there, then compiler gives an error message because main ( ) do not know any
thing about this variable.

This is very important to know while writing functions in C++. Variables used in a
function are unknown outside the function. Thus a local variable will be known to the
function it is defined in, but not to others. A local variable used in this way in a function
is known in C++ as an “automatic” variable, because it is automatically created when a
function is called and destroyed when the function returns.

Example 7.3 demonstrates the function declaration, function calling and function
definition

Example 7.3:
//A Program demonstrating function calling, declaration and definition
#include<iostream.h>
void show (void); //prototype
int main ()
{
show ( ); //function calling
}
void show (void) //function definition
{
cout << “demonstration program \n”,
cout << “for calling a function \n”;
} // end of function

When the programme is compiled, the output of the program will be:
demonstration program
for calling a function

The program given in example 7.4 uses a special character „\a‟ which is called BELL
alert in the standard ASCII code. By using the cout statement, you can create a beeping
sound by using the code given in example 7.3. The program calls a function called
twobeep(). The function makes two beeps separated by a short silent interval. Then the
program asks you to type a letter. When you do, it makes two beeps again.

40
How the delay is created?
A for loop is set up to cycle 1000 times. This constitutes a “null” statement: a statement
with nothing in it. Its only role is to terminate the for loop after cycling 1000 times.
This may be thought as a for loop for introducing delay in the loop.

Example 7.4
A program that makes two beeps
#include<iostream.h>
/* beeps the speaker twice */
void twobeep(void)
{
int k;
cout << "\a";
for (k = 1; k < 1000; k++);
cout << "\a";
}
int main()
{
char x;
twobeep();
cout << "\n Type any character ";
cin >> x ;
twobeep();
}
7.8 Function Prototype
The function prototype tells the C++ compiler in advance about some characteristics of a
function used in a program. i.e. it notifies the C++ compiler of the type and number of
arguments that a function will use.
Prototyping helps the compiler to detect errors if the function is improperly used.
A function prototype takes the form:
Type function_name(type argument_1, type argument-2,. . .);
It has three main components. These are:
i. Function type
ii. Function name
iii. Arguments

Function type
The function “type” is the type of the returned value. If the function does not return a
value, the type is defined as void.

Function name
The function name is any legal identifier followed by the parentheses without spaces in
between.

41
Arguments
The arguments (or parameters) are given inside the parentheses, preceded by their types
and separated by commas. If the function does not use any parameters, the word void is
used inside the parentheses. Here are some examples for prototypes of built-in functions
int getchar(void);
double pow(double x, double y);
void exit(int x);
The first function, int getchar(void); returns an integer value and does not take any
arguments. The second function double pow(double x, double y); takes two double
arguments (x and y) and returns a value of the type double. The third function void
exit(int x); returns no value but it accepts an argument x of the type integer.
The header files such as iostream.h and stdio.h contain the prototypes of the built-in
C++ functions. You may sometimes forget to include the proper header file in your
program, but you still have the program running and may get correct results. This is
because if you do not include the header file, the compiler will use the default type which
is of the type in for any function.

7.9 Use of void() Function


If the function is of the type void, no return statement is used. Actually, the main() block
of the C++ program is a function, and because no type is specified, it is therefore
considered of the type int, Turbo C++ compiler gives a warning if you do not use the
return statement at the end of the main() block. You can avoid this warning by writing
your main function as given below:
main()
{
statement(s);
return(0);
}
This means that no returned value is expected from the main function. Another way to
avoid the warning message is to use the void type like this.

void main()
{
………………
}
You may also run across programs with the main function declared as:
void main (void);

7.10 Accessing a Function


A user defined function is invoked or called from the main program simply by using its
name, including the parentheses containing the parameters to be passed, if any. The

42
parentheses are mandatory so that the compiler knows you are referring to a function and
not a variable that you forgot to declare.

7.11 Invoking a Function without Passing Argument(s)


It is the simplest way of writing a user defined function because there is no formal
argument transfer between the calling statement of the program and a called program
function. Program shown in example 7.5 (a) calls the function sample() without passing
any argument. The function sample() after execution transfers the control back to the
function main (). The presence of void in the function void sample(void) shows that
no value is passed to the function.

Example 7 .5
#include<iostream.h>
void sample (void); /* prototype declaration of function sample */
int main()
{
cout << "\n I am calling function sample \n" <<
endl;
sample();
}
void sample(void) /* function definition */
{
cout << "Thank you for calling me." << "I am sample "<< endl;
} /* end of function */

7.12 Passing Arguments to Function


Arguments are used to pass the values of variable to a function. The structure of a
function passing arguments is shown in example 7.6.

Example 7.6
/* This program that demonstrates passing arguments to a function */
#include<iostream.h>
#include<stdio.h>
void swap1(int xx, int yy)
{
cout << "First is " << xx << endl;
cout << "Second is " << yy << endl;
}
main()
{
int x = 1;
int y = 7;
swap1(x, y);
43
}

A program shown in example 7.7 passes the formal arguments to a function cube( ) but
the function cube( ) does not return any value to the caller. It is one way communication
between a calling program and the function block.

Example 7.7
Program for calling function by passing formal arguments from main ( )
#include<iostream.h>
void cube(int, int); /* prototype declaration function cube*/
int main()
{
int x, y;
cout<<"\nEnter integer values for x and y: \n"<< endl;
cin >> x >> y;
cube(x, y); /* function call */
}

void cube(int x, int y /* function definition */


{
x = x*x*x;
y = y*y*y;
cout << "x cube = " << x << endl;
cout << "y cube = " << y << endl;
} /* end of function */

Example 7.8
A program that finds a cube of a number using a function declaration with the return
statement
#include<iostream.h>
float cube(float); /* prototype declaration of function cube */
main()
{
float i, max, value;
max = 2.0;
i = -2.0;
while(i <= max)
{
value = cube(i);

44
cout << "i = " << "\t" << "\t" << "1 cube = "
<< "\t" << value << endl;
i = i + 0.5;
}
}
float cube(float n) /* function definition */
{
float value;
value = n*n*n;
return (value);
} /* end of function */
When the program is run the output will be as follows:

I = -2 I cube = -8
I = -1.5 I cube = -3.375
I = -1 I cube = -1
I = -0.5 I cube = -0.125
I = 0 I cube = 0
I = 0.5 I cube = 0.125
I = 1 I cube = 1
I = 1.5 I cube = 3.375
I = 2 I cube = 8

In example 7.8, the function cube() gets the value of the parameter n. It calculates the
cube of n and assigns it to value.

The statement return (value) transfers the calculated cube value of n to the main(). Thus,
every time the function cube(i) is called in the main() block, the calculated value of cube
of the argument is returned to the main(). The main() block uses a while loop to assign
different values to the variable i. This argument, i is transferred to the function float cube
(float n)

45

You might also like