Sunteți pe pagina 1din 28

Contents

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

Input and output statements


Control statements
IfElse statement
Switch case statement
Programs

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.

Advantages of C++ language


a.
b.
c.
d.
e.

It is a low level and system implementation language


It has a relatively clear and mature standard
C++ command are much familiar and user friendly
C++ programs are very fast and efficient compared to other high level language programs
A program written in C++ language can be run on any computer without any modification.
This is called portability of the programs
f. The object oriented programming language feature helps to create and simulate real time
entities in the programming model.
g. C++ provides rich set of library functions for variety of purpose; it also allows adding our
own functions as library functions.
Disadvantages
a.
b.
c.
d.

It is not a pure object oriented language


Does not provide strong data type checking
Difficult to develop graphic applications like GUI
Does not support dynamic memory allocation like pointers in C++

Steps in Learning C++ Language


Like any communication language, you should learn all the basic concepts of C++ language
thoroughly. The instructions of C++ language describe the usage of keywords with constants or
variables. A program represents the set of instructions to solve a particular problem. A bug is
called an error in the program and debugs stands for correcting the errors of the program. The
term software stands for set of programs and documentation about a problem.
Let us demonstrate the steps in learning C++ language as flowchart.
Prepare your mind to
Learn C++ language

Read Character set of


C++ Language

Read variables,
Constants and keywords

Introduction to C++ for class XI by P.N

Practice syntax of
Statements and functions

Create program
For the problem

Run the program


Yes
Modify the program

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

Introduction to C++ for class XI by P.N

1.3 Identifiers or Variables


It refers to the user defined names consisting of letters and digits, mainly serves for identifying
the variables, functions, arrays, structures etc. The formal definition of a variable is that it is a
quantity whose value can be changed during the execution of the program. Identifier identifies the
data stored in memory locations by a unique address.
Rules for defining a variable is as follows
a. A variable can contain alphabets, digits and underscore
b. A variable name can be up to 8 characters long. In case of more than 8 characters, the
remaining characters are ignored. Some versions of C++ accepts upto 40 characters.
c. The first character of the variable must be an alphabet
d. The character underscore is used to link between two words of long identifiers
e. You can use either upper case or lower case, but the lower case letters are commonly used
f. It is advised to give meaningful names for the variables so that they can be easily identified in
the lengthy program.
Types of Variables
C++ language provides rich set of data types for declaring variables. The type of the variable
depends upon the data what we are assigning to the variable. But all those variables should be
declared at the beginning itself. Some of the basic types of variables are given below
Variable type
Declaration format
Example values
Integer
int a,b;
a=20;b=40;
Real
float x,y;
x=20.56; y=0.8876;
Character
char choice
choice = y;
String
char name[20];
name[]=adhavan
Table 3.3
Note: You can declare specific type of integer or the lengthy format of real numbers using the
suitable keywords given in the later sections.
Example
The following table contains variables and also states whether it is valid or invalid with reason.
Variable
gross_sal
pay1
$name
net salary

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

Keyword cannot be used


Comma is not allowed
First character is given as digit
- is not allowed
Capital letters are allowed as identifiers
But accepts only the first 8 characters
Underscores are allowed
Table 3.4

Introduction to C++ for class XI by P.N

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

Let us see each of the above mentioned constants in detail.


Numeric constants
Digits and decimal point form a numeric constant. This can be used for arithmetic calculations.
There are two types of numeric constants such as integer and real.
Integer constant
A number without decimal point is called integer constant.
Example: 2922,
-4354,
0,
20331, 10001
An integer number can also be given in the following three formats.
Decimal
It consists of digits 0 through 9, preceded by an optional + or sign.
Example: -8421,
0,
4123, +9993
Octal
It consists of digits 0 through 7 with leading 0.
Example: 0456, 0,
05731
Hexadecimal
It consists of digits 0 through 9 and A through F. These digits are preceded by 0X or 0x.
Example: 0xbc8,
0X0, 0X148A,
0x1243
The decimal type of integer constant is mostly used in our programs. You can also restrict the
usage of integer constants to small or big using its sub types. These are explained in data types
topic.
Real or Float
A number with decimal point is called floating-point number. A real number can be given in three
different ways namely float, double and e-notation.

Introduction to C++ for class XI by P.N

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

