by
Neethu krishna
C++ is an object oriented programming
language.
C++ was developed at AT & T Bell
Laboratories in early 1980s by Bjarne
Stroustrup.
Set of valid characters that a language can
recognize.
Letters A-Z, a-z
Digits 0-9
Special Symbols + - */ ^ \ ( ) [ ] { } = != < > . ‘ “ $ , : ;
% ! & ? _ # <= >= @
White Spaces Blank space, horizontal tab,
carriage return, newline, form
feed
The smallest individual unit in a program is
known as a token.
C++ has the following tokens :
1. Keywords
2. Identifiers
3. Literals
4. Punctuators
5. Operators
Identifiers are fundamental building blocks of a
program
Used as general terminology for names given to
different parts of a program.
Only alphabetic characters ,digits and
underscore are permitted
The name can not start with digits
Uppercase and lowercase letters are distinct
A declared keyword cannot be used a variable
name
E.g.:- Myfile, MYFILE, date_77, _letter
The words that convey a special meaning
to the language compiler.
Reserved for special purpose and must not
be used as normal identifier names.
ANSI C++ standard defines 32 keywords
E.g.:-
break, int, float, new, public etc.
Literals are data items that never change
their value during the program run.
The different kinds of literals are :
integer-constant
character-constant
floating-constant
string-literal
Whole numbers without any fractional part.
An integer constant must have at least one
digit and must not contain any decimal
point.
It may contain either + or – sign. ( no sign
positive)
Commas cannot appear in an integer
constant.
A character constant must contain
one character enclosed in single
quotation marks.
E.g.:-
‘z’ or ‘A’
Numbers having fractional parts.
Written in 2 forms:
fractional form
exponent form
A real constant in fractional form must have
at least one digit before and after the
decimal point.
It can have + or – sign (no sign +ve).
E.g..:-
2.0, 17.5, -13.0
A real constant in exponent form has two
parts : a mantissa and an exponent
Mantissa integer or real constant
Mantissa is followed by a letter e or E and
the exponent.
Exponent integer
E.g..:-
2.5E05, -0.172e-3
A string literal is a sequence of characters
surrounded by double quotes.
Each string literal is automatically
terminated with a null character ‘\0’.
The size of the string is the number of
characters plus one.
E.g.:-
“abc” size 4
The following characters are used as
punctuators :
( ) Parentheses
[ ] Brackets
{ } Braces
, Comma
; Semicolon
: Colon
* Asterisk
… Ellipsis
= Equal to
# Pound
Operators are tokens that trigger some
kind of computation .
Two types :
unary operators
binary operators
Require only one operand to operate upon.
& Address operator
* Indirection operator
+ Unary plus
- Unary minus
~ Bitwise complement
++ Increment operator
-- Decrement operator
! Logical negation
Require two operands to operate upon.
Arithmetic operators +, -, *, /, %
Logical operators &&, ||
Relational operators <, >, <=, >=, ==, !=
Shift operators <<, >>
Bitwise operators &, ^, !
Assignment operators =, *=, +=, /=, %=, -=
Conditional operator ? :
// Program to print a string
#include<iostream.h>
void main( )
{
cout<<“WELCOME TO C++ PROGRAMMING”;
}
OUTPUT
WELCOME TO C++ PROGRAMMING
// Program to print a string comment
All lines beginning with // are comments.
Compiler does not execute comments.
#include<iostream.h> preprocessor
directive
Statements that begin with # sign .
Processed before compilation.
The above statement tells the compiler to
include the header file iostream in the
program
void main( )
Execution of a program starts from main()
function.
Code for every function is included within a
pair of curly braces { }
A program terminates after executing the last
statement of main()
cout<<“WELCOME TO C++ PROGRAMMING”;
cout standard output stream
Inserts a sequence of characters to the
output stream (monitor).
cout is declared in header file iostream.
So in order to use cout in the program we
included this header file .
Every executable statement must be
terminated by a semicolon ;
C++ provides way to handle different types
of data by providing data types.
Data types are means to identify the type of
data and associated operations of handling
it.
Two types :
Fundamental data types
Derived data types
Fundamental data types are those that are
not composed of other data types.
5 types:
int
char
float
double
void
Integers are represented in C++ by int data
type.
An identifier declared as int cannot have
fractional part.
Require 2 bytes of storage.
Characters can store any member of the
C++ character set.
Characters are represented in C++ by char
data type.
Require 1 byte of storage
Floating point numbers are represented in
C++ by float data type.
Require 4 bytes of storage
Double precision floating point numbers
are represented in C++ by double data
type.
Require twice as much memory as float
(8 bytes )
The void type specifies an empty set of
values.
It is used as a return type for function that
do not return a value.
No object of type void may be declared.
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
int a, b, sum;
cout<<“enter the first value ”;
cin>>a;
cout<<“enterthe second value”;
cin>>b;
sum = a + b;
cout<<“The sum = ”<<sum;
getch( );
}
OUTPUT
enter the first value 5
enter the second value 10
The sum = 15
Derived data types are those that are
derived from fundamental data types.
E.g.:-
enumeration
array
pointers
An array is a finite collection of n elements
of same type referenced under one name.
Arrays can be
one dimensional
two dimensional
multi dimensional
E.g.:-
int a[10];
float b[3][4];
Enumeration is an alternative method for naming
integer constants.
E.g.:-
enum { start, pause, go};
defines 3 integer constants called enumerators
and assigns values to them.
Enumerator values are by default assigned
increasing from 0.
The above declaration assigns
start = 0
pause = 1
go = 2
Enumeration can be named also.
enum status {start, pause, go};
A pointer is a variable that holds a memory
address.
This address is usually the location of
another variable in memory.
The general form of declaring a pointer is
type *ptr;
E.g.:-
char *a;
declares a pointer to a character.
The value of a named constant cannot be altered
during the program run.
Constants are created using the keyword const.
const int n =10;
Must be initialized at the time of declaration.
const a = 5; // const int by default
Variables represent named storage locations,
whose values can be manipulated during the
program run.
Variable declaration
type var_name;
int a, b; //declares 2 integer variables
float c;
Variable initialization
We can give initial values to variables as
int sum = 0;
There are 2 values associated with a
variable :
lvalue
rvalue
rvalue
data value stored in the memory.
lvalue
the address of the memory at which the
data value is stored
Memory 1051 1052 1053 1054 1055
address
Data value of 10 25
the variable
Variable’s A B
name
rvalue of A =10 rvalue of B =25
lvalue of A = 1052 lvalue of B = 1055
Escape sequence Meaning
\a Audible bell
\b Backspace
\f Formfeed
\n newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\\ backslash
\’ Single quote
\” Double quote
\? Question mark
\0 Null
Operator Definition Example
+ Adds values of its 6+5 = 11
operands
- Subtracts the values 6-5 = 1
* Multiplies the operands 6*5 = 30
/ Divide left operand by right 60/5 = 12
operand
% Gives the remainder 60%5 = 0
Modulus or 6%5=1
remainder
The operator ++ adds 1 to its operand and - -
subtracts 1
++a or a++ a = a + 1
Both increment and decrement operators come in
2 varieties
postfix – a++
prefix - ++a
The 2 versions have same effect but they differ
when they appear in an expression.
When the increment/decrement operator
precedes its operand, C++ performs the
increment/decrement operation before using the
value of the operand.
E.g.:-
sum = 0;
count =1;
sum = sum + (++ count);
sum 2 count 2
When the increment/decrement operator follows
its operand, C++ performs the
increment/decrement operation after using the
value of the operand.
E.g.:-
sum = 0;
count =1;
sum = sum + (count++);
sum 1 count 2
Evaluate x = ++y+ 2y if y = 6.
Evaluate b = a+++++a if a=10.
Evaluate z = ++x + x++ if x = 10.
Predict the output :
int n = 7;
cout<<“n++ =“<<n++;
cout<<“n=“<<n;
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
Relational operator determine the relation among
different operands.
Comparison true result 1
false result 0
p q p<q p <= q p >q p >= q p == q p != q
0 1 1 1 0 0 0 1
1 0 0 0 1 1 0 1
3 3 0 1 0 1 1 0
2 6 1 1 0 0 0 1
Operator Definition Example Result
Returns true if both
&& expressions are (6<=6) && (5<3) 0
AND true
Returns true if one
|| of the expression is (6<=6) || (5<3) 1
OR true
Negates the result
! of the expression !(6<=6) 0
NOT
It is a ternary operator, i.e. it requires 3 operands.
expression1? expression2: expression3;
If expression1 evaluates true, then the value of
the whole expression is the value of expression2,
otherwise expression3.
E.g.:-
result = marks >= 50 ? ‘P’: ‘F’;
6>4 ? 9:10; //evaluates to 9
The sizeof operator returns the length (in bytes) if
its operand.
General form is :
sizeof var_name; or
sizeof (type);
E.g.:-
int a;
sizeof a returns 2
sizeof (float) returns 4
A comma operator is used to string together
several expressions.
A group of expressions separated by commas is
evaluated left to right.
E.g.:-
b = (a=3, a+1);
first assigns a the value 3 then assigns b the
value a+1 i.e. 4.
++(post increment), - - (post decrement)
++(pre increment), - - (pre decrement), sizeof, !, unary minus,
unary plus
*, /, %
+, -
<, <=, >, >=
==, !=
&&
||
?:
=
Comma operator
The process of converting one predefined type
into another is called type conversion.
Two types
implicit type conversion
explicit type conversion
Conversion performed by the compiler without
programmer’s intervention.
It occurs when differing data types are intermixed
in an expression.
The compiler converts all operands upto the type
of the largest operand.
E.g.:-
If either operand is float the other is converted to
float.
If either operand is double the other is converted
to double.
Explicit conversion is user-defined.
Explicit conversion of an operand to a specific
type is called type casting.
General form:
(type) expression
E.g.:-
(float)(x+y/2)
converts the result to float
Statements are instructions given to the
computer to perform any kind of action.
Statements are the smallest executable unit
within a program.
Statements are terminated with a semicolon.
The simplest statement is the empty or null
statement.
; //null statement
A compound statement is a sequence of
statements enclosed by a pair of braces { }.
{
statement_1;
statement_2;
.
.
.
.
statement_n;
}
In a program statements may be executed
sequentially, selectively or iteratively.
Sequence : statements are executed
sequentially
Selection : execution of statements depending
upon a condition-test.
Iteration : repetition of a set of statements
depending upon condition-test.
Selection statements allow to choose the
set of instructions for execution depending
upon an expression truth value.
Two types :
1) if
2) switch
General form :
if(expression)
{
statement block
}
If the expression evaluates true the statement
block is executed otherwise ignored.
if(expression)
{
statement_block-1
}
else
{
statement_block-2
}
if the expression evaluates true statement_block-1
is executed otherwise statement_block-2 is
executed
if(a>b)
{
cout<<“a is greater”;
}
else
{
cout<<“b is greater”;
}
if(expression_1)
{
if(expression_2)
statement_1;
else
statement_2;
}
else
{
if(expression_3)
statement_3;
else
statement_4;
}
if(expression_1) statement_1;
else if(expression_2) statement_2;
else if(expression_3) statement_3;
…….
…….
…….
else statement_4;
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
char ch;
float a, b, result;
cout<<“enter two numbers \n”;
cin>>a>>b;
cout<<“enter the operator (+, -, *, / ) \n”;
cin>>ch;
if(ch = = ‘+’)
result = a + b;
else if(ch = = ‘-’)
result = a - b;
else if(ch = = ‘*’)
result = a * b;
else if(ch = = ‘/’)
result = a / b;
else
cout<<“wrong operator \n”;
cout<<“the result is”<<result;
getch();
}
OUTPUT
enter two numbers
5
6
enter the operator (+, -, *, /)
*
the result is 30
Multiple branch selection statement.
This statement successively tests the value
of an expression against a list of integer or
character constants.
When a match is found, the statements
associated with that constant are
executed.
switch (expression)
{
case constant1 : group of statements 1;
break;
case constant2 : group of statements 2;
break;
.
.
.
default : default group of statements;
}
switch evaluates expression and checks if it is
equal to constant1, if it is, it executes group of
statements 1 until it finds the break statement.
When it finds the break statement the program
jumps to the end of the switch selective structure.
If expression was not equal to constant1 it will be
checked against constant2. If it is equal to this, it
will execute group of statements 2 .
If the value of expression did not match any of
the constants the program will execute the
default statement.
switch (x)
{
case 1: cout << "x is 1";
break;
case 2: cout << "x is 2";
break;
default :cout << "value of x unknown";
}
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
int dow;
cout<<“enter the number of the week’s day \n”;
cin>>dow;
switch(dow)
{
case 1 : cout<<“Sunday \n”;
break;
case 2 : cout<<“Monday \n”;
break;
case 3 : cout<<“Tuesday \n”;
break;
case 4 : cout<<“Wednesday \n”;
break;
case 5 : cout<<“Thursday \n”;
break;
case 6 : cout<<“Friday \n”;
break;
case 7 : cout<<“Saturday \n”;
break;
default : cout<<“wrong number of day”;
break;
}
getch();
}
OUTPUT
enter the number of the week’s day
5
Thursday
Allow a set of instructions to be executed
repeatedly.
3 types of loops:
1) for loop
2) while loop
3) do-while loop
1) Initialization expression
gives initial value to the control variable before
entering the loop the loop
2) Test expression
the loop body is executed only if the test
expression evaluates true, otherwise loop is
terminated.
3) Update expression
change the value of the loop control variable.
4) Loop body
the statements that are executed repeatedly
General form is:
for (initialization expn; test expn; update expn)
{
loop body
}
E.g.:-
for(j = 1; j<=10; j++)
{
cout<<j<<“\n”;
}
prints numbers from 1 to 10
General form is:
while (test expression)
{
loop body
}
E.g.:-
j = 1;
while(j<=10)
{
cout<<j<<“\n”;
j++;
}
General form is:
do
{
loop body
} while (test expression) ;
In do-while loop the body of the loop is executed
before testing the condition.
for loop and while loops are entry
controlled loops because the test
expression is evaluated before entering the
loop.
do-while is an exit controlled loop because
the test expression is evaluated after
executing the loop body.
A loop may contain another loop in its body.
This form of a loop is called nested loop.
E.g.:-
for(i=1; i<5; i++)
{
for(j=1;j<=i; j++)
{
cout<<“*”;
}
cout<<“\n”;
}
OUTPUT
*
**
***
****
*****
The jump statements unconditionally
transfer the program control within a
function.
5 types
1) goto
2) break
3) continue
4) return
5) exit()
The goto statement can transfer the
program control anywhere in the program.
The destination of goto statement is
marked by a label.
Label and goto must appear in the same
function.
General form is:
goto label ;
……..
……..
……..
label : ……..
The break statement enables a program to
skip over part of the code.
The break statement terminates the
smallest enclosing while, do-while, for or
switch statement.
Execution resumes at the statement
immediately following the body of the
terminated statement.
while(test expn)
{
stmt_1;
if(val>2000)
break;
stmt_2;
stmt_3;
}
stmt_4;
The continue statement also enables a
program to skip over part of the code, but
instead of termination it forces the next
iteration of the loop.
while(test expn)
{
stmt_1;
if(condition)
continue;
stmt_2;
stmt_3;
}
stmt_4;
The exit() function causes the program
to terminate as soon as it is
encountered.
The return statement is used to return
from a function.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“enter the number”;
cin>>num;
if(num%2 == 0)
cout<<“even”;
else
cout<<“odd”;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num, i;
cout<<“enter the number”;
cin>>num;
for(i=2; i<=num-1; i++)
{
if(num% i == 0)
{
cout<<“not prime”;
exit(0);
}
}
cout<<‘prime”;
getch(); }
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, first=0, second=1, third;
cout<<“enter the number of terms”;
cin>>n;
if(n= =1)
cout<<first;
else if(n= =2)
cout<<first<<second;
else
{
cout<<first<<second;
for(i=3; i<=n; i++)
{
third = first + second;
cout<<third;
first = second;
second = third;
}
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, j, a = 1;
cout<<“enter the number of rows of the triangle”;
cin>>n;
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
cout<<a;
a++;
}
cout<<“\n”;
}
getch(); }
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num, org, rev = 0, rem;
cout<<"Enter any number: ";
cin>>num;
org = num; //save original number for comparison
do
{
rem = num% 10;
rev = rev * 10 + rem;
num = num / 10;
} while (num!=0);
if (org = = rev)
{
cout<<"Given number is a palindromic number";
}
else
{
cout<<"Given number is not a palindromic number";
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, num, sum = 0, avg;
cout<<"Enter the limit ";
cin>>n;
cout<<“enter the numbers”;
for(i=1; i<=n; i++)
{
cin>>num;
sum = sum + num;
}
avg = sum/n;
cout<<“sum =“<<sum;
cout<<“avg =“<<avg;
getch();
}
An algorithm is a logical sequence
of discrete steps that describe a
complete solution to a given
problem
A flowchart is a pictorial
representation of step by step
solution of a problem (algorithm).
Start/stop
Input / Output
Processing
Decision box
Flow of control
Connector
1. start
start
2. Read length and breadth
3 area l*b;
Read l and b
4. print area
5. stop Area l*b
Print area
stop
Write the algorithm and draw the flowchart
to find the maximum of 3 nos
Write an algorithm and draw the flowchart
to find the sum of n nos
Write an algorithm to find the the smallest
of n numbers
Write an algorithm to find the roots of a
quadratic equation
An array is a collection of variables of
same data type referenced under one
name.
Arrays can be
one dimensional
two dimensional
multi dimensional
E.g.:-
int a[10];
float b[3][4];
One dimensional
type array_name[size];
E.g.:-
int a[5];
a[0] a[1] a[2] a[3] a[4]
E.g.:-
int a[5] = {11, 12, 13, 14, 15};
a 11 12 13 14 15
a[0] a[1] a[2] a[3] a[4]
E.g.:-
for(i=0; i<5; i++)
{
a[i] = 0;
}
a 0 0 0 0 0
a[0] a[1] a[2] a[3] a[4]
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, a[100];
cout<<"Enter the no. of students ";
cin>>n;
cout<<“enter the marks”;
for(i=0; i<n; i++)
{
cin>>a[i];
}
cout<<“the marks are:”;
for(i=0; i<n; i++)
{
cout<<a[i]<<“\n”;
}
getch();
}
10 8 3 2 1
8 10 3 2 1
3 10 8 2 1
2 10 8 3 1
1 10 8 3 2
1 10 8 3 2
1 8 10 3 2
1 3 10 8 2
1 2 10 8 3
1 2 8 10 3
1 2 8 10 3
1 2 3 10 8
1 2 3 10 8
1 2 3 8 10
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, a[100], temp;
cout<<"Enter the limit ";
cin>>n;
cout<<“enter the numbers”;
for(i=0; i<n; i++)
{
cin>>a[i];
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout<<“the sortrd array is”;
for(i=0; i<n; i++)
{
cout<<a[i];
}
getch(); }
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, a[100], small;
cout<<"Enter the limit ";
cin>>n;
cout<<“enter the numbers”;
for(i=0; i<n; i++)
{
cin>>a[i];
}
small=a[0];
for(i=1; i<n; i++)
{
if(a[i]<small)
small = a[i];
}
cout<<“The smallest is”<<small;
getch();
}
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
int length, i, j, str[50], flag=0;
cout<<"Enter the string";
cin>>str;
length = strlen(str);
for(i=0, j=length-1; i<=length/2; i++,j- -)
{
if(str[i] != str[j])
{
flag=1;
break;
}
}
if(flag= = 1)
cout<<“not palindrome”;
else
cout<<“palindrome”;
getch();
}
A two dimensional array is an array in
which each element is itself is a single
dimensional array.
An array A[m][n] is an mxn table with m
rows and n columns.
The general form is:
type array_name[rows][columns];
E.g.:-
int a[3][4];
0 1 2 3
0
a[1][2]
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>a[i][j];
}
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int m, n, i, j, a[10][10], b[10][10], c[10][10];
cout<<"Enter the no. of rows and columns";
cin>>m>>n;
cout<<“enter the first matrix”;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>a[i][j];
}
}
cout<<“enter the second matrix”;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>b[i][j];
}
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
cout<<“resultant matrix is:”;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cout<<c[i][j];
}
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int m, n, i, j, a[10][10], b[10][10];
cout<<"Enter the no. of rows and columns";
cin>>m>>n;
cout<<“enter the matrix”;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>a[i][j];
}
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
b[i][j] = a[j][i];
}
}
cout<<“the transpose matrix is:”;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cout<<b[i][j];
}
}
getch();
}
A large program is broken down into
smaller units called functions.
A function is a named unit of program
statements.
This unit can be invoked from other parts
of the program.
A function is a subprogram that acts on
data and often returns a value.
1) built-in-functions
- part of the compiler package.
- part of standard library.
- e.g.:- exit(), sqrt(), pow(), strlen(), etc.
2) user-defined functions
- are created by the user as per the
requirements of the program
A function has 3 parts :
1. function declaration/prototype
2. function definition
3. function call
It is the declaration of the function that tells the
program about the type of the value returned by
the function an the number and type of its
arguments.
General form is:
return_type function_name(arguments);
E.g.:-
int add(int a, int b);
A function can be defined anywhere in the
program.
General form is:
return_type function_name(arguments)
{
function body
}
E.g.:-
int add(int a, int b)
{
int sum;
sum = a + b;
return sum;
}
A function is called or invoked by providing
the function name, followed by the
parameters being sent enclosed in
parantheses.
E.g.:- to invoke the function int add(inta, int b) we
give the following function call
add(x,y);
#include<iostream.h> int cube(int x)
#include<conio.h> {
int cube(int x);
int s;
void main()
{ s = x * x * x;
clrscr(); return s;
int n, c; }
cout<<"Enter the number";
cin>>n;
c = cube(n);
cout<<“cube =“<<c;
getch();
}
#include<iostream.h> int diff = sub(a,b);
#include<conio.h>
int add(int x, int y); int pdt = mul(a,b);
int sub(int x, int y);
int mul(int x, int y); float qout = div(a,b);
float div(int x, int y);
void main() cout<<“sum=“<<sum;
{ cout<<“diff=“<<diff;
clrscr(); cout<<“pdt=“<<pdt;
int a, b; cout<<“quot=“<<quot;
cout<<"Enter 2 numbers";
cin>>a>>b; getch();
}
int sum = add(a,b);
float div(int x, int y)
int add(int x, int y) {
{ return x/y;
return x+y; }
}
int sub(int x, int y)
{
return x-y;
}
int mul(int x, int y)
{
return x*y;
}
A function can be called without
specifying all its arguments.
In
such cases, the function assigns a
default value to the parameter which
does not have a matching argument in
function call.
Defaultvalues are specified during
function declaration.
E.g. :-
float amount(float principal, int period, float
rate=0.15);
Suppose the function call is
value = amount(5000,7);
Here one argument is missing and hence the
default value is used for the argument rate.
value = amount(5000,5,0.12);
passes an explicit value of 0.12 to rate.
An argument can be assigned a
default value only if all the arguments
on its right have default values.
int add(int i, int j=5, int k=10); legal
int add(int i=5, int j, int k=10);
illegal
int add(int i, int j, int k=10); legal
int add(int i=10, int j, int k);
illegal
#include<iostream.h> area = area(x,y);
#include<conio.h> cout<<“area =“<<area;
int area(int l, int b=20); getch();
void main() }
{
clrscr(); int area(int l, int b=20)
int x,y, area; {
cout<<“enter the dimensions”; return l*b;
cin>>x>>y; }
area= area(x);
cout<<“area =“<<area;
The use of the same function name to
create functions that perform a variety
of different tasks - Function
overloading.
We can define a family of functions
with one function name but with
different argument lists.
The correct function to be invoked is
determined by checking the number
and type of the arguments and not on
function type.
E.g. :- overloaded add() function
int add(int a, int b); //prototype 1
int add(int a, int b, int c); //prototype 2
double add(double x, double y); //prototype 3
double add(int p, double q); //prototype 4
double add(double p, int q); //prototype 5
// function calls
cout<<add(5,10); // uses prototype 1
cout<<add(15,10.0); // uses prototype
4
cout<<add(12.5,7.5); // uses prototype
3
cout<<add(5,10,15); // uses prototype
A function call matches the prototype
having the same number and type of
arguments and then calls the
appropriate function for execution.
The function selection involves the
following steps.
1. The compiler first tries to find an
exact match.
2. If an exact match is not found, the
compiler uses integral promotions to the
actual arguments.
char to int
float to double
3. When either of them fails, the compiler
tries to use the built-in-conversions to
actual arguments
If the conversion is possible to have a
multiple match then the compiler will
generate an error message.
Suppose we use the following two
functions:
long square(long n);
double square(double x);
A function call such as
square(10)
will cause an error because int
argument can be converted to either
long or double thereby creating
ambiguous situations
Suppose we use the following two
functions:
long square(long n);
double square(double x);
A function call such as
square(10)
will cause an error because int
argument can be converted to either
long or double thereby creating
ambiguous situations
Suppose we use the following two
functions:
long square(long n);
double square(double x);
A function call such as
square(10)
will cause an error because int
argument can be converted to either
long or double thereby creating
ambiguous situations
An inline function is a function that can
be expanded in line when it is invoked.
The compiler replaces the function call
with the function code.
Inline functions are defined as follows.
inline function-header
{
function body
}
E.g.:-
inline double cube(double a)
{
return(a*a*a);
}
The above function can be invoked by
statements like
c = cube(3.0);
d = cube(2.5+1.5);
Allinline functions must be defined
before they are called.
The speed benefits of inline functions
diminish as the function grows in size.
Usually, the functions are made inline
when they are small enough to be
defined in one or two lines.
E.g.
inline double cube( double a) { return
(a*a*a);}
The inline keyword merely sends a
request, not a command, to the
compiler.
The compiler may ignore the request if
the function definition is too long or
too complicated.
#include<iostream.h> inline int cube(int x)
#include<conio.h> {
inline int cube(int x);
return x*x*x;
void main()
{ }
clrscr();
int n, c;
cout<<"Enter the number";
cin>>n;
c = cube(n);
cout<<“cube =“<<c;
getch();
}
Situations where inline functions does
not work
For functions returning values , if a
loop, a switch, or a goto exists.
For functions not returning values, if a
return statement exists.
If functions contain static variables.
If inline functions are recursive.
A function that calls itself is called a
recursive function.
While defining a recursive function we
must specify a condition that
terminates the recursive calls.
int factorial(int n)
{
int fact;
if(n==0)
return 1;
else
return(n* factorial(n-1));
}
#include<iostream.h> int factorial(int n)
#include<conio.h> {
int factorial(int x); int fact;
void main()
{ if(n==0)
clrscr(); return 1;
int n, f; else
cout<<"Enter the number"; return (n* factorial(n-1));
cin>>n; }
f = factorial(n);
cout<<“factorial =“<<f;
getch();
}
A pointer is a variable that holds a memory
address.
This address is usually the location of
another variable in memory.
The general form of declaring a pointer is
type *ptr;
E.g.:-
char *a;
declares a pointer to a character.
int a = 5;
int *p = &a;
p is a pointer to the variable a
variable content Memory
address
p 5006 2005
a 5 5006
There are 2 unary pointer operators.
& -ampersand
* - asterisk
& is called address operator. It will return
the address of the variable.
* is called the pointer de-reference
operator. It can be spelled as “VALUE AT
THE ADDRESS IN”.
E.g.:- *p value at the address in p
*p 5
&p 2005
&a 5006
variable content Memory
address
p 5006 2005
a 5 5006
The arithmetic operations on pointers are
1) increment/decrement
2) add/subtract with an unsigned integer
number
When a pointer is incremented, the pointer
points to the next element’s address.
int x = 10;
int *p = &x;
10 40 50 60 2 100
2000 2002 2004 2006 2008 2010
p++
The name of the array is actually the
starting address of the array. So
*(array_name +n) array_name[n];
x 1 5 7 8 10
0 1 2 3 4
*(x+1) 5
*(x+3) 8
We can access the array using pointers as
follows:
int x[5] = {1, 5, 7, 8, 10}
int *p = x;
5000 5002 5004 5006 5008
x 1 5 7 8 10
0 1 2 3 4
p
*(p+1) *(5002)5
*(p+3) *(5006)8
#include<iostream.h>
#include<conio.h> cout<<“length =“<<length;
void main()
{ getch();
char a[20], *p; }
int length=0;
cout<<“enter the string”;
cin>>a;
p = a;
while(*p != ‘\0’)
{
length++;
p++;
}
The are 2 methods to invoke a function.
1) call by value
2) call by reference
Actual arguments
The arguments in the function call are
called actual arguments.
add(a, b);
actual arguments
Formal arguments
The arguments in the function definition are
called formal arguments.
int add(int x, int y)
{
…….
…….
}
formal arguments
In call by value method a copy of the actual
arguments are sent to the called function.
The function works on this copy of values
so that any change in the formal arguments
will not reflect the actual arguments.
In call by value method a copy of the actual
arguments are sent to the called function.
The function works on this copy of values
so that any change in the formal arguments
will not reflect the actual arguments.
#include<iostream.h> getch();
#include<conio.h> }
void swap(int a, int b);
void main() void swap(int a, int b)
{ {
int a=10, b=15; int temp;
cout<<“values before swap”; temp = a;
cout<<“a=“<<a<<“b=“<<b; a=b;
b=temp;
swap(a,b)
cout<<“swapped values ”;
cout<<“values after swap”; cout<<“a=“<<a<<“b=“<<b;
cout<<“a=“<<a<<“b=“<<b;
}
Output
Values before swap a=10 b=15
Swapped values a=15 b=10
Values after swap a=10 b=15
In call by reference method the address of
the actual arguments are sent to the called
function.
The function works on the original values
so that any change in the formal arguments
will reflect the actual arguments.
#include<iostream.h> getch();
#include<conio.h> }
void swap(int *a, int *b);
void main() void swap(int *a, int *b)
{
{ int temp;
int a=10, b=15;
temp = *a;
cout<<“values before swap”; *a=*b;
cout<<“a=“<<a<<“b=“<<b; *b=temp;
swap(&a,&b) cout<<“swapped values ”;
cout<<“a=“<<*a;
cout<<“values after swap”; cout<<“b=“<<*b;
cout<<“a=“<<a<<“b=“<<b; }
Output
Values before swap a=10 b=15
Swapped values a=15 b=10
Values after swap a=15 b=10
Date of submission
26-03-13
Write a program to find the roots of a quadratic equation.
Write a program to find the factorial using for loop.
Write a program to reverse a string.
Write a program to find the roots of a quadratic equation.
Write a program to sort an array of numbers using
functions. Pass the array and number of elements as
arguments to the function.
Write a program to find the largest of an array of numbers
using function.
Write a program to generate the nth Fibonacci number
using recursion