Documente Academic
Documente Profesional
Documente Cultură
1. C++ Language
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
Introduction
Basics of a C++ program
Variables
Constants
Data types
Operators
Expressions
Structure of a C++ program
Turbo C++ screen layout
Exercise
2. Statements
2.1
2.2
2.3
2.4
2.5
Exercise
3. Control statements
3.1 While statement
3.2 Do..while statement
3.3 For statement
3.4 Rules of FOR loop
3.5 Programs
Exercise
4. Functions
4.1 Library functions
4.2 String functions
4.3 Programs
Exercise
1. C++ Language
1.1 Introduction to C++ language
C++ was developed by Bjarne Stroustrup in the year 1979. It C++ combines the features
of low level and high level programming languages. It is the extension of C Language and it was
originally called as C with Classes and then it was renamed as C++. It is the most popular
programming language widely used all over the world on different platforms and operating
systems. It is mainly used for designing system software like compiler, interpreter, utilities, client
applications, device drivers and video games etc. As the C++ is an extension of C, it is more
compatible with C and it runs any type of C program smoothly.
Read variables,
Constants and keywords
Practice syntax of
Statements and functions
Create program
For the problem
Is there any
Bug?
No
Observe the output
Of the program
Figure 3.1
1.2 Basics of C++ Language
Character set of C++ Language
A character is the basic unit of any language that represents words, numbers or expressions. The
following table summarizes the character set of C++ language.
Category
Symbols
Alphabets/Letters
A to Z
a to z
Digits
0 to 9
Special symbols
,.:;?!/\|~_$%#&^*-+
<>()[]{}=
White spaces
Blank space, Horizontal tab, carriage return,
new line and form feed
Table 3.1
Keywords
Keywords are the basic reserved words of C++ language that cannot be changed or used for other
purposes. Statements are written using these keywords. There are 32 keywords available in
standard C++ language. All the keywords must be written in small letters. Some of the commonly
used keywords are as follows
Auto
Break
Case
Char
Const
Continue
Default
Do
Double
Else
Float
For
Goto
If
Int
Long
Return
Short
Signed
Switch
Unsigned
Void
While
Main
Table 3.2
Valid/Invalid
Valid
Valid
Invalid
Invalid
Reason
Underscore is allowed
Number is allowed
First character must be alphabet
Blank space is not allowed
return
sum,average
1person
name-age
TOTAL
identifier_1
si_ci_int
Invalid
Invalid
Invalid
Invalid
Valid
Valid
Valid
1.4 CONSTANTS
A constant in C++ language is a quantity whose value cannot be changed during the execution of
the program. The different types of constants in C++ language are as follows
CONSTANTS
Numeric
Integer
Real
Decimal
Octal
Hexa
Character
Single
Structured
String Array
Pointer
structure
union
Figure 3.2
Float
It uses four bytes for its storage and it can take values ranging from ___ to ____.
Example: 23.4442,
0.99847,
-0.33234
+123.3423
Double
It uses eight bytes for storage and it can be used to represent big or small numbers.
Example: 1010132.232323,
-0.000044500033,
-1010010233.3333
Rules for numeric constant
a. A numeric constant must have at least one digit
b. Integer constants should be written without decimal point and real numbers must have
decimal point
c. A number can be written as either positive or negative using + or sign. The default sign is
positive.
d. Commas or blank spaces are not allowed in constants
e. Special characters are also not allowed.
E-Notation
It is a special kind of real number that helps to process very big or very small numbers. The
general format of e-notation is as follows
Mantissa
e Exponent
Where mantissa part consists of integer part, real part and sign of the number,
Exponent part specifies the power value and the sign of the power. The absence of the sign
indicates the power is positive. The letter e stands for base 10.
Example: 1.23e23,
-0.343e-10,
+12345.343e+23
Rules for writing exponent component
1. The range of real constants expressed in exponential form is 3.4e38 to 3.4e38. It changes to
the double format.
2. Mantissa may have a positive or negative sign. Default is positive sign.
3. Exponent part must have at least one digit.
4. The letter e is used to separate mantissa and exponent. It represents base 10.
Character constant
It is classified into single character and string. They are as follows
a. Single character
An alphabet, digit or symbol enclosed in a single quote is called character constant. It denotes the
ASCII value of the character and it can be used in calculations also.
Example:
A
0
+
?
a
The ASCII value of the character A is 65, B is 66. Z is 90, similarly the value of a is 97,
b is 98.z is 122. The value of digit 0 is 48, 1 is 49.9 is 57.
String constant
Set of characters enclosed within double quotes is termed as string constants. A blank space
(ASCII value is 32) is also called a character.
Example: ATOMIC ENERGY SCHOOL,
kalpakkam, Narasimman
Introduction to C++ for class XI by P.N
Invalid
Invalid
Valid
Invalid
Invalid
Valid
Valid
Invalid
Bytes
required
1 (8 bits)
1 (8 bits)
2 (16 bits)
2 (16 bits)
Purpose
Range of values
4 (32 bits)
4 (32 bits)
-231 to 2 31-1
3.4e-38 to 3.4e+38
8 (64 bits)
1.6 Operators
Operators play an important role in the expressions. It combines operators, variables, constants,
array elements and function references to form an expression. The data elements that operate on
operators are called operands. Most of the operators require two operands and some operators can
operate on single operand also. The different categories of operators are as follows
a. Arithmetic operators
b. Relational operators
c. Logical operators
d. Unary operators
e. Assignment operators
The operators of each category are explained below.
a. Arithmetic operators
All of the mathematical operations are performed using the arithmetic operators. The following
table summarizes the arithmetic operators
Purpose
Addition
Subtraction
Multiplication
Division
Remainder
(after
integer division)
Operator
+
*
/
%
Example
a+b
c-d-e
A*b*d
b/10
10%3
Table 4.1
Example 1
Suppose that a and b are integer variables whose values are 25 and 10 respectively. Let us
evaluate the following expressions
Expression
A+b
a-b-10
a*b*2
A/b
10%3
Result
35
5
500
2.5
5
Example 2
Represent the following mathematical expression in C++ language. Also specify the invalid
format.
S.No.
1.
2.
3.
4.
5.
Mathematical expression
Multiply x with y
Add x with y
ab/c
ax2+bx+c
a-b / c*d
Invalid format
x*-y
-x+-y
Ab/c
ax2+b*x+c
a-b/c*d
Table 4.2
Some important points about arithmetic operators
a. C++ does not support foe exponentiation, so POW function can be used to calculate power
value.
b. No two consecutive operators are allowed. For example x+-y is not valid, however you can
write it as x+(-y)
c. Integer Arithmetic
If two operands are integers then the operation is called integer arithmetic and the result
obtained will also be the integer. The result of 16/5 is 3, not 3.2, since the decimal point is
truncated.
d. Real arithmetic
The operation involving real operands is called real arithmetic. The result of 10.0/3.0 is 3.333
e. Mixed-mode arithmetic
In an expression, if one operand is real and the other is integer then it is called mixed mode
arithmetic. But the result of the expression is float. For example the result of 150/10.0 is
14.22
b. Relational operators
Relational operators are used to compare two quantities such as constants, variables and
arithmetic expressions. The result of relational operator is either true or false. If the result of the
operator is true then it returns the value as non-zero, otherwise it gives the result as 0. The uses of
various relational operators are given below.
Purpose
Greater than
Less than
Greater than or equal to
Less than or equal to
Equal to
Not equal to
Operator
>
<
>=
<=
==
!=
Example
a>b
age<18
Mark>=35
x<=y
x==20
x!=y
Table 4.3
Example
Suppose that a and b are two variables whose values are 25 and 75 respectively. Evaluate the
following operations.
a.
b.
c.
d.
Logical operators
C++ language provides three logical operators such as and (&&), or (||) and not (!). These
operators are mainly used to combine two or more relational expressions. The operator not (!) is
used to negate the given quantity or expression. It takes a single operand. The result of the
relational expression is either true or false. The following table summarizes the logical operators
Purpose
Combine both
Either or
Negate the quantity
Operator
&&
||
!
Table 4.3
Example
(a>b)&&(a>c)
(sex==f)||(age>18)
!(x==5)
Example
Write the following problems in C++ expression form using relational and logical operators
a. both maths and science are greater than 70
Ans: maths>70 && science>70
b. either basic pay >7000 or net salary > 10000
Ans: (basicpay>7000) || (netsalary>10000)
c. if not grade is equal to D
Ans: !(grade==D)
The following truth table gives the result of logical expression containing logical operators
A
True
True
False
False
B
True
False
True
False
A && B
True
False
False
False
A || B
True
True
True
False
!A
False
False
True
True
Table 4.4
Unary operators
It is a special kind of operators and these are not available in other languages like BASIC,
COBOL, FORTRAN etc. The operators so far discussed takes two operands but unary operator
takes only one operand for its execution. The following table gives the used of three different
unary operators
Purpose
Operator
Increment
++
Decrement
-Unary minus
The logical operator ! (not) also works like unary operator. The increment operator ++ increments
the value of the variables by one, similarly the decrement operator decreases the value by one.
The unary minus operator is used to negate the operand and it can be used as predecessor to the
operand. The increment and decrement operators can be used either before or after the operands.
Let us consider two examples for both the operators.
Example 1
Example 2
kal=16;
pn=kal++;
kal = 16;
pn=++kal;
In the second line of Example 1, the value of kal is first assigned to the variable pn and then the
value of kal is incrementted. So the value of pn is 16 and kal is 17. In the second line of Example
2, the value of kal is first incremented and then assigned to the variable pn. So the value of kal is
17 and pn is 17.
The equivalent statement for increment operator is as follows
a. pn=kal++; is equal to pn = kal;
kal = kal+1;
b. pn=++kal; is equal to
kal = kal+1;
pn = kal;
10
Assignment operator
This operator is mainly used to store the result of an expression to a variable. This follows right to
left associative while executive the expression. The common assignment operator is = (equal to )
sign. The general format of assignment operator is as follows
Variable op = Expression
Where op is a binary operator and it is also known as short hand assignment operator. The above
syntax is equal to Variable = Variable op Expression
For example, x = x+5 can be written as x+=5.
The shorthand operator method of writing expression is more efficient, simplifies the expression
and easy to read.
Note: Assigning same value to more than one variable is known as multiple assignment
statement. Example a=b=c=23; it assigns the value 23 to the variables a, b and c.
Suppose that a and b are two integer variables whose values are 10 and 5 respectively. The
following table gives the result of various expressions involving shorthand operator.
Short hand expression
a+=b
a-=10
a*=(a+b)
a%=b
b/=2.5
a*=a
Result
15
0
150
0
2
100
Conditional operator
It replaces the if..else construct by a single line using conditional operator. An expression
consisting of ternary operators (? : ) is called conditional operator. The general format of this
expression
e1 ? e2 : e3
where e1, e2 and e3 are called expressions. Here e1 must produce the result as either true ( non
zero ) or false (0).
Execution:
First the expression e1 is evaluated. If the result of e1 is true then e2 is executed, otherwise e3 is
executed. You can also assign the result of either e2 or e3 to a variable in the following format
Variable = e1 ? e2 : e3
Here if the result of the expression e1 is true then e2 is evaluated and its value is assigned to
variable at the left side.
Examples
1. (age>18)?printf(\nEligible for voting):printf(\nNot eligible for voting);
Suppose if the condition is true then the output is Eligible for voting, otherwise the result is
Not eligible for voting.
2. bonus = (sal>5000)?2500:3500
If the condition, ie. Sal>5000, is true then the value 2500 is assigned to the variable bonus,
otherwise 3500 is assigned to bonus.
Introduction to C++ for class XI by P.N
11
1.7 Expressions
Expressions are the backbone for any type of calculations in the program. It consists of two or
more operands with one or more operators. Every operator requires minimum two operands for
its execution (except unary operators and not(!) operator). It is interesting to note that all such
expressions are executed in ALU device of CPU. Expressions make use of several quantities such
as operands, variables, constants, function references etc. In C++ language, expressions are
classified into the following three categories. They are
a. Arithmetic expressions
b. Relational expressions
c. Logical expressions
Let us discuss each of these expressions in detail
Arithmetic expression
It represents the mathematical expressions in easy manner. Arithmetic expressions combine
arithmetic operators with variables, constants or any other quantities. The result of the arithmetic
expression is always a finite number. The general format of this expression is as follows
Operand1 <AO> Operand2
Where operand1 and operand2 can be variables, constants or it can be the reference of any
function. The arithmetic expression in the assignment statement form is as follows
Variable = Arithmetic Expression
Let us consider some of the mathematical expressions and its equivalent C++ expressions.
Mathematical expression
ax2+bx+c
a*x*x+b*x+c
-b
--2a
-b/(2*a)
a
b
c
--- + --- + --b
c
d
b2-4ac
sqrt(b*b-4*a*c)
x1/4
pow(x,1/4)
It is necessary to assign value for the variables before it is used in the expression.
Hierarchy of Arithmetic expressions
The order followed in executing the operators in an expression is as follows
a. Arithmetic expression is evaluated from left to right
b. Expressions in innermost parenthesis is executed
Introduction to C++ for class XI by P.N
12
Execution
Result
10>20
20>(10+5)
50<(20+15)
500>900
True
True
False
False
Logical expression
It is also called as Boolean expression, since this expression also produces the result as either true
or false. It compares two relational expressions. The general format of logical expression is
Operand1 <LO> Operand2
Where operand1 and operand2 are the relational expressions and LO is a logical operator. The
operands of logical expression must produce the result as either true or false.
Example
Let a=5, b=7 and c=20. Evaluate the following relational expression and find the result.
Introduction to C++ for class XI by P.N
13
Logical expression
Execution
Result
False
False
True
decision statements such as IF,
Contents
Comments, definitions and includes
etc.
Declaration section
Variables and function declaration
Executable
statements Statements, instructions, function
section
calling etc.
Functions/Subprograms
User defined functions
Body of the
loop
In the above structure, only the body of the program is compulsory and the other sections are
optional. The structure of the body of the program is as follows
main()
{
declaration of variable;
----------Instruction/executable part;
}
Let us consider an example program to illustrate the structure of a C++ program
Program: To find the area and circumference of a circle.
#include <iostream.h>
#include <conio.h>
Header section
#define phi 3.14
main()
{
float radius, area, cir; -- Declaration section
clrscr();
cout<<\nEnter the radius value :;
cin>>radius;
area=phi*r*r;
cir=2*phi*r;
Executable statements section
cout<<\nThe area of the circle is = <<area;
cout<<\nThe circumference of a circle = <<cir;
getch();
}
Do you find it difficult to understand? No problem, You will learn all commands and formats in
the forthcoming lessons.
Introduction to C++ for class XI by P.N
14
Purpose
To activate the menu bar
To save a file
Load a file
To create a new file
Exit turbo C++ editor
To get help facility about Turbo c
To compile a source file
To compile and run a file
Select FileOS Shell to exit from C++ temporarily and goes to the DOS prompt. By typing
EXIT, it returns to the Turbo editor. By default the turbo editor gives the file name as
NONAME.CPP, you can change the name of the file while saving the file.
Steps involved while running a program
A C++ compiler is system software that converts a C++ program into machine language program.
It helps to create the executable version of a program. The steps involved in compilation process
is as follows
a.
b.
c.
d.
Every step uses several programs of C++ compiler to complete the step.
Source code creation
Source code is a program consisting of statements of C++ language. It is created in turbo editor
with an extension .CPP. Example: average.c
Compiling
A source program is compiled to debug the errors, if any errors are occurred then that is displayed
in the screen. After removing all the errors, an object file with an extension .obj is created. It is
also called as intermediate file. Example: average.obj
Linking
It is the process of linking the object code with the code of the library functions that are used by
the same program. The resultant file is called executable file and that has the extension as .EXE
Example: average.exe
Executing
Once the EXE file is created it can run in any folder on any machine without the help of turbo
C++ compiler also. To execute a file, just type the name of the file (eg. c:\>average) in the
prompt.
Introduction to C++ for class XI by P.N
15
2. STATEMENTS
An instruction with its parameter is called as statements in C++ language. These are placed in the
body of the program or function. The instructions of C++ language are classified into three types
such as input, processing and output.
The term input refers to reading data from the standard input devices, processing refers to set of
executable statements for calculation and output refers to producing result on standard output
device. Some of the functions for each of this category are described here.
2.1 Input and output statements
Input function
C++ language provides set of functions for assigning value to the variables. Data can be supplied
to the variables in the following ways
a. Assignment statement
b. cin function
In the assignment method values are directly assigned to the variables in the program itself. For
example, r=5.5, phi=3.14 etc.
The second cin function method helps to supply data in an interactive method at the run time of
the program.
cin>> function
The cin (Console Input) function is used to accept input from the user to the variables. It is made
available to the program by including <iostream.h>. It uses extraction operator (>>) to assign data
into the variable. The syntax of cin function is
cin>>v1>>v2>>v3; where v1, v2 and v3 are variables for which data will be given.
Example
int x,y;
cout << "Enter two numbers : ";
cin>>x>>y;
Entering data
While giving data to the variables of cin statements, data must be separated by blank space(s) or
by separate line.
Let a=10, b=20, c=12.75 and d=NETHRA. The different ways to supply data for the variables
of scanf are as follows
Scanf statement format
cin>>a>>b>>c
cin>>a>>c>>d
16
Output statement
Output statements are used to display the result of any calculation in the screen, file or printer.
The most common output statement used in C++ language is cout function.
cout function
It is a standard output function in C++ language. It is used to display the captions (messages) and
the result of any numerical calculations. This function transforms the result or data from the
memory to the standard output device. The general format of printf function is as follows
cout<<Message or cout<<Message<<variable
The insertion operator(<<) inserts the data that follows into the standard console device
(eg.Monitor)
here Message can be any text enclosed in double quotes( ) and the variable refers to the name
of the variable whose value is to be printed. The escape sequence of characters like \n, \t, \b etc.
can be used to get appropriate space etc in the output.
Some of the control string characters are as follows
\n
\t
\a
----
Example:
cout<<\n Hello Everybody;
cout<<\n My name is <<name<< and I am studying in <<class<< th standard;
cout<<\nResult : a \t b; cout<<a<<\t<<b;
2.2 Control statements
Programs so far we discussed use simple statements and every statement is executed only once.
But in some circumstances it may be required to repeat set of statements depending upon the
condition being tested. The control statements of C++ language helps to decide the order of the
execution based on certain condition. These statements can be used mainly for the following
purpose
Branching
After performing logical test, the appropriate block of statements is executed based on the result
of the logical test. This is known as branching.
Example: Ifelse statement
Selection
It is a special kind of branching that selects one group of statements from the available set of
statements.
Example: Switchcase
Looping
The set of statements is repeated continuously until the given logical condition is satisfied.
Example: for statement, while and dowhile
Introduction to C++ for class XI by P.N
17
is
condition ?
True
Statement part-1
False
Statement part-2
Execution
First the expression is evaluated to check whether it is true (non-zero) or false (zero) and then the
statement part 1 is executed if the value is true, otherwise the statement part 2 is executed.
Example
a. if (age>18) printf(\n Eligible for voting);
b. if(mark1<35 || mark2<35 || mark3<35) printf(\nThe result is fail);
c. if((a>b)&&(a>c))
{ big=a;}
d. if ((b*b-4*a*c)>0)
{
x1=(-b+ sqrt(d))/2*a;
x2=(-b-sqrt(d))/2*a;
printf(root 1= %f root 2 = %f,x1,x2);
}
e. if ((strcmp(result,PASS)==0) && average>75)
printf(You got distinction);
18
if-else format
The extended version of if statement is the if-else format. The general format is as follows
if (condition)
{
statement part-1;
}
else
{
statement part-2;
}
statement part-3;
Execution
After evaluating the condition of if statement, if the result is true then the statement part-1 is
executed and then control is transferred to statement part-3. If the result of the expression is false
then it executes the statement part-2 and then it goes to statement part-3.
Flowchart for if-else
is
condition
?
False
Statement part-1
True
Statement part-2
Statement part-3
Example
a. if(b>c)
printf(\nB is the biggest number);
else
printf(\nC is the biggest number);
b. if(sex==M)
{
tax = (grosspay-70000)*20/100;
}
else
tax=0.0
c. if(n==0)
printf(The number is zero);
else
printf(The number is non-zero);
d. if(n%2 ==0)
printf(\n The given number is even);
else
printf(\n The given number is odd);
Introduction to C++ for class XI by P.N
19
Syntax 2
if (condition-1)
{
if(condition-2)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
if (condition-1)
{
statements;
}
else
{
if(condition-2)
{
statements;
}
else
{
statements;
}
}
20
In switch statement exp stands for expression, it can be a variable or arithmetic expression but the
result should be a integer value. The case labels (prefixes) v1, v2vn cab be a integer value or
character constant.
Execution
First the value of the expression is calculated and then it is compared with the case label starting
from v1 to vn. If a match is found then the set of statements of that case label is executed till the
break statement. If no match is found in between v1 to vn then the statements given in default
part will be executed. The default statement is optional.
The break statement is used to exit out of switch statement and the
following statement of switch.
statements;
}
Condition is a relational or logical expression that should produce the result as either true or false.
The statements in the body of the loop are an executable statement(s), which can be simple or
compound statement. In case of more than one statement, it should be enclosed in the curly
braces.
Execution
The statements in the body of the loop are executed repeatedly as long as the condition in the
while statement is true ( non zero ). If the condition becomes false then it goes to the statement
following the while statement.
21
Flowchart
is
condition
?
True
False
Statement in body
of the loop
statements;
} while (condition);
Condition is a relational or logical expression that should produce the result as either true or false.
A semicolon must be given at the end of the condition.
Execution
First the statements in the body of the loop are executed then the condition is tested. If it is true
then again the body of the loop is executed. This is repeated continuously as long as the condition
in the while statement is true ( non zero ). If the condition becomes false then it goes to the
statement following the while statement.
Flowchart
Statement in body
of the loop
True
is
condition?
False
22
do-while
Condition is placed at the end of the
loop
At least once the body of the loop is
executed without testing condition
Used rarely
control= exp1/Variable
is
Condition
exp1 vs exp2 ?
False
True
Execute the body of
the loop
23
Execution
a. First the expression-1 of for loop is evaluated ie. initial value is assigned to index or
control variable
b. The value of index variable is tested with expression-2
c. If the result of above step is true then the body of the loop is executed, otherwise the
control is transferred to the statement that follows for loop.
d. Now the index value is incremented with the help of expression-3. Go to step (b) and
repeat this procedure as long as the condition is true.
3.4 Rules of for loop
1. More than one variable can be initialized in the for loop separated by commas.
Example: for(i=0,j=5; j<10;i++,j++)
printf(%d %d,i,j);
2. Expression-2 in the for loop is called test condition and it can be a compound relational or
logical expression.
Example: for(i=10,j=100; i<=100 && j>10;i++,j--)
printf(%d %d,i,j);
3. We can also omit one or more expressions in the for loop
Example 1
Example 2
Example 3
i=0;
i=0;
i=0;
for(; i<=10;i++)
for(; i<=10;)
for(; ;)
printf(%d,i);
{ printf(%d,i);
{ printf(%d,i);
i++; }
i++;
if(i>100) break; }
4. A for loop can be used to create time delay in the program by executing null statement
Example: for(i=0;i<=1000;i++); here the body of the loop contains just semicolon (;). It is
called null statement.
5. A for loop without any section and without break point in the body of the loop is called as
indefinite loop.
Example: i=10;
for( ; ; )
{printf(%d,i);
i++);
The body of the loop does not contain break, so loop is never terminated
6. A for loop within another for loop is termed as nested loop.
Example
for(i=0;i<5;i++)
{
for(j=1;j<10;j++)
{
printf(%d %d,i,j); Inner loop
Outer loop
}
}
Introduction to C++ for class XI by P.N
24
7. Every for statement in the nested loop should have unique index variable.
Example
for(i=0;i<5;i++)
{
for(i=1;i<10;i++)
This is not valid
{
printf(%d %d,i,i);
}
8. Control can be transferred at any point from the for loop to some other part of the program
using break statement.
Example
for(i=1;i<=10;i++)
{ printf(%d,i);
if((i%7)==0) break;
}
Break vs Continue
The continue statement can be used in any loop statement like break. On executing break
statement, the control is transferred out of the loop. But the continue statement is used to skip the
remaining part of the loop and continues with the next cycle or iteration of the same loop.
Example 1
Example 2
for(i=0;i<=20;i++)
for(i=0;i<=20;i++)
{
{
if(i%3!=0)
if((i%3)==0)
continue;
break;
else
else
printf(%d,i);
printf(%d,i);
}
}
On executing example 1 coding, it produces the result as 3, 6, 9, 12, 15 and 18. The second
example produces the result as 0, 1 and 2.
4. Functions
4.1 Library functions
The C++ language supports for several types of library functions for variety of purposes. These
functions also called as built-in functions or ready-made functions. Every function is a pre-written
program that is stored in the form of header files. The compiler of C++ language evaluates these
functions when called in the program and the results are returned. The general format of library
function is
function(arguments)
Every function requires arguments that can be a variable, constant or expression. The result type
of a function varies from function to function. Some of the common header files are as follows
S.No
Header file
Used for
Example functions
1.
2.
3.
<iostream.h>
<conio.h>
<math.h>
4.
5.
6.
<string.h>
<stdlib.h>
<time.h>
cin / cout
getch, clrscr, gotoxy
abs, sqrt, pow
strlen, strcpy, strcat
rand, exit, atof
time, difftime, clock
25
26
Example
a. rand() gives the value as 346, it depends upon the machine and compiler.
Note: The function srand(x) is used to initialize the random number with a seed value, so that for
every seed it generates a different random number.
Example
a. srand(645)
rand() gives the result as 26759
b. srand(3455)
rand() gives the result as 16837
7. Trigonometric functions
Some of the trigonometric functions and usage are given below
S.No
1.
Function
name
sin(x)
2.
3.
4.
cos(x)
tan(x)
exp(x)
Argument type
Used for
Example
27
Function call
A function can be called from any part of the program just by the name of the function with its
proper arguments. Same function can be called any number of times in the program as follows
Variable = name(arguments) or name(arguments);
Name refers to the name of the function and arguments refer to the name of the variable,
constants or simple expressions.
Eg. fact(n);
ncr=fact(n)/(fact(r)*fact(n-r));
Return statement
It returns the result to the calling place of the program. The data type of the value to be returned is
decided based on the data type given in the declaration of the function. A program can have any
number of return statements but it can return only one value at a time (ie. For Each call) A
function with void data type cannot return any value.
Scope of the variables
The visibility of the variables in the function or program is termed as scope of the variable. It
refers to the availability of the variables in different parts of the program.
Example:
#include<iostream.>
int factorial(int k);
------- Function prototype
void main ()
{
int n,fact;
cout <<"Enter the number whose factorial has to be calculated" << endl;
cin >> n1;
fact=factorial(n); ------ call to function factorial
cout << "The factorial of " << n << " is : " << fact << endl;
return(0);
}
int factorial(int k) ------- function declaration
{
int i=0,f=1;
if(n<=1)
{ return(1); } --- return statement with a value
else
{
for(i=1;i<=k;i++)
{
f=f*i;
}
return(f);
--- return statement with a value
}
}
Introduction to C++ for class XI by P.N
28