Rules for writing character constants


a. A character constant is either a single alphabet, digit or special character enclosed within a
single quotes( ' ). Ex. #
b. Character constant should contain at most one character
c. A string constant is a sequence of characters enclosed within double quotes.
d. A character constant has an equivalent integer value but the string constants does not have the
equal value.
e. Escape sequences can be used to substitute the additional double quote in string constant. For
example My father\s aim was to educate me well, this is equivalent to My fathers aim
was to educate me well.
Example
The following table shows some of the valid and invalid constants with reason.
Constant
Valid/Invalid
Reason
458921U
Valid
U represents unsigned integer constant
15,234
Invalid
Comma is not allowed
-99.8797
Valid
Real constant
25.756e-05
Valid
Exponential form
5.5e 4
#78.45
0XAB78
-67543
89.56e9.6
41e8
834343L
2343.44.4

Invalid
Invalid
Valid
Invalid
Invalid
Valid
Valid
Invalid

Blank space is not allowed


Special character is not allowed
Hexadecimal integer
Beyond the range of integer
Exponent value must be integer
Exponential form
Long integer form
Two decimal points are not allowed
Table 3.5

1.5 Data types


Data is a fact about people or a thing. Data types of C++ language are mainly used to classify the
data into different category for its storage and retrieval in memory. The memory requirement of
data type decides the possible range of values for that particular type of variable or constant. The
following table summarizes the different data types that can be used for both variables and
constants as described in the previous sections.
Data type
char
short int
int
unsigned
int
long int
float
Double

Bytes
required
1 (8 bits)
1 (8 bits)
2 (16 bits)
2 (16 bits)

Purpose

Range of values

To store a single character


To represent small integer
To represent integer quantity
To represent only positive integers

Any single character


-128 to 127
-32768 to 32767
0 to 65535

4 (32 bits)
4 (32 bits)

To represent big integer numbers


To represent a floating point
number ( precision is 8 digits)
To represent a very big or small
real number( precision is 16 digits)

-231 to 2 31-1
3.4e-38 to 3.4e+38

8 (64 bits)

Introduction to C++ for class XI by P.N

A real number with 16


digits precision.

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

C++ Language format


x* (-y)
(-x)+(-y)
a*b/c
a*x*x+b*x+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.

Introduction to C++ for class XI by P.N

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.

a>b, (25>75) the result of this condition is false


a<(b+50), the result of this condition is true because 25 < (75+50) is true
(a+b)==100, the result is true since (75+25) is equal to 100.
(a!=b), the result is true since 25 is not equal to 75.

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

Introduction to C++ for class XI by P.N

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;

Introduction to C++ for class XI by P.N

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

Equivalent simple expression


a=a+10
a=a-10
a=a*(a+b)
a=a%b
b=b/2.5
a=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

C++ language expression

ax2+bx+c

a*x*x+b*x+c

-b
--2a

-b/(2*a)

a
b
c
--- + --- + --b
c
d

a/b + b/c + 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

c. Function references are executed


d. Multiplication and division is performed
e. Finally addition and subtraction is performed.
Example
Consider the following expression for the values of a=5, b=3 and c=2.
Y = a/c + b*c - ( a%b ) + b/c
Let us calculate the value of Y using the hierarchy rule
Step 1: Y = 5/3 + 3*2 (5%3) + 3/2
Step 2: Y = 5/3 + 3*2 2 + 3/2
Step 3: Y = 1.6 + 6 2 +1.5
Step 4: Y= 9.1 2
The result is 7.1
Relational Expression
An expression consisting of operands and relational operator is termed as relational expression. It
helps to compare two quantities and produces the result as either true (non-zero) or false (zero).
The general format of relational expression is
Operand1 <RO> Operand2
Where operand1 and operand2 can be a variable, constants or arithmetic expressions and RO is
relational operator.
Note: If an operand is arithmetic expression, first it is evaluated then the result is compared.
Example
Let us consider a=20, b= 10 and c=5. Evaluate the following relational expression and find the
final result of each.
Relational expression
a>b
a>(b+c)
5*b < (a+c)
2
a +b2 > (a+b)2

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

(a+b)>c && b>c


False && True
a<b || b<c
False || Flase
b>a && b>c
True && True
Note: Both relational and logical expressions are used with
dowhile and while statements.

Result
False
False
True
decision statements such as IF,

1.8 Structure of a C++ program


The lessons so far you have studied dealt with the basics of C++ language such as constants,
variables, operators and expressions. Let us turn our focus towards the programming side. As you
studied earlier, program is nothing but set of instructions that solves a problem. A program in
C++ language consists of set of blocks or sections. The structure of a C++ program is given
below.
Sections
Header section

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

1.9 Turbo screen layout


Turbo C++ contains a built-in screen editor as part of the compiler. The basic environment of
Turbo C++ is called Integrated Development Environment (IDE). It provides various tools like
menu bar, status bar, scroll bar and editing area at one screen. The starting screen of turbo C++ is
loaded by giving the command tc from the turbo C++ files folder (Usually TC folder). Some of
the important commands of Turbo C++ are as follows
Key/Command
F10
F2 / Alt+FSave
F3 / Alt+FL
Alt+FN
Alt+X
F1
F9
Ctrl+F9

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.

Source code creation


Compiling
Linking
Executing

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

Data input methods


10 20 12.75 or 10 20 or 10
12.75
20
12.75
10 12.75 NETHRA

Rules for cin statement


Variable must be separated by >> sign
Data reading is aborted when data does not match to the variables
The data which are not read in the current line is assigned to the next cin statement
Introduction to C++ for class XI by P.N

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

----

to print data in a new line


to leave one tab space ( normally 5 spaces)
to create beep sound

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

2.3 The if-else statement


It is a logical conditional statement, which uses either relational or logical expression. It executes
one of the two possible block of statements based on the result of the condition given in the if
statement. The general format of if statement is as follows
if (condition)
{
statement part-1;
}
statement part-2;
Condition is either relational or logical expression and it must be placed in parenthesis and the
statement parts contain one or more executable C++ statement.
Flowchart

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);

