Vous êtes sur la page 1sur 291

A look at Procedure Oriented

Programming
 Conventional Programming using high level languages
such as cobol,fortran and C is commonly known as
procedure oriented programming (POP).
 Procedure oriented programming basically consists of
writing list of instructions for the computer to follow,and
organizing these groups into functions.

 Very little attention is paid to the data that is used by


various functions.

 Employs top-down approach in program design.

 It does not model real world problems very well.

 In multi function programs many important data items are


placed as global so that they can be accessed by all the
functions.Global data are more vulnerable to changes by a
function.
Object oriented programming
 Emphasis is on data rather than the procedures
 Programs are divided into what are known as objects.
 Data is hidden and cannot be accessed by external
functions.
 Objects can communicate with each other using
functions
 New data and functions can be added whenever
necessary
 Follows bottom up approach
 C++ is a general purpose programming language.
It has imperative, object-oriented and generic
programming features.

 Bjarne Stroustrup, a Danish and British trained


computer scientist, began his work on C++'s
predecessor "C with Classes" in 1979.

 Since the class was a major addition to the original


C language Stroustrup initially called the new
language ‘C with classes’.However later in 1983 the
name was changed to C++.
A simple C++ Program
 # include <iostream> // include header file
 using namespace std;

 int main()
{
 cout<<“Hello World.\n”;
 Return 0;
}
 Every C++ program must have a main().
 Like C,the C++ statements must terminate with semi-
colons;
Comments
 The double slash comment is basically a single line
comment.Multi-line comments can be written as
follows.

 //This is an example of
 //C++ programs to illustrate

 /*
 */
Output Statement
 The only statement in the above example is an output
statement.

 The statement cout<<“hello“ causes the string to be


displayed on the screen.

 The operator << is called the insertion or put to


operator.

 It inserts or sends the contents of the variable on its


right to the objects on its left.
The iostream file
 # include <iostream>

 This directive causes the pre-processor to add the


contents of the iostream file to the program.

 It contains declarations for the identifier cout and the


operator <<.
Return type of main()
 In C++, main returns an integer type value to the
operating system.Therefore every main() in C++
should end with a return(0). Statement otherwise a
warning or error may occur.

 Since main() returns an integer type value,return type


for main() is explicitly specified as int.
Input Operator
 The statement

 Cin >> number1;


 Is an input statemnt and causes the program to wait
for the user to type in a number.

 The number keyed in placed in variable1.

 The operator >> is known as extraction or get from


operator.
C++ character set
 A character denotes any alphabet,digit or symbol to
represent information.

 Following are valid albhabets,numbers and special


symbols permitted in C++.

 Numerals:0,1,2,3,4,5,6,7,8,9.
 Albhabets:a,b,…..z
 A,B,……….Z
 Arithmetic Operators:=,-,*,/,%(mod)
 Special characters

( ) { } [ ] < >

= ! $ ? . , : ;

