Lecture - Notes C++-2
Lecture - Notes C++-2
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.
Example 1.1
#include<stdio.h>
main( )
{
printf(“Hello World”);
}
Example 1.2
#include <iostream.h>
int 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.
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.
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.
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:
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:
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:
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:
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
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.
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 */
/* 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
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.
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
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
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;
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.
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.
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:
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.
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.
Operators can associate operators are, increment and decrement operators and
conditional operators.
max = a > b ? a : 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
Note that all relational operators have lower precedence than the arithmetic operators.
Logical operators are unary or binary operators. The operand may be constants, variables
or expressions.
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
j
j + k
j/k + 3
k – „a‟
3 + (int)5.0
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
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
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.
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
#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!”;
}
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.
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
#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.
#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.
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.
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:
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 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:
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;
}
}
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 << “$”;
}
}
}
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;
}
}
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";
}
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.
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.
Example 6.15
Draw a Flowchart for calculating the salary of 100 workers using while loop concept
Solution
Exercise
How many times the value of I will be read in the flowchart shown in figure 6.8 below
(a) (b)
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";
}
}
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.
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 ( );
}
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.
void main()
{
………………
}
You may also run across programs with the main function declared as:
void main (void);
42
parentheses are mandatory so that the compiler knows you are referring to a function and
not a variable that you forgot to declare.
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 */
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 */
}
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