Introduction to C++ for class XI by P.N

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

Nested if-else statement


An if-else statement within another if statement is called nested if statement. You can nest any
number of if statements in if part, else part or in both. The two different nested if statement is as
follows
Syntax 1

Syntax 2

if (condition-1)
{
if(condition-2)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}

if (condition-1)
{
statements;
}
else
{
if(condition-2)
{
statements;
}
else
{
statements;
}
}

Rules of if-else statement


The condition of the if statement should be either relational or logical expression. The result
of the condition should be either zero(false) or non-zero(true)
Statements can be either single or compound. In case of more than one statements enclose
within the braces ({ }).
The else part is optional in if statement
Any number of nesting is allowed
If condition contains more than one clause in expression then it must be given in parenthesis.
2.4 The switch Statement
The switch statement is a multiple branching statement. A single switch statement can be used to
replace the nested if statements. It helps to select a particular group of statements among several
groups of statements. This selection is based on the expression given in the switch statement. The
general format of switch statement is as follows
switch(exp)
{
case v1 :
..
break;
case v2 :
..
break;
case vn :
..
break;
default :
..
break;
}
Introduction to C++ for class XI by P.N

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.

control is passed to the

Rules of switch statement


The expression in switch statement must produce the result as integer value. If it is a
character type then the equivalent integer value is considered
Break statement between case labels transfers control out of switch statement, otherwise it
executes the consecutive case blocks also
If none of the case labels are matching with case expression then the default part is executed
The case labels must be unique
Switch is an alternate statement for nested if statement
3. Control statements
3.1 The While statement
It is a looping statement that executes set of statements repeatedly until some condition has been
satisfied. The general format of while statement is
while (condition)
{

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.

Introduction to C++ for class XI by P.N

21

Flowchart

is
condition
?
True

False

Statement in body
of the loop

Rules of while statement


Condition in while should produce the result as either true or false
More than one statement in the body of the loop must be enclosed in braces
Break statement can be used to come out of while if necessary.

3.2 The do-while statement


This is also a looping statement similar to while statement except that the condition is placed at
the end of the loop. So it is assured that at least one time the body of the loop is executed. The
general format of do-while statement is
do
{

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

Introduction to C++ for class XI by P.N

22

Difference between while and do-while


While
Condition is placed at the beginning
of the loop
Body of the loop is executed only
when condition is true
It is used more frequently in many
programs

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

3.3 The for Statement


The for loop is the most commonly used statement in many programs for repeated calculations. It
increments the counter variable automatically. The for loop works well where the number of
iterations of the loop is known before the loop is entered. The general format of for statement is
for (exp1;exp2;exp3)
{
.
statements
.
}
exp1, exp2 and exp3 are the expressions and these are called loop controlled parameters.
The for statement consists of three important parameters namely initialization (exp1), test
condition (exp2) and increment(exp3). If the statement block is only one statement, the braces are
not necessary.
The following code will print AEJC, MUMBAI times:
for (i=0; i<10; i++) printf("\n AEJC, MUMBAI ");
Flowchart of for loop

control= exp1/Variable

is
Condition
exp1 vs exp2 ?

False

True
Execute the body of
the loop

control = increment exp1


variable
with exp3

Introduction to C++ for class XI by P.N

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>

Introduction to C++ for class XI by P.N

Standard input and output functions


Console input and output functions
Mathematical
and
trigonometric
functions
String manipulation functions
Standard library functions
Time related functions

cin / cout
getch, clrscr, gotoxy
abs, sqrt, pow
strlen, strcpy, strcat
rand, exit, atof
time, difftime, clock

25

Some of the most useful library functions are explained.


1. sqrt function
This function is used to find the square root of the given value. The argument of the sqrt function
must be a non-negative real quantity. The general format is sqrt(x). Suppose that if the value of x
is negative number then the C++ compiler produces the error message.
Example
a. sqrt(81.0) gives the result as 9.0
b. sqrt(b*b-4*a*c)
2. abs function
It produces the absolute value of the given number. If the number is negative then it gives the
equivalent positive number. Suppose that if the argument is a positive number then it remains
same. The general format of the abs function is abs(x), where x is a integer number.
Example
a. abs(-232), the result is 232
b. abs(456), the result is 456
c. The result of abs(0) is 0
Note: The function fabs() is used to find the absolute value of the floating point number.
3. pow function
The function pow stands for power. The general format of this command is pow(x,y), where x and
y are of floating point numbers. The pow(x,y) is equivalent to xy
Example
a. pow(3.0,3.0) gives the result as 27.0
b. x=5, pow(x+2,2) gives the result as 49.0
4. fmod function
This function is used to find the remainder of a number divided by another number. The general
format of this function is fmod(x,y) where the arguments are float numbers. It divides the value
of x by y and gives the remainder as result.
Example
a. fmod(99.0,10.0) produces the result as 9
b. fmod(100,10.0) gives the result as 0.0
5. ceil function
It returns the ceiling value, that is, the smallest integer greater than or equal to the given number.
The general format of this command is ceil(x), where x is a floating point number.
Example
a. ceil(7.9) gives the result as 8
b. ceil(-5.6) gives the result as 5
6. rand function
It returns a random number as the result. A random number is a number, which cannot be
predicted. It is used in several places where the samples are to be tested with large number of
data. The general format of the function is rand(), the important point to note here is that it does
not take any parameter.
Introduction to C++ for class XI by P.N

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

Real value in the


form of radians
--do---do-Real value

To find the sine value of x

Example

To find the cosine value of y


To find the tangent value of x
Calculates exponent value of x

User Defined Function / Functions in C++


A function in C++ allows the user to define own functions. A function is defined in some part of
the program with block of statements and it can be called from any part of the program. It helps to
implement the modular programming concept in the programming.The general format of the
function is as follows
Data_type name ( parameter1, parameter2, ...)
{
.
statements
.
}
data_type is the data type of the result to be returned, void indicates it returns NULL.
name is the name of the function by which it will be possible to call the function.
Parameters are the variables that receive data from the calling place. All parameters must
be separated by commas and declared by the corresponding data type.
statements is the body of the function and it must be enclosed by {}
Function Prototype
It is the declaration of the function at the beginning of the program with its data-type, name of the
function and parameters followed by semicolon. The body of the function need not be given. It
helps to instruct the compiler that the actual function definition may be defined in some other
point of the program. The general format of the function is
Data_type name ( parameter1, parameter2, ...);
In the place of parameter, the name of the variable is optional, hence only data type can also be
specified.
Introduction to C++ for class XI by P.N

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

S-ar putea să vă placă și