CPP Notes
CPP Notes
A programming language is designed to help process certain kinds of data containing of numbers,
characters and strings and to provide useful output known as information
The task of processing data is accomplished by executing a sequence of precise instructions called a
program.
These instructions are formed using certain symbols and words accordingly to some rigid rules known
as syntax rules.
Every program instruction must confirm precisely to the syntax rules of the program.
1. Letters.
Uppercase(A-Z), Lower Case(a-z)
2. Digits:- 0..9
3.Special characters:-
, & . ^ ; * : - ? + ‘ < > “ # ! | \(backslash) /(slash) ~ {} [] () $ % etc.
4.White Spaces:
Blank Space.
Horizontal tab
Vertical tab.
New Line
Form Feed
Trigraph characters:
Many non- English keywords do not support all the special characters. The concept of trigraph
sequences to provide a way to enter certain characters that are not available on some keyboards. Each
trigraph sequence consists of three characters (two question marks followed by another character).
Trigraph Characters:
??= #
??( [
??/ \
??) ]
??‘ ^
??< {
??> }
??- ~ (Tilde)
C++ Tokens: Tokens are individual words and punctuation marks in passage of text. In C++, program
the smallest individual units are known as C++ Tokens. C has six types of Tokens.
Keywords:
keywords are the words that convey a special meaning to the c compiler. The keywords cannot be used
as variable names because by doing so.
auto break case char const continue default do double else enum extern float
for goto if int long register return short signed sizeof static struct switch
Identifiers:
Identifiers are used as the general terminology for the names of variables, functions and arrays. These
are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or
the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
Examples:
Name Remark
_ a9 Valid
void Invalid as it is a keyword
a_b valid
x* Invalid
ab Invalid –blank space not allowed.
Constants:
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
0xFeeL /* Legal */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. We
can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, we must include the decimal point, the exponent, or both and
while representing using exponential form; you must include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.
3.14159 /* Legal */
314159E-5L /* Legal */
Character constants
Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t').
There are certain characters in C++ when they are preceded by a backslash they will have special
meaning and they are used to represent. Here, we have a list of some of such escape sequence codes:
\\ \ character
\‘ ' character
\“ " character
\? ? Character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
String literals
String literals or constants are enclosed in double quotes "". A string contains characters that are similar
to character literals: plain characters, escape sequences.
We can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
Defining Constants
Syntax:
#include <iostream.h>
#define LENGTH 10
#define WIDTH 5
int main()
int area;
return 0;
}
The const Keyword
we can use const prefix to declare constants with a specific type as follows:
Example :
#include <iostream.h>
void main()
int area;
Variables:
A variable is nothing but a name given to a storage area that our programs can manipulate.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
TYPE DESCRIPTION
Here, type must be a valid C data type .variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:
Examples:
int i, j, k;
char c, ch;
float f, salary;
double d;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:
Examples are:
Data Types:
In the C++ programming language, data types refer to an extensive system used for declaring variables
or functions of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
1. Basic Types:
2. Enumerated Type
They are again arithmetic types and they are used to define variables that can only be assigned certain
discrete integer values throughout the program.
Data Types :
Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ language is rich in built-in operators and provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators.
Arithmetic Operators.
3 * Multiplication
4 / Division
5 % Modulus
#include
void main()
int a=9,b=4,c;
c=a+b;
cout<<"a+b=\n"<<c;
c=a-b;
cout<<"a-b=\n"<<c;
c=a*b;
cout<<"a*b=\n"<<c;
c=a/b;
cout<<"a/b=\n"<<c;
c=a%b;
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Relational Operator:
Relational operators checks relationship between two operands. If the relation is true, it returns value 1
and if the relation is false, it returns value 0.
== Equal to 4==2(false)
&& Logical AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.
Conditional Operator
Conditional operator takes three operands and consists of two operators ? And :. Conditional operators
are used for decision making in C++.
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators.
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operator Meaning
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
Comma Operator:
Comma operators are used to link related expressions together.
For example:
int a,c=5,d;
Program:
#include <iostream.h>
int main()
int a;
float b;
double c;
char d;
cout<<"Size of int=<<sizeof(a)<<”\n”;
cout<<"Size of double="<<sizeo©<<”\n”;
cout<<"Size of char="<<sizeof(d)<<”\n”;
return 0;
2 ! ~ ++ -- Right Left
(type) sizeof
Unary operator: + - * &
/* prefix operators */
#include<iostream>
void main()
cin>a>>b;
c = b * (++a) + 5 * (a++);
cout<<“ a = ”<< a;
cout<<“\n b =”<<b;
cout<<“\n c =”<<c;
Output:
a=9
b = 12
c = 153 ( 12 * 9 + 5 * 9)
If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.
If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.
#include<iostream.h>
void main()
int a = 7, b = 12, c;
c = b * (a++) + 5 * (++a);
cout<<“ a =”<< a;
cout<<“\n b = ”<<b;
cout<<“\n c =”<<c;
}
Output:
a=9
b = 12
c = 136 ( 12 * 8 + 5 * 8) .
/* postfix operators */
#include<iostream.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (a++);
cout<<“ a = ”<< a;
cout<<“\n b =”<<b;
cout<<“\n c =”<<c;
#include<iostream>
using namespace std;
int main()
{ int rad;
float pi=3.14,area,ci;
cout<<"\n Enter radius of circle: ";
cin>>rad;
area = pi * rad * rad;
cout<<"\n Area of circle : “<<area;
ci = 2 * pi * rad;
cout<<"\n Circumference : "<<ci;
}
Type Conversion:
The type conversion or type casting refers to the process of changing an entity of one type into another.
1.Implicit conversion.
2.Explicit Conversion
• Implicit Conversion:
It is an automatic type conversion. In a mixed type expression ,data of one or more sub types can be
converted to a super type as needed at runtime. So the program will run correctly.
Ex: long b;
int c;
if (c>b) b=c;
if(b==c) a+=2
Although a, b, c belong to different data types, they will be automatically converted to equal data types
each time.
Data can be lost when floating point representations are converted to integral representations as the
fractional components of the floating point values will be truncated.
Conversely, converting from an integral representation to a floating point one can also lose precision,
since the floating point may be unable to represent the integer exactly.
• Explicit Conversion
The explicit conversion can be made possible to convert one data type to another by forcefully and it is
different from the implicit conversion.
int a=10;
float (a);
• Example2:
double d=6.5;
double b=8.5;
int result=(int)(d)+(int)(b)
2.By using the input/output statements several functions are available for input/output operations
cout<<”factorial of number=”<<fact ;
Control Statements
In a program all the instructions are executed sequentially by default. In some situation we may have to
change the execution order of statements based on condition or to repeat a set of statements until certain
conditions are met .In such situations conditional and control statements are very useful.
Example:
i=i+1;
j=j+1;
2) Selection statements: Here the sequence of the instructions are determined by using the result of the
condition.
Example:
if(x>y)
i=i+1;
else
j=j+1
3) Iteration Structure: In which statements are repeatedly executed .These forms program loops.
Example:
for(i=0;i<=9;i++)
{
i=i+1;
}
where the statement i=i+1 will be executed 10 times.
If Statement:
The if staement is a decision making statement.It is used to control the flow of execution of statements
and also used to test logically whether the condition is true or false .It is always used in conjunction with
condition .The statement is used when a question require answer.
Syntax1:
if(condition)
statement;
Syntax2:
if(condition)
{
statements;
}
If the condition is true, then the statements are executed. The statements may be a single or group of
statements.
If-else Statement:
It is two way decision making statement and always used in conjunction with condition .It is used to
control the flow of execution and also used to carry out the logical test and then pickup one of the two
possible actions on the logical test.
It is used to execute some statements when the condition is true and execute some other statements,
when the condition is false.
Syntax:
if(condition)
statements;
else
statements;
When a series of if-else statements are occurred in a program. we can write an entire if-else statement in
another if-else statement called nesting and the statement is called nested if.
Syntax: if(condition)
{ if(condition)
{ statement2;
else {
statement3; }
} else
statement1;
If–else ladder:
Nested if statements can become complex if there are more than 3 alternatives and indentation is not
consistent, it may be different for us to determine the logical structure of the if statement. In this
situation we can use the nested if as the else if ladder.
Syantax: if(condition1)
{ staement1;
else if(condition2)
{ statement2;
else if(condition3)
{ staement3;
Flowchart:
simple if:
• /* check a citizen is eligible for voting */
#include<iostream.h>
int main()
int age;
cin>>age;
int main()
int number;
cout<<“Enter a number : “;
cin>>number;
if((number %2) == 0)
else
cout<<”odd number=.”<<number;
}
• /* check whether a year is leap year or not */
#include<iostream.h>
void main()
int year;
cin>>year;
if((year %100) == 0)
if((year % 400) == 0)
cout<<"leap year=."<<year;
else
else
if((year % 4) == 0)
cout<<"leap year.="<<year;
else
void main()
int marks;
cin>>marks;
cout<<"Distinction";
cout<<"First class";
cout<<"Third class";
else
cout<<"Failed";
#include<math.h>
void main()
float a,b,c,root1,root2;
clrscr();
cin>>a>>b>>c;
/*checking condition*/
if(b*b>4*a*c)
root1=-b+sqrt(b*b-4*a*c)/2*a;
root2=-b-sqrt(b*b-4*a*c)/2*a;
cout<<"\n*****ROOTS ARE*****\n";
else
}
SWITCH CASE:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each switch case.
SYNTAX:
switch(expression)
default : statement(s);
The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
• /* program to simulate a simple calculator */
#include<iostream.h>
void main()
{
float a,b;
char opr;
cout<<"Enter number1 operator number2 : ";
cin>>a>>opr>>b;
switch(opr)
{
case '+':
/* Write a C++ program, which takes two integer operands and one operator form
the user, performs the operation and then prints the result. (Consider the
operators +,-,*, /, % and use Switch Statement) */
#include<iostream.h>
#include<conio.h>
void main()
int a,b,res,ch;
cout<<"\t *********************";
cout<<"\n\tMENU\n";
cout<<"\t********************";
cout<<"\n\t(1)ADDITION";
cout<<"\n\t(2)SUBTRACTION";
cout<<"\n\t(3)MULTIPLICATION";
cout<<"\n\t(4)DIVISION";
cout<<"\n\t(5)REMAINDER";
cout<<"\n\t(0)EXIT";
cout<<"\n\t********************";
cin>>a>>b;
switch(ch)
case 1:
res=a+b;
cout<<"\n Addition:"<<res;
break;
case 2:
res=a-b;
cout<<"\n Subtraction:%d",res;
break;
case 3:
res=a*b;
cout<<"\n Multiplication:"<<res;
break;
case 4:
res=a/b;
cout<<"\n Division:”<<res;
break;
case 5:
res=a%b;
cout<<"\n Remainder:"<<res;
break;
case 0:
exit();
break;
default:
LOOPS:
There may be a situation, when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages:
FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
statement(s);
The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as long
as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition). After the condition becomes false, the for loop
terminates.
• FLOWCHART
FORLOOP
int main()
int n,i,factors = 0;
cin>>n;
if (factors == 2)
cout<<"prime number."<<n;
else
}
/* Write a C++ program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user. */
#include <iostream.h>
void main()
int no,counter,counter1,check;
cin>>no;
check = 0;
if(counter%counter1 == 0)
break;
if(check == 0)
cout<<counter;
}
/* Write a C++ program to calculate the following Sum:
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */
#include <iostream.h>
#include <math.h>
void main()
int counter,f_coun;
float sum=0,x,power,fact;
cin>>x;
fact=1;
fact *= f_coun;
sum=sum+(pow(-1,counter)*(pow(x,power)/fact));
cout<<"SUM : %f",sum);
}
Program to display 10 numbers
#include <iostream.h>
int main ()
{
for( int a = 0; a <=9; a = a + 1 )
{
cout<<"value of a: =\n"<< a;
}
}
cin>>time;
cout<<"\t\t\tVELOCITY AT sec (m/sec) : "<<time;
cin>>velos;
cout<<"\t\t\tACCLERATION AT sec (m/sec^2): "<<time;
cin>>accl;
distance += (velos*time + (accl*pow(time,2))/2);
}
cout<<"\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN INTERVALS OF TIME :
"<<tim_intrval<<distance;
}
/*Write a C++ program to read in two numbers, x and n, and then compute the sum of this
geometric progression:1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the
program computes 1+5+25+125.Print x, n, the sum Perform error checking. For example, the
formula does not make sense for negative exponents - if n is less than 0. Have your program print
an error message if n<0, then go back and read in the next pair of numbers of without computing
the sum.Are any values of x also illegal ? If so, test for them too. */
#include<iostream.h>
#include<math.h>
void main()
{
int s_sum,i,x,n;
cout<<"Enter the values for x and n:";
cin>>x>>n;
if(n<=0 || x<=0)
{
cout<<"Value is not valid\n";
}
else
{
cout<<"Value is valid\n";
s_sum=1;
for(i=1;i<=n;i++)
{
s_sum=s_sum+pow(x,i);
}
cout<<"Sum of series=\n"<<s_sum;
}
}
WHILE LOOP
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax:
while(condition)
statement(s);
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop
FLOW CHART
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result
is false, the loop body will be skipped and the first statement after the while loop will be executed
/* Write a C++ program to find the sum of individual digits of a positive integer.*/
#include<iostream.h>
#include<conio.h>
void main()
{
int num, k=1, sum=0;
cin>>num;
while(num!=0)
k=num%10;
sum=sum+k;
k=num/10;
num=k;
getch();
#include <iostream.h>
void main ()
{
int a = 0;
while( a <=10 )
{
cout<<"value of a:\n"<< a;
a++;
}
}
DO WHILE:
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in
C++ programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.
Syntax:
do
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute
again. This process repeats until the given condition becomes false.
#include <iostream.h>
int main ()
int a = 0;
do
cout<<"value of a: \n"<< a;
a = a + 1;
}
while( a < 9 );
break Statement
In C++ programming, break is used in terminating the loop immediately after it is encountered. The
break statement is used with conditional if statement.
break;
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.
continue;
goto Statement
In C++ programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control
of the program will jump to the label: and executes the code/s after it.
Functions
A function is as self contained block of statements that perform a task .Every C++ program can
be thought of as a collection of these functions. In C++ every program must have a main function to
indicate where the program has to begin its executions.
The program may become too large and complex and as result the task of debugging, testing and
maintaining becomes defficult.If a program is divided into functional part may be independently coded
and later combined into a single unit. These independently coded programs are called subprograms that
are much easier to understand, debug and test. In C, such subprograms are referred to as functions.
Concepts of functions
1. Function Declaration or Function Proto Type.
2. Function Definition.
3. Function Body
4. Function Arguments.
5. Function Call.
Function Declaration
All functions know about other declarations and can call these functions
The number and the type of arguments that must be supplied in a call to the function.
When a function call is encountered, the compiler checks the function call its declaration. So that correct
argument types are used.
Syntax:
ret_type specifies the data type of the value in the return statement.
A Function can return any data type; if there is no return value, the keyword void is placed before the
function name.
The function definition is similar to the function declaration but does not have the semicolon.
The first line of the function is called a function declarator.This is followed by the function body. It is
composed of the statements that make up the function, delimited by braces.
The declarator and declaration must use the same function name, number of arguments, argument types,
and the return type.
If the functions are defined before they are called, then the declarations are unnecessary.
Function Call:
A function is a dormant entity, which comes to life when a call is made to the function. A function call
is specified by the function name followed by the values of the parameters enclosed within parentheses,
terminated by a semicolon.
When the compiler encounters a function call, the control is transferred to the function. Then the
function executed line by line.
If a function does not return a value, the return type in the function definition and declaration is
specified as void. Otherwise, the return type is specified as a valid data type.There may be multiple
return statements.
Function parameters
Function parameters are the means of communication between the calling and the called functions. They
can be classified into Actual parameters and Formal Parameters.
The formal Parameters are parameters given in the function declaration and function definition.
The actual parameters, often known as arguments, are specified in the function call.
#include<iostream.h>
void main()
{
void message();
cout<<"welcome to main function \n";
message();
}
void message()
{
cout<<"welcome to user defined functions";
}
//Program using alert using function.
#include<iostream.h>
void main()
{
void beep();
beep();
}
void beep()
{
cout<<"\a";
}
#include<iostream.h>
void main()
{
float maximum(float a,float b,float c);
float x,y,z,max;
cout<<"enter x,y,z values \n";
cin>>x>>y>>z;
max=maximum(x,y,z);
cout<<“Max==\n"<<max;
}
float maximum(float a,float b,float c)
{
if(a>b)
If(a>c)
return(a);
else
return(c);
else
{
if(b>c)
return(b);
else
return(c);
}
}
#include<iostream.h>
void main()
{
Int cube(int);
int n;
cout<<"Result== \n",cube(10);
cout<<"Enter n value \n";
cin>>n;
cout<<"Result== \n"<<cube(n);
}
int cube(int i)
{
int r;
r=i*i*i;
return r;
}
#include<iostream.h>
void main()
{
long int fact(long int);
long int n,x;
cout<<"Enter n value \n";
cin>>n;
x=fact(n);
cout<<"fact==\n"<<x;
}
long int fact(long int n)
{
long int v=1,i;
if(n==1)
return(v);
else
{
for(i=1;i<=n;i++)
v=v*i;
return(v);
}
}
OUTPUT:
n=5
fact=120.
n=2
v=1*1==>1
v=1*2==>2
n=3
v=1*1==>1
v=1*2==>2
v=2*3==>6
n=4
v=1*1==>1
v=1*2==>2
v=2*3==>6
v=6*4==>24
n=5
v=1*1==>1
v=1*2==>2
v=2*3==>6
v=6*4==>24
v=24*5==>120
#include<iostream.h>
void main()
{
int sum(int,int,int);
int x,y,z,total;
cout<<"Enter x,y,x \n";
cin>>x>>y>>z;
total=sum(x,y,z);
cout<<"sum==” \n"<<total;
}
int sum(int a,int b,int c)
{
int t;
t=a+b+c;
return(t);
}
//Program to find biggest of three numbers using functions.
#include<iostream.h>
void main()
{
void square(int);
int max,i;
cout<<"Enter a value \n";
cin>>max;
for(i=0;i<=max-1;i++)
square(i);
}
void square(int n)
{
float value;
value=n*n;
cout<<"i==”<<n<<”sq==”<<value;
}
OUTPUT:
i=0 sq=0
i=1 sq=1
i=2 sq=4
i=3 sq=9
A parameter cannot be both a formal and an actual parameter, but both formal parameters and actual parameters
can be either value parameters or variable parameters
1. Pass by Value:
Functions in C++ pass all arguments by value. Passing arguments by value means that the contents of
the arguments in the calling function are not changed, even if they are changed in the called function.
This is because the content of the variable is copied to the formal parameters of the function definition,
thus preserving the contents of the arguments in the calling function.
#include<iostream.h>
void main()
int a,b;
cin>>a>>b;
swap(a,b);
cout<<a<<b;
{ int t;
t=a;
a =b;
b=t;
2. Pass by address:
In Call by reference, a function receives implicit references to the argument rather than a copy of its
value. Therefore, the function can modify the value of the variable and that change will be reflected in
the calling function as well.
To indicate that an argument is passed using call by reference, an ampersand sign (&) is placed after the
type in the parameter list.
Advantages
1. Arguments are not copied into new variables, so it provides good time and space efficiency.
2. The function change the value of the argument and change is reflected in the caller.
3. A function can return only one value. In this case we can return multiple values, so pass arguments by
reference .Those modified values are visible in the calling function.
#include<iostream.h>
#include<conio.h>
void main()
int a,b;
cin>>a>>b;
swap(&a,&b);
cout<<a<<b;
Int t;
t=*a;
*a =*b;
*b=t;
#include<iostream.h>
void main()
int n,x;
cout<<“enter n value”;
cin>>n;
x=fact(n);
cout<<factorial=”<<x;
int v=1;
if(n==1)
return v;
else
for(i=1;i<=n;i++)
v=v*I;
return v;
Recursion
A recursive function is defined as a function that calls itself to solve a task until a last call is made which
does not require a call to itself.
#include<iostream.h>
void main()
long n,x;
cout<<“enter integer”;
cin>>n;
x=fact(n);
cout<<“n==<<n<<” factorial ==<<x;
int value=1;
if(num==1)
return (value);
else
value=num*fact(num-1);
return (value);
/* Write C++ programs that use both recursive and non-recursive functions
#include<iostream.h>
#include<math.h>
int main(void)
int a,b,iGcd;
clrscr();
cin>>a>>b;
/* Recursive Function*/
if(n>m)
return GcdRecursive(n,m);
if(n==0)
return m;
else
return GcdRecursive(n,m%n);
/* Non-Recursive Function*/
unsigned remainder;
remainder = p-(p/q*q);
if(remainder==0)
return q;
else
GcdRecursive(q,remainder);
#include<iostream.h>
#include<conio.h>
void main()
{
int sum(int);
int x,n;
cout<<“enter n value\n”;
cin>>n;
cout<<“sum==”<<sum(n);
}
int sum(int n)
{
int sum(int n);
int v;
v=0;
If(n==0)
return (v);
else
{
v=n+sum(n-1);
return(v);
}
OUTPUT”
Enter value
10
Sum==55
//PROGRAM TO FIND SUM OF NUMBERS
#include<iostream.h>
void main()
{
int sum(int);
int x,n;
cout<<“enter n value\n”;
cin>>>n;
cout<<“sum==”<<sum(n);
}
int sum(int n)
{
int v;
v=0;
if(n==0)
return (v);
else
{
for(i=0i<=n;i++)
v=v+I;
return(v);
}
}
OUTPUT”
Enter value
10
Sum==55
Scope and Extent:
Scope: The region of source code which the declaration of an identifier is visible is called the scope of
the identifier.
Extent: The period of time during which memory is associated with a variable is called the extent of
variable.
2. File scope.
1. Block Scope: A block is defined as a sequence of statements enclosed between curly braces{ and }.In
other words a block is a compound statement.
2. File scope:
Variables declared outside all functions are said to have global scope. Global variables can be classified under
two categories:
1. Static or File static variables, whose scope is limited to the file in which it is declared,.
2. Global variables, which accessed across files which are linked together.
Storage Classes:
The life time of a variable is characterized by its storage class. The storage class of a variable indicates the
allocation of storage space to the variable.
Local variables:
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined
at the top of a block.
When a local variable is defined - it is not initialized by the system, programmer must initialize it .
When execution of the block starts the variable is available, and when the block ends the variable 'dies'.(OR) Variable
whose existence is known only to the main program or functions are called local variables. Local variables are
declared within the main program or a function.
Global variables:
Global variable is defined at the top of the program file and it can be visible and modified by any function that
may reference it.
Global variables are initialized automatically by the system when you define them!
Data Type Initialser
int 0
char '\0'
float 0
pointer NULL
Variables whose existence is known to the both main() as well as other functions are called global variables.
Global variables are declared outside the main() and other functions.
#include<iostream.h>
int a = 10; /* global declaration */
int main()
{
int b; /* Local variable */
cout<<a;
b = value(a)
cout<<b;
}
int value(int x)
{
int c; /* Local variable */
c = x + 10;
return(c);
}
The storage classes define the extent of a variable. Storage classes are of four types.
1. auto.
2. register.
3. static.
4. extern.
1. auto variable:
All variables within a function are auto by default. The extent of a variable is defined by its scope.
Variables declared auto can only be accessed only within the function or the nested block within which
they are declared.
They are created when the block is entered into and destroyed when it is exited.
#include<iostream.h>
void autostorage();
void main()
{
int I;
for(i=1;i<=3;i++)
autostorage();
}
void autostorage()
{
auto int x=0;
x=x+1;
cout<<“x==\n”<<x;
}
OUTPUT:
X=1
X=1
X=1
//PROGRAM USING AUTO VARIABLE.
#include<iostream.h>
void main()
{
int fun(int x);
int i,x;
for(i=1;i<=10;i++)
{
value=fun(i);
cout<<i<<value;
}
}
int fun(int x)
{
int sum=100;
sum=sum+x;
return(sum);
}
OUTPUT:
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
10 110
#include<iostream.h>
void main()
{
int fun(int x);
int i,x;
for(i=1;i<=10;i++)
{
value=fun(i);
cout<<i<<value;
}
}
int fun(int x)
{
static Int sum=100;
sum=sum+x;
return(sum);
}
OUTPUT:
1 101
2 103
3 106
4 110
5 115
6 121
7 128
8 136
9 145
10 155
2. Register variables:
C++ allows the use of the prefix register in primitive variable declarations. Such variables are
called register variables, and are stored in the registers of the microprocessor. The numbers of variables
which can be declared register are limited.
If more variables are declared register variables, they are treated as auto variables.
A program that uses register variables executes faster as compared to a similar program without register
variables.
It is responsibility of the compiler to allot register variables .In case the compiler is unable to do so;
these variables are treated as auto variables.
#include<iostream.h>
void main()
{
register int;
for(i=0;i<=2;i++)
{
cout<<“i==\n”<<i;
}
}
3. Static variables:
Static variables are two types
1. Static variables that are declared within function (function static variables) .These variables retain their
values from the previous call i.e., the values which they had before returning from the function.
2. File static variables. These variables are declared outside any function using the keyword static .File
static variables are accessible only in the file which they are declared.
#include<iostream.h>
#include<conio.h>
void staticstorage();
void main()
{
int I;
for(i=1;i<=3;i++)
staticstorage();
}
Void static storage()
{
static int x=0;
x=x+1;
cout<<“x==\n”<<x;
}
OUTPUT:
X=1
X=2
X=3
4. Extern variables:
Global static variables are global to the file in which they are defined. They are used when the same
global variable is referenced in each of the files and these variables must be independent of each other across
files.
The use of global variables is not recommended, as function independence is one of the basic ideas of
modular programming.
When a program spans across different files and we want to have a global variable accessible to all
functions in these files, the keyword extern should be used before the data type name in the declarations in all
the files where it is accessed.
#include<iostream.h>
extern int x=10;
void main()
{
int y=20,z;
z=x+y;
cout<<“z==”<<z;
}
//PROGRAM USING GLOBAL VARIABLE.
#include<iostream.h>
int x;
int y=10;
void main()
{
x=10;
void sum();
Sum();
}
void sum()
{
int sum;
sum=x+y;
cout<<“x==”<<x;
cout<<“y=”<<y;
cout<<“sum==”<<sum;
}
Arrays:
An array is a sequence of data in memory, wherein all data are of the same type, and are placed
in physically adjacent locations.
In C++ .arrays are two types: one dimensional and multidimensional.
The C++ language treats strings as an array of characters, the last of which is the null
character(character with an ASCII value zero).
An array is fundamental data structure that enables the storing and manipulation of potentially huge
quantities of data.
An array stores ordered sequence of homogeneous values.
Homogeneous means that all the values are of the same type.
In The single dimensional array, there will be a single subscript or index whose value refers to the
individual array element which ranges from 0 to (n-1), where n is the total number of elements in the
array.
Declaration:
We must declare the array. It is done at the beginning of the function main () with statement.
Syntax
Example:
Each individual array element is called an indexed variable or a subscripted variable, since both a variable name
and an index or a subscript value must be used to reference the element.
The index or subscript value gives the position of the element in the array
An array size must be a positive integer number or an expression that evaluates to a positive integer number.
Example:
int a[5]={1,5,8,9,0};
Automatic Sizing:
While initializing, the size of a one dimensional array can be omitted.
For initializing an individual array element, a particular array index has to be used.
Example:
a [0]=7;
a [5]=8;
Strings in C++ are represented by arrays of characters. The end of string is marked with a special
character, the null character, which is a character all of whose bits are zero.
The NULL character or string terminator character is represented by another character escape sequence
\0.
Example:
Example:
Multidimensional Arrays:
Arrays with more than one dimension are called multidimensional arrays.
Syntax:
Syntax:
Example:
int a[2][6][8];
Like values, it is also possible to pass values of an array to function. To pass a one dimensional
an array to a called function, it is sufficient to list the of the array, without any subscripts, and size of the
array as arguments.
Example:
The strings are as characters arrays in C++ and therefore the rules for passing strings to functions are
very similar to those for passing arrays to functions.
Example:
output(name);
#include<iostream.h>
#include<conio.h>
Void main()
{
int a[7]={1,2,3,4,5,6,7};
int I;
cout<<“CONTENTS OF THE ARRAY \n”;
for(i=0;i<=6;i++)
cout<<“\t”<<a[i];
}
//PROGRAM TO READ THE NUMBERS USING ARRAYS.
#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],I,n;
cout<<“HOW MANY NUMBERS ARE IN THE ARRAY \n”;
cin>>n;
cout<<“ENETR ELEMENTS \n”;
for(i=0;i<=n-1;i++)
{
cin>>a[i];
}
cout<<“CONTENTS OF THE ARRAYS \n”;
for(i=0;i<=n-1;i++)
cout<<“\t”<<a[i];
}
//PROGRAM TO FIND LARGEST AND SMALL ELEMENT IN THE ARRAY.
#include<iostream>
Using namespace std;
void main()
{
int i,n;
int a[25],large,small;
cout<<“ENTER SIZE OF THE ARRAY \n”;
cin>>n;
cout<<“\n Enter ARRAY ELEMENTS \n”;
for(i=0;i<n;i++)
cin>>a[i];
large=a[0];
small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
else
if(a[i]<small)
small=a[i];
}
cout<<“\n LARGE==”<<large;
cout<<“\n SMALL==”<<small;
}
OUTPUT:
24 6 14 11 8
LARGE==24
SMALL==6
#include<iostream>
using namespace std;
void main()
{
int i,j,k,n;
int a[100],temp;
cout<<“\n ENTER SIZE OF THE ARRAY”;
cin>>n;
cout<<“\n Enter ARRAY ELEMENTS \n;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
If(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
cout<<“\n ELEMENTS IN ASCENDING ORDER \n;
for(i=0;i<n;i++)
cout<<a[i);
}
OUTPUT:
ENTER SIZE OF ARRAY.
8
ARRAY ELEMENTS ARE
91 21 10 7 24 11 2 8
2 7 8 10 11 21 24 91
#include<iostream.h>
void main()
{
int a[10][10],I,j,n,trace;
cout<<“ENTER THE ORDER OF A MATRIX\n”;
cin>>n;
cout<<“ENTER A MATRIX \n”;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
trace=0;
for(i=0;i<n;i++)
trace=trace+a[i][i];
cout<<“trace= \n”<<trace;
}
#include<iostream.h>
#include<conio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int m,n, i, j, k, l,g;
cout<<"Enter the number of rows and column of first matrix\n";
cin>>m>>n;
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10];
int I,j,m,n;
cout<<“ENTER ROW & COL OF A MATRIX\n”;
cin>n>>m;
cout<<“ENTER A MATRIX \n”;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>a[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[i][j]=a[j][i];
cout<<“\n TRANSPOSE OF A MTRIX\n”;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cout<<b[i][j];
cout<<“\n”;
}
OUTPUT:
ENTER ROW & COL OF A MATRIX: 3X4
ENTER A MATRIX
1 2 3 4
5 6 7 8
9 10 11 12
TRANSPOSE OF A MATRIX:
1 5 9
2 6 10
3 7 11
4 8 12
STRINGS
In C++, String is an array of characters. Every string is terminated by a null character. Null character is
indicated by ‘\0’.
Example:
Example:
char s[] =”hello”;
Here ,character array s have characters namely h,e,l,l,o. Apart from these characters a null characters(‘\0’) is
stored at the end of the string. So, the internal representation of the string becomes hello’\0’.
To use string functions, the header file string.h must be included in the program with the statement.
1. strlen() Function:
strlen() function computes the length of the string.
PROGRAM:
void main()
{
char str[]=”welcome”;
cout<<“\n Length==”<<strlen(str);
}
This function computes the length without including the null character.
2. strcpy() function:
Program:
void main()
{
char str1[15],str2[15];
str2[15]=”welcome”;
strcpy(str1,str2);
cout<<“\nstring1==”<<str1;
}
3. Strcat () function:
PROGRAM:
void main ()
{
char str1[15]=”welcome”;
char str2[]=”to c”;
strcat(str1,str2);
cout<<“\n str1==”<<str1;
}
4.strcmp() function:
PROGRAM:
void main()
{
char str1[10]=”welcome”;
char str2[10]=”you”;
If(strcmp(str1,str2)==0)
cout<<“\n strings are equal”;
else
cout<<“\n not equal”;
}
2.Strchr() Function:
strchr() function searches for the first occurrences of the character in the string pointed to by the argument str.
3.strrchr() function:
strrchr() function searches for the first occurrences of the character beginning at the rear end and working
towards the front in string pointed to by the argument str.
4.strstr() function:
strstr() function is used to find the first occurrences of string str2 (terminating character not included) in the
str1.It returns a pointer to the first occurrences of str2 in str1.If match not found ,then null pointer is returned.
5.strspn() function:
strspn() function returns the index of the first character in str1 that doesn’t match any character in str2.
6.strcspn() function:
strcspn() function returns the index of the first character in str1,that matches any of the characters in str2.
7. Strpbrk () function:
strpbrk () function returns a pointer to the first occurrence in str1 of any character in str2 or null if none are
present.
8. strtok () function:
strtok () function is used to isolate sequential tokens in a null terminating string str.These tokens are separated
in the string using delimiters.
strncpy () function copies only left most n characters of the source string to the target string variable.
PROGRAM:
void main()
{
char str1[5]=”abc”;
char str2[5]=”def”;
strncat(str1,str2,2);
cout<<“\n str1==”<<str1;
}
13. Strncmp () function:
Syntax: strncmp () (const char *str1, const char *str2), size_t n);
This function compares at most the first n characters of str1 and str2 .Otherwise, it returns a value less than zero
or greater than zero if str1 is less than or greater than str2, respectively.
PROGRAM:
void main ()
{
char str1 [10] =’abc”;
char str2 [10]=”abd”;
if (strncmp (str1,str2,2)==0)
cout<<“\n str and str2 equal”;
else
cout<<”\n both are not equal”;
}
14.strncat() function:
Syntax: strncat(str1,str2,2);
Adds the string pointed to by str2 to the end of the string pointed to by str1 upto n characters.
PROGRAM:
void main()
{
char str1[10]=”hello”;
char str2[10]=”how r u”;
strncat(str1,str2,2);
cout<<“\n str1==”<<str1;
}
15.atoi() function:
/* Write a C++ program that uses functions to perform the following operations:
To insert a sub-string in to given main string from a given position.*/
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[10];
char b[10];
char c[10];
int p=0,r=0,i=0;
int t=0;
int x,g,s,n,o;
puts("Enter First String:");
gets(a);
puts("Enter Second String:");
gets(b);
cout<<"Enter the position where the item has to be inserted: ";
cin>>p;
r = strlen(a);
n = strlen(b);
i=0;
// Copying the input string into another array
while(i <= r)
{
c[i]=a[i];
i++;
}
s = n+r;
o = p+n;
#include<iostream.h>
#include<string.h>
enum Boolean{false,true};
enum Boolean IsPalindrome(char string[])
{
int left,right,len=strlen(string);
enum Boolean matched=true;
if(len==0)
return 0;
left=0;
right=len-1;
/* Compare the first and last letter,second & second last & so on */
while(left<right&&matched)
{
if(string[left]!=string[right])
matched=false;
else
{
left++;
right--;
}
}
return matched;
}
int main()
{
char string[40];
cout<<"****Program to test if the given string is a palindrome****\n";
cout<<"Enter a string:";
cin>>string;
if(IsPalindrome(string))
cout<<"The given string %s is a palindrome\n"<<string;
else
cout<<"The given string %s is not a palindrome\n"<<string;
getch();
return 0;
}
/* Write a C++ program that uses functions to perform the following operations:
To delete n Characters from a given position in a given string.*/
#include <iostream.h>
#include <string.h>
void delchar(char *x,int a, int b);
void main()
{
char string[10];
int n,pos,p;
puts("Enter the string");
gets(string);
cout<<"Enter the position from where to delete";
cin>>"%d",&pos);
cout<<"Enter the number of characters to be deleted";
cin>>"%d",&n;
delchar(string, n,pos);
getch();
}
// Function to delete n characters
void delchar(char *x,int a, int b)
{
if ((a+b-1) <= strlen(x))
{
strcpy(&x[b-1],&x[a+b-1]);
puts(x);
}
}
/* Write a C++ program to count the lines, words and characters in a given text*/
#include <iostream.h>
void main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
cout<<"KEY IN THE TEXT.\n";
cout<<"GIVE ONE SPACE AFTER EACH WORD.\n";
cout<<"WHEN COMPLETED, PRESS 'RETURN'.\n\n";
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
Cout<<"\n";
cout<<"Number of lines = "<< lines;
cout<<"Number of words ="<< words;
cout<<"Number of characters = "<< characters;
}
Output
KEY IN THE TEXT.
GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS 'RETURN'.
Admiration is a very short-lived passion.
Admiration involves a glorious obliquity of vision.
Always we like those who admire us but we do not
like those whom we admire.
Fools admire, but men of sense approve.
Number of lines = 5
Number of words = 36
Number of characters = 205
/* Write a C++ program that displays the position or index in the string S
where the string T begins, or - 1 if S doesn't contain T. */
#include<iostream.h>
#include<string.h>
void main()
{
char s[30], t[20];
char *found;
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
cout<<"Second String is found in the First String at %d position.\n"<<found-s;
else
cout<<"-1");
}