‘ “ & | ^ ~ ` #

\ Blank - _ / * % @
Identifier
 An identifier is an unlimited sequence of characters
consisting of letters,digits or underscore.The first
character is either underscore or letter.An identifier
cannot be a reserved keyword.

 Example record,salary,average are identifiers


Keywords
 Keywords are words whose meaning has already been
defined to the C++ compiler.The keywords are also
known as reserved words.

 The keywords cannot be used as variables in the


program because by doing so we would be assigning a
new meaning to the keyword which is not allowed by
the compiler.
Escape Sequence
 The following escape sequence can be used
\b Backspace

\t Horizontal tab

\n Newline

\v Vertical tab

\a Audible bell

\f Formfeed

\r Carriage return

\0 Null character
Data types
 Data types defines a set of values and a set of
operations that can be applied on those values which
are governed by :

 1)same set of rules


 2)operated by same set of operations
 3)occupy some number of bytes in memory.
Name Size Range
Char 1 byte -128 to 127
Int 2 bytes -32768 to 32767
Float 4 bytes +/-1.4023 * 10-45 to
3.4028*1038

Double 8 bytes +/- 4.9406 * 10-324 to


1.7977 * 10 305

Void is also a datatype and the use of void is to specify the


return type of function when it is not returning any value.

2)To indicate an empty argument list to a function.

Void function1(void);
Qualifiers
Type Bytes Range
Short 2 -32768 to 32767
Unsigned short 2 0 -65,536
int
Unsigned int 2 0-
>+4,294,967,295
Long int 4 -2,147,483,648 -
>+2,147,483,647
Signed char 1 -128->+127
Unsigned char 1 0->+255
Long double 10 3.410-4932 to 3.4
*10 4932
Constants in C++
 A constant is a value of any type which remains the
same and can never change,during the program
execution.

 The simplest use of const is to declare a named


constant by adding const before variable name.

 const int constant1=30;


Declaring Variables in C++

 A variable is a named location in memory that is used


to hold a value that can be modified by the program.
Dynamic Initialization of Variables
 In C a variable must be initilized using a constant
expression and the C compiler would fix the
initialisation code at the time of compilation.

 C++ permits the initialization of variables at run time


.This is referred to as dynamic initialization.

 Float area=3.14159*rad*rad;
 Declaration and initialization can be done
simeltenously.
 Float average;
 Average = sum/I;

 The two statements can be combined into a single


statement

 Float average=sum/I;
Reference Variable
 C++ introduces a new kind of variable called as the
reference variable.

 A reference variable provides an alias (Alternative


name) for a previously defined variable.

 Example we make the variable sum a reference to the


variable total,then sum and total can be used
interchangeably to represent that variable.
 A reference variable is created as follows.

 DATA TYPE & REFERENCE-NAME=VARIABLE NAME

 Example

 Float total=100;
 Float &sum=total;
 Total is float type variable that has already been
declared.;Sum is the alternative name declared to
represent the variable total.Both the variables refer to
the same data object in the memory.

 Now the statement

 Cout<<total;

 And
 Cout<<Sum;
 Both print the value 100;
 The statement

 Total=total+10;

 Will change the value of both total and sum to 110.

 A reference variable must be initialized at the time of


declaration.
 This establishes the correspondence between the
reference and the data object which it names.
Arithmetic Operators
 C++ provides two types of arithmetic operators

 1)Binary arithmetic operators


 2)Unary Arithmetic operators.
Binary arithmetic operators
 Binary arithmetic operators need two types of
arithmetic operators to operate upon.

Operator Meaning C++ Result


expression
+ Addition 2+6 8
- Subtraction 7-5 2
* Multiplicatio 4*2 8
n
/ Division 6/3 2

% Modulus(Re 9%8 1
mainder)
Unary operator
 Unary operators need only one operand .The two
unary operators are ++,--.

 Both the increment(++) and decrement(--)operators


can either precede (prefix) or follow(postfix) the
operand.
 For example
 x=x+1
 can be written as
 ++x; // prefix form
 x++ //postfix form

 similarly

 x=x-1 can be written as


 --x //prefix
 x-- //postfix
 Evaluate x=++y+y if y =8
 Given int y=19 and int z;
 What values will y and z have after z=y--;
 Given x=7 and y;what value will x and y have after
y=++x?
Example
 Int value1=20,value2=20;sum1=0;sum2=0;
 Sum1=sum1+ ++value1; //change then use
 Sum2=sum2+ value2++ //use then change
 Cout<<sum1<<value1<<endl;
 Cout<<sum2<<value2<<endl;
Example 2
 int x,m,n;
 m=10;
 n=15;
 x=++m +n++;
Example 3
 #include<iostream.h>
 using namespace std;
 void main()
{
int a=5;b=10;
for(int x=1;x<=2;x++)
{
cout<<++a<<”, ”<<a++<<endl;
cout<<b--<<“,”<<--b<<endl;
}
}
Relational Operators
 Relational operators are symbols that are used to
compare & test the relationship between two
variables,or between a variable and a constant.

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
 One mistake done by programmers is in using =
assignment operator in place of relational operator ==.

 Marks==70 == for comparing,whether marks is 70 or


not.
 Marks=70 = for assigning value 70 to variable
marks.
Logical operators
 Logical operators enable you to combine logical
expressions and establish relationships between
expressions.

Operator Meaning
! Not
&& And
|| Or
Conditional operator
 Consider
 Exp1 ? Exp2 : Exp3; where Exp1, Exp2, and Exp3 are
expressions. Notice the use and placement of the colon.

 The value of a ? expression is determined like this: Exp1 is


evaluated. If it is true, then Exp2 is evaluated and becomes
the value of the entire ? expression.

 If Exp1 is false, then Exp3 is evaluated and its value


becomes the value of the expression.
 The ? is called a ternary operator because it requires
three operands and can be used to replace if-else
statements.

 (x>7)?cout<<“greater than 7”:cout<<“less than 7”;


Sizeof() operator
 The sizeof is a keyword, but it is a compile-time
operator that determines the size, in bytes, of a
variable or data type.
 The sizeof operator can be used to get the size of
classes, structures, unions and any other user defined
data type.
 The syntax of using sizeof is as follows:
 sizeof (data type)
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : "size of char : <<
<< sizeof(char) 1 endl;
Size
cout << "Size of int : " << of int <<
sizeof(int) : 4endl;
cout << "Size of short intSize ofsizeof(short
: " << short int int): 2 << endl;
cout << "Size of long int :Size of long int
" << sizeof(long int): <<
4 endl;
Size
cout << "Size of float : " << of float <<
sizeof(float) : 4endl;
return 0;
}
#include <iostream>
using namespace std;
int main() Size of variable i : 4
{ Size of variable c : 1
int i;
char c;
cout << "Size of variable i : " << sizeof(i) << endl;
cout << "Size of variable c : " << sizeof(c) << endl;
return 0;
}
typecast
 Explicit process of conversion of data of one type to
another.

 int a;float b;
 b=(float)a;
Assignment operators

Term Expression Equivalent
+= y+=x y=y+x;

-= X-=5 X=x-5;
/= x/=y X=x/y;

*= X*=y X=x*y;
%= X%=y X=x%y;
Scope resolution operator
 Variables declared inside a block are local variables
and scope of the local variable is block scope.These
variables only exist inside the specific function that
create them.They are unknown to other functions and
to the main program.

 Global variables are defined outside the main function


block.These variables are referred by same name and
same data type throught the program at the time of
calling as well as in the function block.
 #include<iostream.h>
 int num;
 char ch; //global
 float num1; //global
 double numd;
 void main()
{
 int num_m; //local
 float num_x; //local
}
Role of scope resolution operator
 If a variable is declared as local as well as global by the
same name then the value of local variable is accessed
by default.

 If you want to access the value of global variable then


an operator known as scope resolution operator is used
.symbol ::
 int a=10;
 void main()
{
 int a=5;
 cout<<a<<::a;
}
Control Statements
 if(boolean_expression)
 {
 // statement(s) will execute if the boolean expression
is true
 }
 Else
 {
 // statement(s) will execute if the boolean expression
is false
 }
#include <iostream>
using namespace std;
int main ()
{
int a = 100;
if( a < 20 )
{
cout << "a is less than 20;" << endl;
}
else
{
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
While loop
 A while loop statement repeatedly executes a target
statement as long as a given condition is true.

 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


non-zero value.

 The loop iterates while the condition is true.


 #include <iostream>
 using namespace std;
 int main ()
 {
 int a = 10;
 while( a < 20 )
 {
 cout << "value of a: " << a << endl;
 a++;
 }
 return 0;
 }
Do while
 Unlike for and while loops, which test the loop
condition at the top of the loop, the do...while loop
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.
 do
{
 statement(s);
}
 while( condition );
 #include <iostream>
 using namespace std;
 int main ()
 {
 int a = 10;
 do
 {
 cout << "value of a: " << a << endl;
 a = a + 1;
 }
 while( a < 20 );
 return 0; }
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.

 for ( init; condition; increment )


{
 statement(s);
 }
 #include <iostream>
 using namespace std;
 int main ()
 {
 for( int a = 10; a < 20; a = a + 1 )
{
 cout << "value of a: " << a << endl;
}
 return 0;
}
 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 case.
 switch (2)
{
 case 1: // Does not match -- skipped
 cout << 1 << endl;
 case 2: // Match! Execution begins at the next statement
 cout << 2 << endl; // Execution begins here
 case 3:
 cout << 3 << endl; // This is also executed
 case 4:
 cout << 4 << endl; // This is also executed
 default:
 cout << 5 << endl; // This is also executed
}
 The expression used in a switch statement must have
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.
 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.
 #include <iostream>
 using namespace std;
 int main ()
 {
 char grade = 'D';
 switch(grade)
 {
 case 'A' :
 cout << "Excellent!" << endl;
 break;
 case 'B' :
 case 'C' :
 cout << "Well done" << endl;
 break;
 case 'D' : cout << "You passed" << endl;
 break;
 case 'F' : cout << "Better try again" << endl;
 break;
 default : cout << "Invalid grade" << endl;
 }
 cout << "Your grade is " << grade << endl; return 0; }
Continue
 The continue statement provides a convenient way to
jump back to the top of a loop earlier than normal,
which can be used to bypass the remainder of the loop
for an iteration. Here’s an example of using continue:
 #include <iostream>
 using namespace std;
 int main ()
 {
 for (int n=10; n>0; n--)
 {
 if (n==5)
 continue;
 cout << n << ", ";
 }
 cout << "liftoff!\n";
 }
Comma Operator
 The purpose of comma operator is to string together
several expressions.

 var = (count=19, incr=10, count+1);

 Here first assigns count the value 19, assigns incr the
value 10, then adds 1 to count, and finally, assigns var
the value of the rightmost expression, count+1, which
is 20.
 #include <iostream>
 using namespace std;
 int main()
{
 int i, j;
 j = 10;
 i = (j++, j+100, 999+j);
 cout << i;
 return 0;
}
Editor in C++
 An Editor is an program much like a Word Processor
that you use to edit the Source Code of any program
you write.

 Most IDEs come with a built in editor and some will


automatically highlight compile errors in the editor to
simplify fixing them.
 When you write a c++ program, the next step is to
compile the program before running it.

 The compilation is the process which convert the


program written in human readable language like C,
C++ etc into a machine code, directly understood by
the Central Processing Unit.
 Preprocessing

 In this phase the preprocessor changes the program
according to the directives mentioned (that starts with
# sign). The C++ preprocessor takes the program and
deals with the # include directives and the resulting
program is pure c++ program
Compilation
 This phase translates the program into a low level
assembly level code. The compiler takes the
preprocessed file ( without any directives) and
generates an object file containing assembly level
code. Now, the object file created is in the binary form.
Linking
 Linking as the name suggests, refers to creation of a
single executable file from multiple object files. The
file created after linking is ready to be loaded into
memory and executed by the system .
Debugging
 Debugging is the process of isolating and correcting
the errors.

 One simple way of debugging is to place print


statements throught the programs to display the
values of the variables.

 Another approach is the process of deduction. The


location of the error is arrived at using the process of
elimination and refinement.This is done using a list of
possible causes of the error.
 The third error detecting method is to backtrack the
incorrect results through the logic of the program until
the mistake is located.
Commands
 For Microsoft compilers, the command to invoke the
compiler is cl :

c:\directory location> cl -GX factorial.cpp


Manipulators
 Manipulators are operators that are used to format the
data display.The most commonly used manipulators
are endl and setw.

 The endl manipulator,when used in an output


statement causes a linefeed to be inserted.It has the
same effect as using the newline chararcter.
 Ex

 Cout<<“m=“<<m<<endl;
 Cout<<“n=“<<n<<endl;
 Cout<<“p=“<<p<<endl;

 This will cause three lines of output,one for each


variable
 Setw manipulator
 The setw manipulator allows the user to specify a
common field width for all numbers and force them to
be printed right-justified.

 Cout<<setw(5)<<sum<<endl;

 The manipulator setw(5) specifies a field width 5 for


printing the value of the variable sum.The value is
right justified.
 Header file <iomanip.h>

 It is used to define several manipulators that each take


a single argument.
FUNCTIONS
 Dividing a program into functions is one of the major
principles of top-down,structures programming.

 It is possible to reduce the size of a program by calling


and using them at different places in the program.
SYNTAX
 void show(); // function declaration
 main()
{

 show() //function call

 }
 void show() // function definition
 {
 ……… //function body
 }
 When function is called control is transferred to the
first statement in the function body.

 The other statements in the function body are then


executed and control returns to the main program
when the closing brace is encountered.
Call by value
 The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function.

 The actual values of the variable remains unchanged as


changes are made to the copied values of the variables.

 By default, C++ uses call by value to pass arguments


#include<iostream.h>
#include<conio.h>
void swap(int x, int y);
int main()
{
int a,b;
cout<<"enter two numbers"<<endl;
cin>>a;
cin>>b;
cout<<"value of numbers before swapping \t:"<<"a="<<a<<" "<<"b="<<b;
swap(a,b);
cout<<"in main after swapping \n "<<"a="<<a<<" "<<"b="<<b<<endl;
}
void swap(int x, int y)
{

int temp;
temp=x;
x=y;
y=temp;
cout<<"\n in swap "<<"x="<<x<<" "<<"y="<<y<<endl;
}
 Call by Reference

 Call by reference is the method by which the address


of the variables are passed to the function. The "&"
symbol is used to refer the address of the variables to
the function.

 It is a method of passing arguments to a function and


copies the reference of an argument into the formal
parameter.
#include<iostream.h>
void swap(int &x,int &y);
int main()
{
int a,b;
cout<<"Enter two numbers"<<endl;
cin>>a;
cin>>b;
cout<<"value of numbers before swapping \t"<<"a ="<<a<<" "<<"b="<<b;
swap(a,b);
cout<<"In main after swapping \n"<<"a= "<<a<<" "<<"b ="<<b<<endl;
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
cout<<"\n in swap "<<"x="<<x<<" "<<"y="<<y<<endl;
}
Example
#include<iostream.h>
using namespace std;
int global=10;
void func(int &x,int y)
{
x=x-y;
y=x*10;
cout<<x<<" ,"<<y<<endl;
}
int main()
{
int global=7;
func(::global,global);
cout<<global<<" ,"<<::global<<endl;
func(global,::global);
cout<<global<<", "<<::global<<endl;
}
#include<iostream.h>
using namespace std;
int global=8;
void func(int &x,int y)
{
x=x-y;
y=x*10;
cout<<x<<" ,"<<y<<endl;
}
int main()
{
int global=6;
func(::global,global);
cout<<global<<" ,"<<::global<<endl;
func(global,::global);
cout<<global<<", "<<::global<<endl;
}
#include<iostream.h>
using namespace std; 2011 oct
int max(int &x,int &y,int &z) board
{
if(x>y && y>z)
{
y++;
z++;
return x;
}
else
if(y>x)
return y;
else
return z;
}
int main()
{
int a=10,b=13,c=8;
a=max(a,b,c);
cout<<a<<" "<<b<<" "<<c<<endl;
b=max(a,b,c);
cout<<++a<<" "<<++b<<" "<<++c<<endl;
c=max(a,b,c);
cout<<a++<<" "<<++b<<" "<<c<<endl;
cout<<a<<" "<<b<<" "<<c<<endl;
Call by reference using pointers
 The both cases do exactly the same.

 However, the small difference is, that references are


never null (and inside function you are sure, that they
are referencing valid variable). On the other hand,
pointers may be empty or may point to invalid place in
memory.
#include<iostream.h>
using namespace std;
int a=3;
void demo(int &x,int y ,int *z)
{
a+=x;
y*=a;
*z=a+y;
}
int main()
{
int a=2,b=5;
demo(::a,a,&b);
cout<<::a<<" "<<a<<" "<<b<<endl;
demo(a,::a,&b);
cout<<::a<<" "<<a<<" "<<b;

}
#include<iostream.h>
2011 board
using namespace std;
question
int a=30;
void trial(int &x,int y,int *z)
{
a/=x;
y+=a;
*z=a+y;
x+=5;
cout<<a<<" "<<x<<" "<<y<<" "<<*z<<endl;
}
int main()
{
int a=5,b=10;
trial(::a,a,&b);
cout<<::a<<" "<<a<<" "<<b<<endl;
trial(b,::a,&a);
cout<<::a<<" "<<a<<" "<<b<<endl;
}
#include<iostream.h>
Prelims 2016
int g=20;
void func(int &x,int y)
{
x=x-y;
y=x*10;
cout<<x<<“,”<<y<<endl;
-13,-130
}
void main()
-13,20
{ 33,330
int g=7;
func(g,::g); -13,33
cout<<g<<“,”<<::g<<endl;
func(::g,g);
cout<<g<<“,”<<::g<<endl;
}
#include<iostream.h> Board 2016
int a=3;
void demo(int x,int y,int &z)
{
a+=x+y;
z=a+y;
y+=x;
cout<<x<<y<<z<<endl;
3 5 10
}
void main() 8 2 10
{
int a=2,b=5;
demo(::a,a,b);
8 10 20
cout<<::a<<a<<b<<endl;
demo(::a,a,b); 18 2 20
cout<<::a<<a<<b<<endl;
}
#include<iostream.h> 2014 board
using namespace std;
int x=10;
void pass(int &a,int b,int &c)
{
int x=4;
c+=x;
a*=::x;
b+=c;
cout<<a<<" "<<b<<" "<<c<<endl;
}
int main()
{
int y=1,x=2;
pass(y,::x,x);
cout<<x<<" "<<y<<" "<<::x<<endl;
pass(::x,x,y);
cout<<x<<" "<<y<<" "<<" "<<::x<<endl;
}
Board 2017
 #include<iostream.h>
 int global=10;
 void func(int &x,int y)
 {
 x=x-y;
 y=x*10;
 cout<<x<<","<<y<<"\n";
 }
 int main()
 {
 int global=7;
 func(::global,global);
 cout<<global<<","<<::global<,endl;
 func(global,::global);
 cout<<global<<","<<::global<<endl;
 }
#include<iostream.h>
using namespace std;
int main()
{
void execute(int &b,int c=100);
int m=90,n=10;
execute(m);
cout<<m<<" "<<n<<"\n";
execute(m,n);
cout<<m<<" "<<n<<"\n";
}
void execute(int &b,int c)
{
int t=b+c;
b=b+t;
if (c==100)
cout<<t<<" "<<b<<" "<<c<<"\n";
}
#include<iostream.h>
using namespace std;
void withdef(int hisnum=30)
{
for (int i=20;i<=hisnum;i+=5)
cout<<i<<",";
cout<<endl;
}
void control(int&mynum)
{
mynum=mynum+10;
withdef();
}
int main()
{

int yournum=20;
control(yournum);
withdef();
cout<<"number="<<yournum<<endl;
}
Return by reference
 Int & max(int &x,int &y)
{
 If (x>y)
 Return x;
 Else
 Return y;
}
Return by reference
 A function call can also return a reference. Since the
return type of max is int&,the function returns
refernce to x or y and not the values.

 A function call such as max(a,b)will yield a reference


to either a or b depending on their values.
 #include<iostream>
 using namespace std;

 int fun(int x = 0, int y = 0, int z)
 { return (x + y + z); }

 int main()
{ Compiler Error
 cout << fun(10);
 return 0;
}
#include <iostream>
using namespace std;
int add(int a, int b);
int main()
{
int i = 5, j = 6;
cout << add(i, j) << endl;
}
int add(int a, int b )
{
int sum = a + b;
a = 7;
return a + b;
} 13
Inline Functions
 Every time a function is called, it takes a lot of extra
time in executing a series of instructions for tasks such
as jumping to the function, saving registers, pushing
arguments into the stack, and returning to the calling
function.

 When function is small a substantial percentage of


execution time is spent in such overheads.
 To eliminate the cost of calls to small functions C++
proposes a new feature called inline function.

 An inline function is a function that is expanded in


line when its invoked.

 The compiler replaces the function call with the


corresponding function code.

 Inline function-header
 {
 Function -body
 }
 We should exercise care before making a function
inline.

 The speed benefits of inline functions diminish as the


function grows in size. At some point the overhead of
the function call becomes small compared to the
execution of the function.

 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
and compile the function as a normal function.
 Some of the situations where inline functions may not
work are

 1)for functions returning values if a loop,a switch or a


goto exists.

 2)for functions not returning values if a return


statement exists.

 3)if functions contain static variables.

 4)If inline functions are recurcive.


 #include <iostream>
 using namespace std;
 inline int Max(int x, int y)
 {
 return (x > y)? x : y;
 }
 // Main function for the program
 int main( )
 {
 cout << "Max (20,10): " << Max(20,10) << endl;
 cout << "Max (0,200): " << Max(0,200) << endl;
 cout << "Max (100,1010): " << Max(100,1010) << endl;
 return 0;
 }
Functions with default parameters
 C++ allows us to call functions without specifying all
its parameters.

 In such cases the function assigns a default value to the


parameter which does not have a matching argument
in the function call.

 Default values are specified when the function is


declared.
 The compiler looks at the prototype to see how many
arguments a function uses and alerts the program for
possible default values.

 Float amount(float principal,int period,float rate=0.15)

 A function call like

 Amount(5000,7)

 Passes value 5000 to principal,7 to period and lets the


function use 0.15 for rate.
 Value =amount(5000,5,0.12)

 Passes an explicit value of 0.12 to rate.

 Important point to note is that only trailing arguments


can have default values and therefore we must add
defaults from right to left.

 We cannot provide a default value to a particular


argument in the middle of an argument list.
Output Example
#include<iostream.h>
using namespace std;
void execute(int &x,int y=150)
{
int temp=x+y;
x+=temp;
if(y!=200)
cout<<temp<<"\t"<<x<<"\t"<<y<<endl;
}
int main()
{
int a=50,b=20;
execute(b);
cout<<a<<"\t"<<b<<endl;
execute(b,a);
cout<<a<<"\t"<<b<<endl;
}
Function overloading
 We can use a same function name to create functions
that perform a variety of tasks.This is known as
function overloading in OOP.

 We can design a family of functions with one function


name but with different argument lists.

 The function would perform different operations


depending on the argument lists in the function call.
The correct function to be invoked is determined by
checking the number and type of the arguments but
not the function type.
 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

 Cout<<add(5,10);
 Cout<<add(15,10.0)
 Cout<<add(12.5,7.5)
 Cout<<add(5,10,15)
 Cout<<add(0.75,5)
#include <iostream>
using namespace std;
void display(int);
void display(float);
void display(int, float);
int main()
{
int a = 5;
float b = 5.5;
display(a);
display(a, b);
display(b);

}
void display(int var)
{
cout << "Integer number: " << var << endl;
}
void display(float var)
{
cout << "Float number: " << var << endl;
}
void display(int var1, float var2)
{
cout << "Integer number: " << var1; cout << " and float number:" << var2;
}
 #include <iostream>
Int volume(int s)
 Using namespace std; {

Return(s*s*s);
 Int volume(int);
}
 Double volume(double,int)
 Long volume(long,int,int);
Double volume(double r,int h)
{
 Int main() Return(3.14519*r*r*h)

 { }
 Cout<<volume(10);
Long volume(long l,int b,int h)
 Cout<<volume(2.5,8); {
Return(l*b*h);
 Cout<<volume(100,75,15);
 } }
 Passing array as parameters

 only the address of the array element is passed. So it is


"passing by reference" so that the actual array element
will get changed. Even though the array is passed as
reference "&" symbol is not used instead the "[]" is
used to in the parameter name.
Passing arrays to functions
#include <iostream>

Using namespace std;


int answer(int a[],int num);
Int main()
{
int numbers[5]={1,2,3,4,5};
int total=answer(numbers,5);
cout<< “the sum of all elements in the
array“<<total<<endl;
return (0);
}
Int answer(int a[],int num)
{
Int sum=0;
For(int i=0;i<=5;i++)
{
Sum +=a[i]
}
Return sum;

}
Output Based example
# include <iostream.h>
using namespace std;
void ChangeArray (int Number, int ARR[], int Size)
{
for (int L=0; L<Size; L++)
if (L<Number)
ARR[L]+=L;
else
ARR[L]*=L;

}
void Show(int ARR [], int size)
{
for (int L=0; L<size; L++)
(L%2!=0) ? cout<<ARR[L] <<"#" : cout<<ARR[L] <<endl;
}
int main ( )
{
int Array [] = {30,20,40,10,60,50};
ChangeArray (3, Array, 6);
Show (Array,6);
}
Built in functions
 <string.h>

 Strlen()

Returns the length of the string


Char mystring[100]=“test string”
Strlen(mystr) returns 11 characters.
String.h
 Strcmp()
 Compares two strings.The function compares the first
character of each string.If they are equal to each other
it continues with the following pairs until the
characters differ or until a terminaring null character
is encountered.
 Returns 0 indicates both strings are equal.
 A negative return value indicates that str1 is smaller
than str2.
 A positive return value indicates str1 is greater than
str2.
String.h
 strcat()

 Concatenates two strings.

 Strcat(str1,str2);
String.h
Strcpy()
Copies the contents of one string into another
Char str1[20]=“hello”;
Char str2[20]=“world”;
Strcpy(str1,str2);
Cout<<str1;

 Output:world.
<ctype.h>
 Isalnum()

 Int isalnum( c )
 True if c is a letter or digit.

 Ex : if (isalnum(‘a’))
 Cout<<“Yes it is alphanumeric”;
Ctype.h
 Isdigit()

 Int isdigit( c )
 True if c is a digit 0 -9
 If (isdigit(7))
 Cout<<“It is a digit”;
Ctype.h
islower()
int islower( c )
true if c is a lowercase letter
ex if (islower (‘a’))
cout<<it is a lower case letter”;
Ctype.h
isupper()

int isupper( c )
true if c is an uppercase letter.
if(isupper( ‘c’ )
cout<<“it is an upper case letter;
Ctype.h
tolower( )

int tolower( c )
returns lowercase version of c if there is one,otherwise it
returns the character unchanged.

ex. cout<<tolower(‘a’)
output :a
Ctype.h
toupper()

int toupper( c )

returns uppercase version of c if there is one otherwise it


returns the character unchanged.

ex:cout<<toupper(‘a’);
output :a
Ctype.h
isalpha()

int isalpha( c )

true if c is a letter.

if(isalpha (‘a))
cout<<“yes it is a alphabet”;
Ctype.h
isspace()

int isspace( c )
true if c is a whitespace character (space,tab,vertical
tab,formfeed,carriage return or new line)

if (isspace(“\n”))
cout<<“it is newline”;
Ctype.h
isspace()

int isspace( c )
true if c is a whitespace character (space,tab,vertical
tab,formfeed,carriage return or new line)

if (isspace(“\n”))
cout<<“it is newline”;
Math.h
 Abs()

 int abs(int x);

 returns the absolute value of an integer.


Math.h
 sqrt(x)

 double sqrt(double x);

 calculates the positive square root of x.


(x is >=0)
Math.h
 pow()

 pow(x,y)

 double pow(double x,double y);

 calculates x to the power of y.


Math.h
 Cos()

 The C library function double cos(double x) returns


the cosine of a radian angle x.
Math.h
Sin()

The C library function double sin(double x) returns


the sine of a radian angle x.

Following is the declaration for sin() function.

double sin(double x)
Math.h
The C library function double log(double x) returns
the natural logarithm of x.

Following is the declaration for log() function.

double log(double x)
Conio.h
getch()

getch function prompts the user to press a character and


that character is not printed on screen, getch header file
is conio.h.

#include<iostream.h>
#include<conio.h>
int main()
{
cout << "Enter a character";
getch();
}
Conio.h
 clrscr()-This is used for clearing the output screen i.e
console

 suppose you run a program, alter it and run it again


you may find that the previous output is still stuck
there itself, at this time clrscr(); would clean the
previous screen.
Stdio.h
 Gets()- Reads a string of characters

 char x[10];
 gets(x)
Stdio.h
 puts()

 outputs a string

 char x[10]=“hello”;
 puts(x);
Stdio.h
 Getchar()-Reads a character from the input device.

 char x;
 x=getchar();
Stdio.h
 putchar()

 displays a character on screen.

 char x=‘a’;
 putchar(x);
Limitations of structures
 C does not allow the struct data type to be treated like
built in types.
 Example
 struct complex
 {
float x;
float y;
};
Struct complex c1,c2,c3;

This statement c3=c1+c2; is illegal in c


 Another limitation of C structures is that they do not
permit data hiding.Structure members can be directly
accessed by the structure variables by any function
anywhere in the scope.
Basic concepts object oriented
programming
 A class is a way to bind data and its associated
functions together.It allows the data and functions to
be hidden.

 When we define a class we are creating a new abstract


data type that can be treated like any other buit in data
type.
 Class specification has two parts

 1)Class declarations
 2)Class functions declarations
 General form of class declaration is

 Class class_name
{
 Private:
 Variable declarations;
 Function declarations;
 Public:
 Variable declarations;
 Functions declarations;
 };
 The body of the class is enclosed within braces and
terminated by semicolon.

 The functions and variables are collectively called class


members.
Object Oriented Programming
Paradigms
 OOP treats data as a critical element in the program
development and does not allow it to flow freely
around the system.

 It ties data more closely to the functions that operate


on it and protects it from accidental modifications
from outside functions.

 OOP allows decomposition of a problem into a


number of entities called objects and then builds data
and function around these objects.
 Some of the striking features of object oriented
paradigm
 emphasis is on on data rather than procedure.
 Programs are divided into objects.
 Data structures are designed such that they
characterize the objects.
 Functions that operate on the data of the object are
tied together in the data structure.
 Data is hidden and cannot be accessed by external
functions.
 Objects may communicate with each other through
functions.
 New data and functions can be added whenever
necessary
 Follows bottom up approach in program designing.
Objects
 Objects are basic runtime entities in object oriented
system.

 They may represent a person, a place, a bank account, table


of data or any item that a program has to handle. Objects
take up place in memory and have an associated address.

 When a program is executed, the objects interact by


sending messages to one another.

 For e.g. : customer and account are two objects in the


program, then the customer object may send a message to
the account object requesting for bank balance.
 Objects contain data and code to manipulate data.
Objects can interact without having to know the
details of each others data or code.
Classes
 The entire set of data and code of an object can be
made a user-defined data type with the help of a class.

 Objects are variables of type class.

 Once a class has been defined we can create any


number of objects belonging to that class.

 Each object is associated with the data of type class


with which they are created.
 A class is thus a collection of objects of similar type.

 For example mango,apple and orange are members of


class fruit.

 If a fruit has been defined as a class then the statement

 Fruit mango;

 Will create an object mango belonging to class fruit.


Data encapsulation
 The wrapping up of data and functions into a single
unit called class is known as encapsulation.

 Data is not accessible to the outside world,and only


those functions which are wrapped in the class can
access it.

 The insulation of data from direct access by program is


called information hiding or data hiding.
Data Abstraction
 Abstraction refers to the act of representing essential
features without including the background details or
explanations.

 Classes uses the concepts of abstraction and are


defined as a list of abstract attributes such as as
size,weight and cost and functions to operate on these
attributes.

 Attributes are sometimes called data members.


 The functions that operate on the data are sometimes
called member functions.

 Since classes uses the concept of data abstraction they


are known as abstract data types.
inheritance
 Inheritance is the process by which objects of one class
acquire the properties ofobjects of another class.

 In OOP the concept of inheritance provides the idea of


reusability.

 This means we can add additional features to an


existing class without modifying it.

 This is possible by deriving a new class from an


existing class.
 The new class will have combined features of both the
classes.
Polymorphism
 Polymorphism a Greek term means the ability to take
more than one form.

 An operation may exhibit different behaviours in


different instances.

 The behavior depends on the type of data used in the


operation.
 For example consider the operation of addition.

 For two numbers the operation will generate a sum .

 If the operands are strings then the operation will


produce a third string by concatenation.

 This process of making an operator to exhibit different


behaviors in different instances is known as operator
overloading.
 Using single function name to perform different tasks
is known as function overloading .

 Program to illustrate polymorphism/function


overloading
#include<iostream.h>
int volume(int a)
double volume(float r,int h)
int volume(int l,int b,int h)
int main()
{
int a,l,b,h;
float r;
cout<<“enter the side of the cube”;
cin>>a;
cout<<“enter the radius and height of the cylinder”
cin>>r>>h;
cout<<“enter the side of the rectangular cube”;
cin>>l>>b>>h;
cout<<“volume of cube=“<<volume(a);
cout<<“volume of cylinder=“<<volume(r,h);
cout<<“volume of rectangular cube=“<<volume(l,b,h);
} CONTD
int volume(int a)
{
return(a*a*a);
}
double volume(float r,int h)
{
return (3.14*r*r*h);
}
int volume(int l,int b,int h)
{
return(l*b*h);
}
Basic concepts object oriented
programming
 A class is a way to bind data and its associated
functions together.It allows the data and functions to
be hidden.

 When we define a class we are creating a new abstract


data type that can be treated like any other buit in data
type.
 Class specification has two parts

 1)Class declarations
 2)Class functions declarations
 General form of class declaration is

 Class class_name
{
 Private:
 Variable declarations;
 Function declarations;
 Public:
 Variable declarations;
 Functions declarations;
 };
 The body of the class is enclosed within braces and
terminated by semicolon.

 The functions and variables are collectively called class


members.

 The class members that have been declared as private


can be accessed only from within the class.

 Public members can be accessed from outside the class


also.
 By default the members of the class are private.If both
the labels are missing then by default all members are
private.

 Such a class is completely hidden and does not serve


any purpose.

 The variables declared inside the class are known as


data members.

 The functions are known as member functions.


 Only the member functions can have access to the
private data members and private functions.
 Data within the class cannot be initialized at the time
of declaration. This is because declaration of class only
serves as a template and no memory is allocated at the
time of declaration.

 Initialization of data will take place at the time of


object declaration.
Simple class example
 Class item
{
 Int number; //variable declarations
 Float cost; //private by default

 Public:
 Void getdata(int a,float b) //functions declarations
 Void putdata (void); //using prototype

 }; //ends with semicolon


 The function getdata() can be used to assign values to
the member variables number and cost and putdata()
for displaying their values.

 Data cannot be accessed by any function that is


not a member of the class item.
Creating objects
 Once a class has been declared we can create variables
of that type using the class name.

 Item x;

 Creates a variable x of type item.


 We can declare more than one object in one statement

 Item x,y,z;

 Objects can also be created by placing their names


immediately after the closing braces.

 Class item
{

 }x,y,z;
 Accessing class members

 The private data of a class can be accessed only


through the member functions of that class.

 The main cannot contain statements that access


number and cost directly.

 Following is the format for calling a member function

 Object-name.function-name(actual-arguments);
 For example the function call

 x.getdata(100,75.5);

 Assigns the value 100 to number and 75.5 to cost of the


object x by implementing the getdata() function.

 Similarly the statement

 X.putdata();

 Would display the values of the data members.


 The statement like

 Getdata(100,75,5);

 Has no meaning.

 Similarly the statement

 X.number=100; Is also illegal.

 Although x is an object of type item to which number


belongs.(The number declared private )can be
accessed only through member functions and not the
object directly.
 Objects communicate by sending and receiving
messages.

 This is achieved through member functions.

 X.putdata();

 Sends a message to x requesting the objects to display


its contents.
 Variable declared as public can be accessed by the
objects directly.

 Example

 Class xyz
{
 Int x;
 Int y;
 Public:
 Int z;
 };
 Xyz p
 P.x=0;
 P.z=10
 #include<iostream.h> Void main ()
 Class sample {
 { private: Sample obj;
int rollno; Obj.enter();
char name[20]; Obj.show();
int marks; }
public:
void enter()
{
cout<<“\n enter roll no”;
cin>>rollno;
cout<<“Enter name\n”;
cin>>name;
cout<<“enter marks\n”
cin>>marks;
}
void show()
{
cout<<“\n roll number”<<rollno;
cout<<“\n name”<<name;
cout<<“\n marks”<<marks;
}
};
Sending arguments to member
function of class
 It is possible to send values to member functions
through the function calls just the way it is done in
ordinary function calls.

 Write a program to assign values to model


number,part number and the cost of parts of tube
tubelights and then display these values.

 The program should be written with classes andn


objects.

 The values to the objects should be sent through


function calls.
 #include<iostream.h> int main()
 Class tube {
 { tube part1;
private: part1.setpart(333,33,639.66);
int modelno; part1.showpart();
int partno; }
float cost;
public:
void setpart(int mno,int pno,float c)
{
modelno=mno;
partno=pno;
cost=c;
}
void showpart()
{
cout<<“\n model number”<<modelno;
cout<<“\n part number:”<<partno;
cout<<“\n cost Rs”<<cost;
}
};
Returning Values from member
functions
 The member functions of a class are like any other
ordinary functions with respect to receiving or sending
values.

 Write a program that allows the user to enter two


distinct numbers and display the one that is greater.

 Use the feature of classes and objects,and the member


functions should return the value which is higher.
#include<iostream.h>
Class sample Int main()
{ {
private: sample object;
int a,b;
object.input();
cout<<“The higher number is”<<object.check();
Public:
}
void input()
{
cout<<“\n Enter number 1”;
cin>>a;
cout<<“Enter second number 2\n”;
cin>>b;
}
int check()
{
if(a>b)
return a;
else
return b;
}
};
Defining member functions
 Member functions can be defined in two places

 Outside the class definition


 Inside the class definition
ARRAYS WITHIN A CLASS
#include<iostream>
using namespace std; int main()
class student
{ {
int roll_no; student stu;
int marks[5]; stu.getdata();
public:
void getdata ();
stu.tot_marks();
void tot_marks (); }
};
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
cin>>roll_no;
for(int i=0; i<5; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<":";
cin>>marks[i];
}
}

void student :: tot_marks()


{
int total=0;
for(int i=0; i<5; i++)
total+= marks[i];
cout<<"\n\nTotal marks "<<total;
}
Outside the class definition
 Member functions that are declared inside a class have
to be defined separately outside the class.

 An important difference between member function


and normal function is that member function
incorporates a membership identity label in the header.

 This label tells the compiler which class the


function belongs to.
General form of member function
definition

 Return –type class-name :: function-name(argument-declaration)


 {
 Function body
 }
 Member-functions have special characteristics

 Several different classes can use the same function


name .The membership label will resolve their scope.

 Member functions can access the private data of a


class.

 A member function can call another member function


directly.
Inside the class definition
 Another way of defining member function is to replace
the function declaration by the actual function
definition inside the class.
 Class item
 {
 Int number;
 Float cost;

 Public:

 Void getdata(int a,float b); //declaration

 Void putdata() //definition inside the class


 {

 Cout<<number<<“\n”;
 Cout<<cost<<“\n”;

 }
 };
 When a function is defined inside a class,it is treated
as an inline function.

 Normally all small functions are defined inside the


class definition.
 A private member function can only be called by
another function that is member of its class.

 Even an object cannot invoke a private function using


the dot operator.
Nesting of members functions

 When a member function is called by another member


function of the same class , it is called Nesting of members
functions.
int nesting::largest()
{
class nesting if(m>n)
{ return(m);
private: else
int m,n; return(n);
public: }
void input(); void nesting::display()
void display(); {
int largest(); cout<<"the largest among
}; the m and n is"<<largest();
void nesting::input() }
{ intmain()
cout<<"input the vaues” {
cin>>m>>n; nesting s;
} s.input();
s.display();
}
Arrays Of Objects
 Consider the following Example

class employee
{
char name[30];
float age;
public:
void getdata();
void putdata();
};
 The identifier employee is a user-defined data type
and can be used to create objects that relate to
different categories of employees.

 Employee manager[3]; //Array of manager


 Employee foreman[15]; //Array of foreman
 Employee worker[75]; //Array of worker

 The array manager contains three objects (managers)


 Namely manager[0],manager[1] and manager[2] of
type employee class. Similarly for the others.
 The statement

 manager[i].putdata();

 Will display the data of the ith element of the array


manager.
 An array of objects is stored inside the memory in the
same way as a multi-dimensional array.

name
Manager[0]
age

name
Manager[1]
age

name
Manager[2]
age
#include<iostream.h>
class employee const int size=3;
{ int main()
char name[30]; {
float age; employee manager[size];
public: for(int i=0; i<size; i++)
void getdata(void); {
void putdata(void); cout<<“\n details of
}; manager”<<i+1<<\n;
void employee::getdata() manager[i].gettdata();
{ }
cout<<“enter name:”; for(int i=0; i<size; i++)
cin>>name; {
cout<<“enter age”; cout<<“\n manager”<<i+1<<\n;
cin>>age; manager[i].putdata();
} }
void employee::putdata() }
{
cout<<“name:”<<name<<“\n”;
cout<<“age”;<<age<<“\n”;
}
 Objects as Function arguments

 An object may be used as a function argument.

 This can be done in two ways.

 1)A copy of the entire object is passed to the function.


 2)Only the address of the object is passed to the
function.
OBJECTS AS ARGUMENTS
#include<iostream.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<<hours<<"hours and ";
cout<<minutes<<"minutes"<<"\n";
}
void sum(time,time);
};
void time::sum(time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours =minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
int main()
{
time t1,t2,t3;
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(T1,T2);
cout<<"T1 = "; t1.puttime();
cout<<"T2 = "; t2.puttime();
cout<<"T3 = "; t3.puttime();
return 0;
}
Objects as arguments (Example)
void convert::conv_cm(convert obj)
{
#include<iostream.h> obj.cm=obj.m*100;
using namespace std; cout<<"\n \t in cm"<<obj.cm;
class convert }
{
float cm,m;
public:
void input(); int main()
void conv_cm(convert); {
}; convert obj1,obj2;
obj1.input();
obj1.conv_cm(obj1);
void convert::input() obj2.input();
{ obj2.conv_cm(obj2);
cout<<"please enter value in }
metres";
cin>>m;
}
Passing objects as refernce
 The memory address of the object is passed to the
function and the called function operates on the
original object being passed,

 Any change made to the object inside the function will


reflect in the actual argument.
#include<iostream.h>
Int main()
class number
{
{
number obj1,obj2;
int num;
obj2.get();
public:
obj2.put();
void modify(number &n)
obj1.modify(obj2);
{
obj2.put();
n.num++;
}
}
void get()
{
num=10;
}
void put()
{
cout<<num<<endl;
}
};
Returning objects
Rectangle Sum(Rectangle Rec)
#include<iostream.h>
{
class Rectangle
{
Rectangle temp;
int L,B; temp.L = L + Rec.L;
public: temp.B = B + Rec.B;
void set (int a,int b) return temp;
{ }
L=a; void Display()
B=b; {
} cout<<"\nLength : "<<L;
int main() cout<<"\nBreadth : "<<B;
{ }

Rectangle R1,R2,R3; };
R1.set(5,7);
R2.set(2,3);
R1.Display();
R2.Display();
R3 = R1.Sum(R2);
R3.Display();
}
Classes within classes (Nested Classes)

C++ permits declaration of a class within another class. A class declared as a


member of another class is called as a nested class.
The general syntax of the nested class declaration is shown below.
Class outer_class_name
{
private:
// data members
//member functions
public:
//data members
//member functions
class inner_class_name
{
private:
// data members
//member functions
public:
//data members
//member functions
};
};
void student_info::stu_info(char n[], long int r,
class student_info char s)
{ {
private: strcpy(name,n);
char name[20[;
rollno=r;
long int rollno;
gender=s;
char gender;
public: }
void stu_info( char na[],long int r, char void student_info::date::dated(int dy, int mh,
s); int yr)
void display(); {
class date day=dy;
{ month=mh;
private: year=yr;
int day; }
int month;
void student_info::display()
int year;
{
public:
void dated(int dy, int mh, int yr); cout<<“student name rollno gender
date of birth\n”;
void show_date();
}; cout<<“\n”<<name<<“\t”<<rollno<<“\t”
<<gender;
};
}
void student_info::date::show_date()
{
cout<<day<<“/”<<month<<“/”<<year<<endl;
}
intmain()
{
student_info obj1;
obj1.stu_info(“aryan”,95001, ‘m’);
student_info::date obj2;
obj2.data(13,7,94);
obj1.display();
obj2.show_date();
}
Practice Questions
#include<iostream.h>
int main()
class train
{
{
train t(10),n;
int tno,tripno,personcount;
n.trip();
public:
t.show();
train(int tmno=1)
t.trip(70);
{
n.trip(40);
tno=tmno;
n.show();
tripno=0;
t.show();
personcount=0;
}
}
void trip(int tc=100)
{
tripno++;
personcount+=tc;
}
void show()
{

cout<<tno<<":"<<tripno<<":"<
<personcount<<endl;
}
};
#include<iostream.h>
using namespace std;
void execute(int &x,int y=150)
{
int temp=x+y;
x+=temp;
if(y!=200)
cout<<temp<<"\t"<<x<<"\t"<<y<<endl;
}
int main()
{
int a=50,b=20;
execute(b);
cout<<a<<"\t"<<b<<endl;
execute(b,a);
cout<<a<<"\t"<<b<<endl;
}
#include<iostream.h>
class aroundus Void main()
{ {
int place,humidity,temp; aroundus a,b(5);
public: a.hot(10);
aroundus(int p=2) a.justsee();
{ b.humid(15);
place=p; b.hot(2);
humidity=60; b.justsee();
temp=20; a.humid(5);
} a.justsee();
void hot(int t) }
{
temp +=t;
}
void humid(int h)
{
humidity+=h;
}
void justsee()
{

cout<<place<<“:”<<temp<<“&”<<humidity<<“%”<<endl;
}

};
Write an equivalent while loop for the
following for loop

for(int i=2,sum=0;i<20;i+i+2)
sum+=i;

i=2;sum=0;
while(i<=20)
{
sum+=i;
i=i+2;
}
Rewrite the following code using a for loop

int i=99;

while (i>=0)
{
cout<<“half of this is “<<i<<endl;
i=i/2;
}
Rewrite the following code using a while loop

int i,x=0;
for(i=0;x<5;++i)
x+=i;
Rewrite the following code using switch

if(ch==’p’)
physcics++;
else if (ch==’m’)
maths++;
else if (ch==’b’)
biology++;
else if (ch==’c’)
chemistry++;
else
unknown++;

switch(ch)
Rewrite the following with a switch
Evaluate the output of the following statements

1) x=5; cout<<x++; cout<<x; cout<<++x;

2)Int a=50,b=10,c;cout<<c=(a>45)?a:b;
3)Int a=2,b,b=++a;cout<<a;cout<<b<<cout++a<<b++
Give the output of the following

#include<iostream.h>
Int main()
{
C
Ca
char *str=“CALIFORNIA”; Cal
for(int i=0;str[i ]!=‘\0’;i++)
{ Cali
for(int j=0;j<=i;j++) Calif
cout<<str[j]; Califo
cout<<endl;
} Califor
} Californ
Californi
calofornia
#include<iostream.h>
int main()
{
int z[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
int a,b;
for(a=0;a<3;++a)
for(b=0;b<4;++b)
if(z[a][b]%2==1)
z[a][b]--;

for(a=0;a<3;++a)
{
cout<<endl;
for(b=0;b<4;++b)
cout<<z[a][b]<<"\t";
}
}
Convert the following if else code into its equivalent switch case

Char code;
Cin>>code;
If(code==‘A’)
Cout<<“Accountant”;
Else if (code==‘C’||code==‘G’)
Cout<<“GradeIV”;
Else if (code==‘F’)
Cout<<“Financial Advisor”;
Else
Cout<<“Wrong code”;
Write a program in C++ to display the following pattern for N number of
lines .

*
* * *
* * * * *

The function should accept number 0f lines as its arguments


#include<iostream.h>
int main()
{
int n,j,k,p;
cout<<"enter n"<<endl;
cin>>n;
for(int i=1;i<=n;i++)
{
for( j=i;j<=n;j++)
cout<<" ";
for( k=i;k<=2*i-1;k++)
cout<<"* ";

cout<<endl;
}
}
Write a user defined function named pattern() which accepts an integer number
as parameter which represents the total number of lines to be generated to
display a pattern.

Eg if n=4

*
* *
* *
* * * * * * *
Void pattern(int n)
{
int I,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=2*i-1;j++)
if(j==1||j==2*i-1||i==n)
cout<<“*”;
else
cout<<“ ”;
cout<<endl;
}
}
Switch(code)
{
case’A’:
cout<<“Accountant”;
break;
case ‘C’:
case ‘G’:
cout<<“Grade IV”;
Break;
case’F’:
cout<<“Financial Advisor”;
break;
default:
cout<<“Wrong Choice”;
}
Write a user defined function in C++ to display the following pattern for N
number of lines .

1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4

The function should accept number 0f lines as its arguments

Prelims 2016
Generate the following pattern in C++

1234
5678
9012
3456
#include<iostream.h>
int main()
{
int n,i,j,a=1;
cout<<"Enter the number of rows : ";
cin>>n;
cout<<"The number pattern is : \n";
for(i=1; i<=n; i++)
{
for(j=1; j<=4; j++)
{
cout<<a;
if(a<9)
a++;
else
a=0;
}
cout<<endl;
}
}
1
2 3
3 45
4 567
5 6789
#include<iostream.h>
using namespace std;
int main()
{
int i,j,a,n;
cout<<"Enter number of rows : ";
cin>>n;
for(i=1;i<=n;i++)
{
a=i;
for(j=1;j<=i;j++)
{
cout<<a<<" ";
a++;
}
cout<<"\n";
}

}
Void pattern(int n)
{
int n,j,k,p;
cout<<"enter n"<<endl;
cin>>n;
for(int i=1;i<=n;i++)
{
for( j=i;j<=n;j++)
cout<<" ";
for( k=i;k<=2*i-1;k++)
cout<<k;
for( p=k-2;p>=i;p--)
cout<<p;
cout<<endl;
}
}
Write a complete C program to accept a positive number N.The program
should count and display the number of even digits present in the number.

#include<iostream.h>
using namespace std;
int main() Prelims 2015
{
long int n;
int count=0;
cout<<"Enter any positive number \n ";
cin>>n;
while(n>0)
{
int d=n%10;
if(d%2==0)
{
cout<<d<<endl;
count++;
}
n=n/10;
}
cout<<"Number of even digits \n"<<count;
}
Write a C program to find the sum of the following series.
1+(1+2)+(1+2+3)+(1+2+3+4)+……….+upto N terms.

#include<stdio.h>
int main() Prelims 2016
{
int n,sum,i,j,t;
printf("Enter how many number of terms you want to add \n");
scanf("%d",&n);
sum=0;
for( i=1;i<=n;i++)
{
t=0;
for( j=1;j<=i;j++)
t=t+j;
sum=sum+t;
}
printf("Sum of first %d terms is %d\n",n,sum);
}
Write a complete C++ program to generate the following pattern

1
2 4
1 3 5
2 4 6 8
Write a C++ program to generate the following pattern

*
**
***
****
*****
#include<iostream>
using namespace std;
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
cout<<' ';
for(k=1;k<=i;k++)
cout<<'*';
cout<<endl;
}
}
#include<iostream.h>
using namespace std;
int main()
{
int i,x;
for(int i=1;i<=4;i++)
{
if(i%2==0)
x=2;
else
x=1;
for(int j=1;j<=i;j++,x+=2)
{
cout<<x<<" ";
}
cout<<endl;
}
}
Write a complete C++ program to generate the following
pattern
Board 2016

If n=4

10 9 8 7

6 5 4

3 2

1
#include<iostream.h>
void main()
{
int n,k;
cout<<“enter the number of lines “;
cin>>n;
k=n*(n+1)/2;
for(int i=n;i>0;i--)
{
for(int j=0;j<i;j++)
{
cout<<k<<“ “;
k--;
}
cout<<endl;
}
}
Find the Output

#include<iostream.h>
#include<string.h>
#include<ctype.h>
void newtext(char string[],int &position)
{
int length=strlen(string);
for(;position<length-2;position++)
string[position]=toupper(string[position]);
}
int main()
{
int loc=3;
char message[]="Silver Zone";
newtext(message,loc);
cout<<message<<"#"<<loc;
}
Write a c++ program to check if number entered is prime number

#include<iostream.h>
using namespace std;
int main()
{
int n,temp,flag=0;
cout<<"enter the number";
cin>>n;
temp=n;
for(int i=2;i<n;i++)
{

if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0)
cout<<" prime";
else
cout<<"not prime";
}
Define a class play in C++ with the following specifications

Private data members:


Play code:integer
Playtitle:array of 20 characters
Duration:Type float
Noofscenes:integer

Public members:

1. Newplay()-function to accept values for playcode and playtitle.


2. Moreinfo()-Function to assign the data values of duration and no.of
scenes with the help of corresponding values passed as parameters to this
function.
3. Showplay()-Function to display all the datamembers on the screen.
Class play Void play::showplay()
{ {
int playcode; cout<<playcode;
char playtitle[25]; cout<<playtitle;
float duration; cout<<duration;
int noofscenes; cout<<noofscenes;
public: }
void newplay();
void moreinfo(float,int);
void showplay();
};
Void play::newplay()
{
cout<<“Enter the playcode”<<endl;
cin>>playcode;
cout<<“Enter the title of the
play”<<endl;
gets(playtitle);
}
Void play::moreinfo(float x,int y)
{
duration=x;
noofscenes=y;
}
Write a C program to check if a number entered by the user is emirp number or not
.Emirp number is any number which is prime backwards and forward.

For example 13 is emirp number as 13 and 31 both are prime numbers.


while(temp>0)
{
#include<iostream.h>
x=temp%10;
int main()
rev=rev*10+x;
{
temp=temp/10;
int a,temp,x,count1=0,count2=0,rev=0;
}
cout<<"enter a number";
for(int y=1;y<=rev;y++)
cin>>a;
{
temp=a;
if(rev%y==0)
for(int i=1;i<=a;i++)
{
{
if(a%i==0)
count2++;
{
}
count1++;
}
}
if(count1==2&&count2==2)
}
{

printf("Emirp number");
}
else
printf("non emirp number");
}
int main()
#include<iostream.h>
{
void modify(int &a,int b=10)
disp(3);
{
disp(4);
if(b%10==0)
modify(2,20);
a+=5;
}
for(int i=5;i<=a;i++)
cout<<b++<<":";
cout<<endl;
}
void disp(int x)
{
if(x%3==0)
modify(x);
else
10:11:12:13
}
modify(x,3);
20:21:22
#include<iostream.h>
using namespace std;
int main()
{
int numbers[]={2,4,8,10};
int *ptr=numbers;
for(int c=0;c<3;c++)
{
cout<<*ptr<<"@";
ptr++;
}
cout<<endl;
for(int c=0;c<4;c++)
{
(*ptr)*=2;
--ptr;
}
for(int c=0;c<4;c++)
cout<<numbers[c]<<"#";
cout<<endl;
}
Determine the output of the following program:

#include<iostream.h>
Void indirect(int temp=20)
{
for(int i=1;i<=temp;i+=5)
cout<<i<<“ ”;
cout<<endl;
}
Void direct(int &num) 1,6,11,16,21,26
{
num+=10; 1,6,11,16
indirect(num);
} 30
Void main()
{
int number=20;
direct(number);
indirect();
cout<<number<<endl;
}
Consider the following program

#include<iostream.h>
Class complex
{ Define inline member function product that
int real,imag; multiplies objects sent as parameter
public:
void show()
{
cout<<endl<<real<<“+”<<imag;
}
complex(int x,int y)
{
real=x;
imag=y;
}
};
Int main()
{
complex a(12,20),b(23,40)
complex c;
c.product();
a.show();
b.show();
c.show();
}
Void product(complex x,complex y)
{
real=x.real*y.real-x.imag*y.imag;
imag=x.real*y.imag+y.real;
}
#include <iostream.h>
int main()
{
int row, c, n, temp;
cout<<"Enter the number of rows\n";
cin>>n;
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( c = 1 ; c < temp ; c++ )
cout<<" "; // space
temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
cout<<"*";
cout<<"\n";
}

}
Define a class report in C++ with the following specifications

Private members
1)Stream – array of 10 characters
2)Mno –of type integer
3)name-array of 30 characters
4)div-01 character
5)grade-01 character
6)remark-array of 30 characters
7)getremark()- function which assigns remark based on the following
conditions

Remark Condition

“Qualify for next class” If student secures a grade from A to


G

“Needs Improvement If Student secures H or I grade

CONTD
Public:
1)Input()- function to ask and store the value of mno,name,class,div,grade and call
getremark() function to assign remark
2)Display()-Function to display all the data members.
Class report
{
char stream[10],name[20],remark[20];
int rno;
char div,grade;
void getremark();
public:
void input();
void display();
};
Void report::input()
{
cout<<“enter stream\n”;
gets(stream);
cout<<“Enter name\n”;
gets(name);
cout<<“Enter roll number\n”;
cin>>rno;
cout<<“enter division\n”;
cin>>div;
cout<<“enter the grade\n”;
cin>>grade;
};
Void report::getremark()
{
if(grade==‘A’||grade==‘B’||grade==‘C’||grade==‘D’||grade==‘E’||grade==‘F’
||grade==‘G’)
strcpy(remark,”Qualify for next class”);
else
strcpy(remark,”Needs Improvement”);
}

Void report::display()
{
cout<<“\nStream:-”<<stream;
cout<<“\nName:-”<<name;
cout<<“\nRemark”<<remark;
cout<<“\nRoll No”<<rno;
cout<<“\n Division”<<div;
cout<<“\n Grade”<<Grade;
}
#include<iostream.h>
int m=2;
int setvalue(int &x,int y)
{
x=m*x-x/y;
y=m*y-x%y;

}
return y; 6 4 4 16
int main()
{
int m=4,p,q;
p=setvalue(m,::m);
q=setvalue(::m,p);
cout<<"\n"<<m<<" "<<::m<<" "<<p<<" "<<q;
}
Define a class named EGG with the following specfications
Private:
1)Doz of type integer
2)No of type integer
3)Define a member function getdata which accepts values for all the data members
4)Define a member function sum() which accepts two objects as parameters and
initialises data members as per the summation of dozons of both the objects (refer
example below)
5)Define a member function show()in public visibility label to display values of data
members of all the objects .Further write appropriate main () function.

Example

If obj1 is 3 doz 8 numbers


obj2 is 4 doz 6 numbers
obj3 is 8 doz 2 numbers
#include<iostream.h>
class egg
{
int doz,no;
public:
void getdata()
{
cout<<"Enter the value of doz\n";
cin>>doz;
cout<<"enter the value of no\n";
cin>>no;
}
void show()
{
cout<<"Dozen"<<doz;
cout<<"Numbers"<<no<<endl;

}
void sum(egg t1,egg t2);
};
void egg::sum(egg t1,egg t2)
{
no=t1.no+t2.no;
doz=no/12;
no=no%12;
doz=doz+t1.doz+t2.doz;

}
int main()
{
egg t1,t2,t3;
t1.getdata();
t2.getdata();
t3.sum(t1,t2);
t1.show();
t2.show();
t3.show();
}
Write a complete procedural C++ program to print all two digit special numbers.

Note:A special number is a number in which adding sum of f digits to the product
of digits gives the original number.

Ex:49 is a special number because

Sum of digits 4+9=13


Product of digits 4*9=36

36+13=49
#include<iostream.h>
Int main()
{
int x,sum,product,digit;
cout<<“\n”;
for(int i=10;i<=99;i++)
{
x=i;
sum=0; product=1;
while(x!=0)
{
digit=x%10;
sum=sum+digit;
product=product*digit;
x=x/10;
}
if(i==sum+product)
cout<<i<<“,”;
}
}
Write a user defined function named design() in c++ which accepts two character
variables x,y and a positive integer variable n as parameter and generates the
following pattern for n lines.

If n=5,x=‘*’,y=“#’ then pattern to be generated is

*
##
* * *
## # #
* * * * *
Void design(char x,char y,int n)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
if(i%2!=0)
cout<<x<<“ ”;
else
cout<<y<<“ ”;
}
}
}
Write a short note on precedence and associativity of
operators in C++

Precedence:-order of execution of operators in


same or different groups of operators

Associativity:-Direction of execution of
operators from left to right or right to left in
same precedence group.
#include<iostream.h>
using namespace std;
void revert(int &num,int last=2)
{
last=(last%2==0)?last+1:last-1;
for(int c=1;c<=last;c++)
num+=c;
}
int main()
{
int a=20,b=4;
revert(a,b);
cout<<a<<"&"<<b<<endl;
b--;
revert(a,b);
cout<<a<<"#"<<b<<endl;
revert(b);
cout<<a<<"#"<<b<<endl;
}
Prelims 2018

Write a user defined function named pattern() which accpets a positive


integer number ‘n’ as parameter and generates the following pattern for n
lines

If n=4 then output is

1
2 4
3 6 9
4 8 12 16
Void pattern(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
cout<<i*j<<“ ”;
cout<<endl;

}
}

Vous aimerez peut-être aussi