Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
135 views

Object Oriented Programming Notes

The document discusses object oriented programming in C++. It covers: - C++ compilers convert source code to object files that can be executed by computers. The preprocessing, compiling, and linking stages are described. - The basic building blocks of C++ like character sets, tokens, literals, punctuators, and operators are defined. Data types like integers, characters, and floating points are also introduced. - Variables are used to store and manipulate data in programs. Input/output streams allow getting data into programs and displaying output. Type conversion changes an expression's data type.

Uploaded by

elvis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views

Object Oriented Programming Notes

The document discusses object oriented programming in C++. It covers: - C++ compilers convert source code to object files that can be executed by computers. The preprocessing, compiling, and linking stages are described. - The basic building blocks of C++ like character sets, tokens, literals, punctuators, and operators are defined. Data types like integers, characters, and floating points are also introduced. - Variables are used to store and manipulate data in programs. Input/output streams allow getting data into programs and displaying output. Type conversion changes an expression's data type.

Uploaded by

elvis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

OBJECT ORIENTED PROGRAMMING 1

INTRODUCTION:

A computer cannot understand our language that we use in our day to day conversations,
and likewise, we cannot understand the binary language that the computer uses to do it’s
tasks. It is therefore necessary for us to write instructions in some specially defined
language like C++ which is like natural language and after converting with the help of
compiler the computer can understand it.

C++ COMPILER

A C++ compiler is itself a computer program which only job is to convert the C++
program from our form to a form the computer can read and execute. The original C++
program is called the “source code”, and the resulting compiled code produced by the
compiler is usually called an “object file”.

Before compilation the preprocessor performs preliminary operations on C++ source


files. Preprocessed form of the source code is sent to compiler.

After compilation stage object files are combined with predefined libraries by a linker,
sometimes called a binder, to produce the final complete file that can be executed by the
computer. A library is a collection of pre-compiled “object code” that provides operations
that are done repeatedly by many computer programs.

Compiling and linking process C++ program Using Turbo C++ Compiler

1
The first and frequently used method for creating program is Turbo C++'s Integrated
Developement Enviornment (IDE). To start IDE type TC at DOS prompt. Or search the
file TC.EXE in your computer and Run it.

Before we begin to learn to write meaningful programs in C++ language, let us have a
look at the various building block of C++ language, also called elements of C++
language....

C++ CHARACTER SET

Character set is a set of valid characters that a language can recognize.


Letters A-Z, a-z
Digits 0-9
Special Characters Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ? _ #
<= >= @
Formatting characters backspace, horizontal tab, vertical tab, form feed, and carriage
return

TOKENS

A token is a group of characters that logically belong together. The programmer can write
a program by using tokens. C++ uses the following types of tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.

1. Keywords

These are some reserved words in C++ which have predefined meaning to compiler
called keywords. Some commonly used Keyword are given below:

2
asm auto break case catch
char class const continue default
delete do double else enum
extern inline int float for
friend goto if long new
operator private protected public register
return short signed sizeof static
struct switch template this Try
typedef union unsigned virtual void
volatile while

2. Identifiers

Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a
sequence of characters taken from C++ character set. The rule for the formation of an
identifier are:

* An identifier can consist of alphabets, digits and/or underscores.


* It must not start with a digit
* C++ is case sensitive that is upper case and lower case letters are considered different
from each other.
* It should not be a reserved word.

3. Literals

Literals (often referred to as constants) are data items that never change their value during
the execution of the program. The following types of literals are available in C++.

* Integer-Constants
* Character-constants

3
* Floating-constants
* Strings-constants

Integer Constants

Integer constants are whole number without any fractional part. C++ allows three types
of integer constants.
Decimal integer constants : It consists of sequence of digits and should not begin with 0
(zero). For example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For
example. 014, 012.

Hexadecimal integer constant: It consists of sequence of digits preceded by ox or OX.


Character constants

A character constant in C++ must contain one or more characters and must be enclosed in
single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which
cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These
characters can be represented by using an escape sequence. An escape sequence
represents a single character. The following table gives a listing of common escape
sequences.

Escape Sequence Nongraphic Character


\a Bell (beep)
\n Newline
\r Carriage Return
\t Horizontal tab
\0 Null Character

Floating constants

4
They are also called real constants. They are numbers having fractional parts. They may
be written in fractional form or exponent form. A real constant in fractional form consists
of signed or unsigned digits including a decimal point between digits. For example 3.0, -
17.0, -0.627 etc.

String Literals

A sequence of character enclosed within double quotes is called a string literal. String
literal is by default (automatically) added with a special character ‘\0' which denotes the
end of the string. Therefore the size of the string is increased by one character. For
example "COMPUTER" will re represented as "COMPUTER\0" in the memory and its
size is 9 characters.

4. Punctuators

The following characters are used as punctuators in C++.


Brackets [ ] Opening and closing brackets indicate single and multidimensional array
subscript.
Parentheses ( ) Opening and closing brackets indicate functions calls,; function
parameters for grouping expressions etc.
Braces { } Opening and closing braces indicate the start and end of a compound
statement.
Comma , It is used as a separator in a function argument list.
Semicolon ; It is used as a statement terminator.
Colon : It indicates a labeled statement or conditional operator symbol.
Asterisk * It is used in pointer declaration or as multiplication operator.
Equal sign = It is used as an assignment operator.
Pound sign # It is used as pre-processor directive.

5. Operators

5
Operators are special symbols used for specific purposes. C++ provides six types of
operators. Arithmetical operators, Relational operators, Logical operators, Unary
operators, Assignment operators, Conditional operators, Comma operator

DATA HANDLING,BASIC DATA TYPES

C++ supports a large number of data types. The built in or basic data types supported by
C++ are integer, floating point and character. These are summarized in table along with
description and memory requirement

Type Byte Range Description


int 2 -32768 to +32767 Small whole number
long int 4 -2147483648 to +2147483647 Large whole number
float 4 3.4x10-38 to 3.4x10+38 Small real number
double 8 1.7x10-308 to 1.7x10+308 Large real number
long double 10 3.4x10-4932 to 3.4x10+4932 Very Large real number
char 1 0 to 255 A Single Character

VARIABLES

It is a location in the computer memory which can store data and is given a symbolic
name for easy reference. The variables can be used to hold different values at different
times during the execution of a program.

To understand more clearly we should study the following statements:


Total = 20.00; In this statement a value 20.00 has been stored in a memory location Total.

Declaration of a variable

6
Before a variable is used in a program, we must declare it. This activity enables the
compiler to make available the appropriate type of location in the memory.
float Total;

You can declare more than one variable of same type in a single statement
int x,y;

Initialization of variable

When we declare a variable it's default value is undetermined. We can declare a variable
with some initial value.
int a = 20;

INPUT/OUTPUT (I/O)

C++ supports input/output statements which can be used to feed new data into the
computer or obtain output on an output device such as: VDU, printer etc. The following
C++ stream objects can be used for the input/output purpose.

cin console input


cout console output

cout is used in conjuction with << operator, known as insertion or put to operator.
cin is used in conjuction with >> operator, known as extraction or get from operator.

cout << “My first computer"; Once the above statement is carried out by the computer,
the message "My first computer" will appear on the screen.

cin can be used to input a value entered by the user from the keyboard. However, the get
from operator>> is also required to get the typed value from cin and store it in the
memory location.

7
Let us consider the following program segment:
int marks;
cin >> marks; In the above segment, the user has defined a variable marks of integer type
in the first statement and in the second statement he is trying to read a value from the
keyboard.

TYPE CONVERSION

The process in which one pre-defined type of expression is converted into another type is
called conversion. There are two types of conversion in C++.

1. Implicit conversion
2. Explicit conversion

Implicit conversion
Data type can be mixed in the expression. For example
double a;
int b = 5;
float c = 8.5;
a = b * c;

When two operands of different type are encountered in the same expression, the lower
type variable is converted to the higher type variable. The following table shows the
order of data types.
Order of data types
Data type
long double
double
float
long
int

8
char order (highest)

To (lowest)

The int value of b is converted to type float and stored in a temporary variable before
being multiplied by the float variable c. The result is then converted to double so that it
can be assigned to the double variable a.

Explicit conversion
It is also called type casting. It temporarily changes a variable data type from its declared
data type to a new one. It may be noted here that type casting can only be done on the
right hand side the assignment statement.
T_Pay = double (salary) + bonus;
Initially variable salary is defined as float but for the above calculation it is first
converted to double data type and then added to the variable bonus.

CONSTANTS

A number which does not change its value during execution of a program is known as a
constant. Any attempt to change the value of a constant will result in an error message. A
constant in C++ can be of any of the basic data types, const qualifier can be used to
declare constant as shown below:
const float pi = 3.1415; The above declaration means that Pi is a constant of float types
having a value 3.1415.
Examples of valid constant declarations are:
const int rate = 50;
const float pi = 3.1415;
const char ch = 'A';

STRUCTURE OF C++ PROGRAM

9
Refer to class notes

A C++ program starts with function called main ( ). The body of the function is enclosed
between curly braces. The program statements are written within the braces. Each
statement must end by a semicolon;(statement terminator). A C++ program may contain
as many functions as required. However, when the program is loaded in the memory, the
control is handed over to function main ( ) and it is the first function to be executed.
// This is my first program is C++
/* this program will illustrate different components of
a simple program in C++ */

# include <iostream.h>
int main ( )
{
cout <<"Hello World!";
return 0;
}

When the above program is compiled, linked and executed, the following output is
displayed on the VDU screen.

Hello World!

Various components of this program are discussed below:


Comments

First three lines of the above program are comments and are ignored by the compiler.
Comments are included in a program to make it more readable. If a comment is short and
can be accommodated in a single line, then it is started with double slash sequence in the

10
first line of the program. However, if there are multiple lines in a comment, it is enclosed
between the two symbols /* and */

#include <iostream.h>

The line in the above program that start with # symbol are called directives and are
instructions to the compiler. The word include with '#' tells the compiler to include the
file iostream.h into the file of the above program. File iostream.h is a header file needed
for input/ output requirements of the program. Therefore, this file has been included at
the top of the program.

int main ( )

The word main is a function name. The brackets ( ) with main tells that main ( ) is a
function. The word int before main ( ) indicates that integer value is being returned by the
function main (). When program is loaded in the memory, the control is handed over to
function main ( ) and it is the first function to be executed.
Curly bracket and body of the function main ( )

A C++ program starts with function called main(). The body of the function is enclosed
between curly braces. The program statements are written within the brackets. Each
statement must end by a semicolon, without which an error message in generated.
cout<<"Hello World!";

This statement prints our "Hello World!" message on the screen. cout understands that
anything sent to it via the << operator should be printed on the screen.
return 0;

11
This is a new type of statement, called a return statement. When a program finishes
running, it sends a value to the operating system. This particular return statement returns
the value of 0 to the operating system, which means “everything went okay!”.
/* This program illustrates how to declare variable, read data and display data. */

#include <iostream.h>
int main()
{
int rollno; //declare the variable rollno of type int
float marks; //declare the variable marks of type float
cout << "Enter roll number and marks :";
cin >> rollno >> marks; //store data into variable rollno & marks
cout << "Rollno: " << rollno<<"\n";
cout << "Marks: " << marks;
return 0;
}

Sample Run: In this sample run, the user input is shaded.

Enter roll number and marks :102 87.5


Rollno: 102
Marks: 87.5

OPERATORS

Operators are special symbols used for specific purposes. C++ provides six types of
operators.
Arithmetical operators,
Relational operators,

12
Logical operators,
Unary operators,
Assignment operators,
Conditional operators,
Comma operator

Arithmetical operators

Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric)


operation. You can use the operators +, -, *, and / with both integral and floating-point
data types. Modulus or remainder % operator is used only with the integral data type.
Operators that have two operands are called binary operators.

Relational operators

The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational expression
returns zero when the relation is false and a non-zero when it is true. The following table
shows the relational operators.

Relational Operators Meaning


< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to

Logical operators

13
The logical operators are used to combine one or more relational expression. The logical
operators are:

Operators Meaning
|| OR
&& AND
! NOT

Unary operators

C++ provides two unary operators for which only one variable is required.
For Example a = - 50;
a = + 50; Here plus sign (+) and minus sign (-) are unary because they are not used
between two variables.

Assignment operator

The assignment operator '=' is used for assigning a variable to a value. This operator takes
the expression on its right-hand-side and places it into the variable on its left-hand-side.
For example: m = 5; The operator takes the expression on the right, 5, and stores it in the
variable on the left, m. x = y = z = 32; This code stores the value 32 in each of the three
variables x, y, and z. in addition to standard assignment operator shown above, C++ also
support compound assignment operators.

Compound Assignment Operators


Operator Example Equivalent to
+= A+=2 A=A+2
-= A-=2 A=A-2
%= A%=2 A=A%2
/= A/ = 2 A=A/2
*= A*=2 A=A*2

14
Increment and Decrement Operators

C++ provides two special operators viz '++' and '--' for incrementing and decrementing
the value of a variable by 1. The increment/decrement operator can be used with any type
of variable but it cannot be used with any constant. Increment and decrement operators
each have two forms, pre and post.

The syntax of the increment operator is:

Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: ––variable
Post-decrement: variable––

In Prefix form first variable is first incremented/decremented, then evaluated


In Postfix form first variable is first evaluated, then incremented/decremented
int x,y;
int i=10,j=10;
x = ++i; //add one to i, store the result back in x
y= j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10

Conditional operator

The conditional operator ?: is called ternary operator as it requires three operands. The
format of the conditional operator is:
Conditional_ expression ? expression1 : expression2;

15
If the value of conditional expression is true then the expression1 is evaluated, otherwise
expression2 is evaluated. int a = 5, b = 6;
big = (a > b) ? a : b; The condition evaluates to false, therefore biggets the value from b
and it becomes 6.

The comma operator

The comma operator gives left to right evaluation of expressions. When the set of
expressions has to be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i Would first assign the value of a to i, and then assign value of b
to variable i. So, at the end, variable i would contain the value 2.

The sizeof operator

As we know that different types of Variables, constant, etc. require different amounts of
memory to store them The sizeof operator can be used to find how many bytes are
required for an object to store in memory. For example
sizeof (char) returns 1
sizeof (int) returns 2
sizeof (float) returns 4
If k is integer variable, the sizeof (k) returns 2.
the sizeof operator determines the amount of memory required for an object at compile
time rather than at run time.

The order of Precedence

The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is
called the order of precedence. The following table shows the order of precedence.
Order Operators
First

16
Second
Third ()
*, /, %
+, -

The following table shows the precedence of operators.


++, --(post increment/decrement)

Highest

To

Lowest
++ (Pre increment) -- (Pre decrement), sizeof ( ), !(not), -(unary), +(unary)
*,/, %
+, -
<, <=, >, >=
==,!=
&&
?:
=

Comma operator

FLOW OF CONTROL

Statements

17
Statements are the instructions given to the computer to perform any kind of action.
Action may be in the form of data movement, decision making etc. Statements form the
smallest executable unit within a C++ program. Statements are always terminated by
semicolon.
Compound Statement

A compound statement is a grouping of statements in which each individual statement


ends with a semi-colon. The group of statements is called block. Compound statements
are enclosed between the pair of braces ({}.). The opening brace ({) signifies the
beginning and closing brace (}) signifies the end of the block.

Null Statement

Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement.
This is quite useful when the syntax of the language needs to specify a statement but the
logic of the program does not need any statement. This statement is generally used in for
and while looping statements.

Conditional Statements

Sometimes the program needs to be executed depending upon a particular condition. C++
provides the following statements for implementing the selection control structure.

* if statement
* if else statement
* nested if statement
* switch statement

if statement

18
syntax of the if statement
if (condition)
{
statement(s);
}

From the flowchart it is clear that if the if condition is true, statement is executed;
otherwise it is skipped. The statement may either be a single or compound statement.

if-else

if else statement

syntax of the if - else statement


if (condition)
statement1;
else
statement2;

From the above flowchart it is clear that the given condition is evaluated first. If the
condition is true, statement1 is executed. If the condition is false, statement2 is executed.
It should be kept in mind that statement and statement2 can be single or compound
statement.

if example if else example


if (x == 100)
cout << "x is 100"; if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

19
Nested if statement

The if block may be nested in another if or else block. This is called nesting of if or else
block.

syntax of the nested if statement


if(condition 1)
{
if(condition 2)
{
statement(s);
}
}

if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

if-else-if example
if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;

20
switch statement

The if and if-else statements permit two way branching whereas switch statement permits
multiple branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement 1;
break;
case constant2 : statement2;
break;
.
.
default: statement3;
break;
}

The execution of switch statement begins with the evaluation of expression. If the value
of expression matches with the constant then the statements following this statement
execute sequentially till it executes break. The break statement transfers control to the
end of the switch statement. If the value of expression does not match with any constant,
the statement with default is executed.

Some important points about switch statement

* The expression of switch statement must be of type integer or character type.


* The default case need not to be used at last case. It can be placed at any place.
* The case values need not to be in specific order.

FLOW OF CONTROL

Looping statement

21
It is also called a Repetitive control structure. Sometimes we require a set of statements to
be executed a number of times by changing the value of one or more variables each time
to obtain a different result. This type of program execution is called looping. C++
provides the following construct

* while loop
* do-while loop
* for loop

While loop

Syntax of while loop


while(condition)
{
statement(s);
}

The flow diagram indicates that a condition is first evaluated. If the condition is true, the
loop body is executed and the condition is re-evaluated. Hence, the loop body is executed
repeatedly as long as the condition remains true. As soon as the condition becomes false,
it comes out of the loop and goes to the statement next to the ‘while’ loop.

while do-while loop


do-while loop

Syntax of do-while loop


do
{
statements;
} while (condition);

22
Note : That the loop body is always executed at least once. One important difference
between the while loop and the do-while loop the relative ordering of the conditional test
and loop body execution. In the while loop, the loop repetition test is performed before
each execution the loop body; the loop body is not executed at all if the initial test fail. In
the do-while loop, the loop termination test is Performed after each execution of the loop
body. hence, the loop body is always executed least once.

for loop

for loop

It is a count controlled loop in the sense that the program knows in advance how many
times the loop is to be executed.

syntax of for loop for (initialization; decision; increment/decrement)


{
statement(s);
}

The flow diagram indicates that in for loop three operations take place:

* Initialization of loop control variable


* Testing of loop control variable
* Update the loop control variable either by incrementing or decrementing.

Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test
whether the condition is true or false. If the condition is true, the program executes the

23
body of the loop and then the value of loop control variable is updated. Again it checks
the condition and so on. If the condition is false, it gets out of the loop.
Jump Statements

The jump statements unconditionally transfer program control within a function.

* goto statement
* break statement
* continue statement

The goto statement


goto allows to make jump to another point in the program. goto pqr;
pqr: pqr is known as label. It is a user defined identifier. After the execution of goto
statement, the control transfers to the line after label pqr.

The break statement


The break statement, when executed in a switch structure, provides an immediate
exit from the switch structure. Similarly, you can use the break statement in
any of the loop. When the break statement executes in a loop, it immediately exits from
the loop.

The continue statement


The continue statement is used in loops and causes a program to skip the rest of the body
of the loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;

24
}
The continue statement skips rest of the loop body and starts a new iteration.

The exit ( ) function


The execution of a program can be stopped at any point with exit ( ) and a status code can
be informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of
the code varies depending upon the operating system.

LIBRARY FUNCTION

# Include Directive
The # include directive instructs the compiler to read and include another file in the
current file. The compiler compiles the entire code. A header file may be included in one
of two ways.

include <iostream.h>
or
include "iostream.h"

The header file in angle brackets means that file reside in standard include directory. The
header file in double quotes means that file reside in current directory.

LIBRARY FUNCTIONS
Console I/O functions

The following are the list of functions are in stdio.h


getchar() It returns a single character from a standard input device (keyboard). It
takes no parameter and the returned value is the input character.

25
putchar() It takes one argument, which is the character to be sent to output device. It
also returns this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream
stdin.
puts() It takes a string which is to be sent to output device.

FUNCTION
A function is a subprogram that acts on data and often returns a value. A program written
with numerous functions is easier to maintain, update and debug than one very long
program. By programming in a modular (functional) fashion, several programmers can
work independently on separate functions which can be assembled at a later date to create
the entire project. Each function has its own name. When that name is encountered in a
program, the execution of the program branches to the body of that function. When the
function is finished, execution returns to the area of the program code from which it was
called, and the program continues on to the next line of code.

Creating User-Defined Functions

Declare the function.

The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the
functions to be used in a program, the argument they take and the type of value they
return.
Define the function.

The function definition tells the compiler what task the function will be performing. The
function prototype and the function definition must be same on the return type, the name,
and the parameters. The only difference between the function prototype and the function
header is a semicolon.

26
The function definition consists of the function header and its body. The header is
EXACTLY like the function prototype, EXCEPT that it contains NO terminating
semicolon.

//Prototyping, defining and calling a function


#include <iostream.h>
void starline(); // prototype the function
int main()
{
starline( ); // function call
cout<< "\t\tBjarne Stroustrup\n";
starline( ); // function call
return 0;
}

// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}

ARGUMENT TO A FUNCTION

Sometimes the calling function supplies some values to the called function. These are
known as parameters. The variables which supply the values to a calling function called
actual parameters. The variable which receive the value from called statement are termed
formal parameters.

27
Consider the following example that evaluates the area of a circle.
#include<iostream.h>
void area(float);
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;
}
void area(float r)
{
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}

Here radius is called actual parameter and r is called formal parameter.

RETURN TYPE OF A FUNCTION

// Example program
#include <iostream.h>

int timesTwo(int num); // function prototype


int main()
{
int number, response;
cout<<"Please enter a number:";
cin>>number;
response = timesTwo(number); //function call
cout<< "The answer is "<<response;
return 0;

28
}
//timesTwo function
int timesTwo (int num)
{
int answer; //local variable
answer = 2 * num;
return (answer);
}

CALLING OF FUNCTION
The function can be called using either of the following methods:

i) Call by value
ii) Call by reference

CALL BY VALUE
In call by value method, the called function creates its own copies of original values sent
to it. Any changes, that are made, occur on the function’s copy of values and are not
reflected back to the calling function.

CALL BY REFERENCE
In call be reference method, the called function accesses and works with the original
values using their references. Any changes, that occur, take place on the original values
are reflected back to the calling code.

Consider the following program which will swap the value of two variables.
using call by reference using call by value
#include<iostream.h>
void swap(int &, int &);
int main()
{

29
int a=10,b=20;
swap(a,b);
cout<<a<<" "<<b;
return 0;
}
void swap(int &c, int &d)
{
int t;
t=c;
c=d;
d=t;
} #include<iostream.h>
void swap(int , int );
int main()
{
int a=10,b=20;
swap(a,b);
cout<<a<<" "<< b;
return 0;
}
void swap(int c, int d)
{
int t;
t=c;
c=d;
d=t;
}
output:
20 10
output:
10 20

30
Function With Default Arguments
C++ allows to call a function without specifying all its arguments. In such cases, the
function assigns a default value to a parameter which does not have a mathching
arguments in the function call. Default values are specified when the function is declared.
The complier knows from the prototype how many arguments a function uses for calling.
Example : float result(int marks1, int marks2, int marks3=75); a subsequent function call
average = result(60,70); passes the value 60 to marks1, 70 to marks2 and lets the function
use default value of 75 for marks3.
The function call average = result (60, 70, 80); passes the value 80 to marks3.

INLINE FUNCTION
Functions save memory space because all the calls to the function cause the same code to
be executed. The functions body need not be duplicated in memory. When the complier
sees a function call, it normally jumps to the function. At the end of the function. it
normally jumps back to the statement following the call.
While the sequence of events may save memory space, it takes some extra time. To save
execution time in short functions, inline function is used. Each time there is a function
call, the actual code from the function is inserted instead of a jump to the function. The
inline function is used only for shorter code.

inline int cube(int r)


{
return r*r*r;
}

Some important points to be noted

* Function is made inline by putting a word inline in the beginning.


* Inline function should be declared before main() function.
* It does not have function prototype.

31
* Only shorter code is used in inline function If longer code is made inline then
compiler ignores the request and it will be executed as normal function.

Global Variable And Local Variable


Local Variable : a variable declared within the body of a function will be evaluated only
within the function. The portion of the program in which a variable is retained in memory
is known as the scope of the variable. The scope of the local variable is a function where
it is defined. A variable may be local to function or compound statement.
Global Variable : a variable that is declared outside any function is known as a global
variable. The scope of such a variable extends till the end of the program. these variables
are available to all functions which follow their declaration. So it should be defined at the
beginning, before any function is defined.

Variables and storage Class


The storage class of a variable determines which parts of a program can access it and how
long it stays in existence. The storage class can be classified as automatic register static
external

Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent.
Auto variables retain their scope till the end of the function in which they are defined. An
automatic variable is not created until the function in which it defined is called. When the
function exits and control is returned to the calling program, the variables are destroyed
and their values are lost. The name automatic is used because the variables are
automatically created when a function is called and automatically destroyed when it
returns.

Register variable
A register declaration is an auto declaration. A register variable has all the characteristics
of an auto variable. The difference is that register variable provides fast access as they are
stored inside CPU registers rather than in memory.

32
Static variable
A static variable has the visibility of a local variable but the lifetime of an external
variable. Thus it is visible only inside the function in which it is defined, but it remains in
existence for the life of the program.

External variable
A large program may be written by a number of persons in different files. A variable
declared global in one file will not be available to a function in another file. Such a
variable, if required by functions in both the files, should be declared global in one file
and at the same time declared external in the second file.

STRUCTURE

A structure is a collection of variable which can be same or different types. You can refer
to a structure as a single variable, and to its parts as members of that variable by using the
dot (.) operator. The power of structures lies in the fact that once defined, the structure
name becomes a user-defined data type and may be used the same way as other built-in
data types, such as int, double, char.

struct STUDENT
{
int rollno, age;
char name[80];
float marks;
};

int main()
{
// declare two variables of the new type

33
STUDENT s1, s3;
//accessing of data members
cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
cout<<s1.rollno<<s1.age<<s1.name<<s1.marks;
//initialization of structure variable
STUDENT s2 = {100,17,”Aniket”,92};
cout<<s2.rollno<<s2.age<<s2.name<<s2.marks;
//structure variable in assignment statement
s3=s2;
cout<<s3.rollno<<s3.age<<s3.name<<s3.marks;
return 0;
}

Defining a structure

When dealing with the students in a school, many variables of different types are needed.
It may be necessary to keep track of name, age, Rollno, and marks point for example.
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
}; STUDENT is called the structure tag, and is your brand new data type, like int, double
or char.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct

34
The most efficient method of dealing with structure variables is to define the structure
globally. This tells "the whole world", namely main and any functions in the program,
that a new data type exists. To declare a structure globally, place it BEFORE void
main(). The structure variables can then be defined locally in main, for example…
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
};

int main()
{
// declare two variables of the new type
STUDENT s1, s3;
………
………
return 0;
}

Alternate method of declaring variables of type struct:


struct STUDENT
{
int rollno, age;
char name[80];
float marks;
} s1, s3;

Accessing of data members

The accessing of data members is done by using the following format:

35
structure variable.member name
for example cin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
Initialization of structure variable

Initialization is done at the time of declaration of a variable. For example STUDENT s2 =


{100,17,”Aniket”,92};

Procedural Paradigm
In procedural programming paradigm, the emphasis is on doing things i.e., the procedure
or the algorithm. The data takes the back seat in procedural programming paradigm.
Also, this paradigm does not model real world well.

Object Oriented programming


The object oriented programming paradigm models the real world well and overcomes
the shortcomings of procedural paradigm. It views a problem in terms of objects and thus
emphasizes on both procedures as well as data.

The following are the basic concepts used in object-oriented programming.

Object-: An object is an identifiable entity with some characteristics and behavior.

Class-: A class represents a group of objects that share common properties, behavior and
relationships.

Data Abstraction-: Abstraction refers to act of representing essential features without


including the background details or explanations.

Encapsulation-: The wrapping up of data and associated functions into a single unit is
known as Encapsulation. Encapsulation implements data abstraction.

36
Modularity-: Modularity is the property of a system that has been decomposed into a set
of cohesive and loosely coupled modules.

Inheritance-: It is the capability of one class of things to inherit capabilities or properties


from another class.

Base and sub classes-: The class whose properties are inherited is called base class (or
superclass) and the class that inherits the properties is known as derived class(or
subclass).

Derived Class :- The class, which inherits from other classes is called derived class or
Subclass.

Polymorphism-: It is the ability for a message or data to be processed in more than one
form. Polymorphism is a property by which the same message can be sent to objects of
several different classes. Polymorphism is implemented in C++ through virtual functions
and overloading- function overloading and operator overloading.

Advantages of Object oriented programming.


Software complexity can be easily managed
Object-oriented systems can be easily upgraded
It is quite easy to partition the work in a project based on object

class enforce data-hiding, abstraction & encapsulation


A class groups its members into three sections : private, protected, and public. The
private and protected members remain hidden from outside world. Thus through private
and protected members, a class enforces data-hiding.

The outside world is given only the essential and necessary information through public
members, rest of the things remain hidden, which is nothing but abstraction. Abstraction

37
means representation of essential features without including the background details and
explanation.

CLASSES & OBJECTS

The mechanism that allows you to combine data and the function in a single unit is called
a class. Once a class is defined, you can declare variables of that type. A class variable is
called object or instance. In other words, a class would be the data type, and an object
would be the variable. Classes are generally declared using the keyword class, with the
following format:

class class_name
{
private:
members1;
protected:
members2;
public:
members3;
};

Where class_name is a valid identifier for the class. The body of the declaration can
contain members, that can be either data or function declarations, The members of a class
are classified into three categories: private, public, and protected. Private, protected, and
public are reserved words and are called member access specifiers. These specifiers
modify the access rights that the members following them acquire.

private members of a class are accessible only from within other members of the same
class. You cannot access it outside of the class.
protected members are accessible from members of their same class and also from
members of their derived classes.

38
Finally, public members are accessible from anywhere where the object is visible.

By default, all members of a class declared with the class keyword have private access
for all its members. Therefore, any member that is declared before one other class
specifier automatically has private access.

Here is a complete example : class student


{
private :
int rollno;
float marks;
public:
void getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void displaydata()
{
cout<<"Roll number : "<<rollno<<"\nMarks : "<<marks;
}
};
Object Declaration

Once a class is defined, you can declare objects of that type. The syntax for declaring a
object is the same as that for declaring any other variable. The following statements
declare two objects of type student: student st1, st2;
Accessing Class Members

39
Once an object of a class is declared, it can access the public members of the class.
st1.getdata();
Defining Member function of class

You can define Functions inside the class as shown in above example. Member functions
defined inside a class this way are created as inline functions by default. It is also
possible to declare a function within a class but define it elsewhere. Functions defined
outside the class are not normally inline.
When we define a function outside the class we cannot reference them (directly) outside
of the class. In order to reference these, we use the scope re operator, ::
(double colon). In this example, we are defining function getdata outside the class:void
student :: getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}

The following program demostrates the general feature of classes. Member function
initdata() is defined inside the class. Member functions getdata() and showdata() defined
outside the class.

class student //specify a class


{
private :
int rollno; //class data members
float marks;
public:
void initdata(int r, int m)
{

40
rollno=r;
marks=m;
}
void getdata(); //member function to get data from user
void showdata();// member function to show data
};

void student :: getdata()


{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}

void student :: showdata()


{
cout<<"Roll number : "<<rollno<<"\nMarks : "<<marks;
}

int main()
{
student st1, st2; //define two objects of class student
st1.initdata(5,78); //call member function to initialize
st1.showdata();
st2.getdata(); //call member function to input data
st2.showdata(); //call member function to display data
return 0;
}

41
CONSTRUCTOR AND DESTRUCTOR
CONSTURCTOR

It is a member function having same name as it’s class and which is used to initialize the
objects of that class type with a legel initial value. Constructor is automatically called
when object is created.
Types of Constructor

Default Constructor-: A constructor that accepts no parameters is known as default


constructor. If no constructor is defined then the compiler supplies a default constructor.

student :: student()
{
rollno=0;
marks=0.0;
}

Parameterized Constructor -: A constructor that receives arguments/parameters, is called


parameterized constructor.

student :: student(int r)
{
rollno=r;
}

Copy Constructor-: A constructor that initializes an object using values of another object
passed to it as parameter, is called copy constructor. It creates the copy of the passed
object.

student :: student(student &t)

42
{
rollno = t.rollno;
}

There can be multiple constructors of the same class, provided they have different
signatures.

DESTRUCTOR

A destructor is a member function having sane name as that of its class preceded by
~(tilde) sign and which is used to destroy the objects that have been created by a
constructor. It gets invoked when an object’s scope is over.

~student() { }

Example : In the following program constructors, destructor and other member functions
are defined inside class definitions. Since we are using multiple constructor in class so
this example also illustrates the concept of constructor overloading

#include<iostream.h>

class student //specify a class


{
private :
int rollno; //class data members
float marks;
public:
student() //default constructor
{
rollno=0;
marks=0.0;

43
}
student(int r, int m) //parameterized constructor
{
rollno=r;
marks=m;
}
student(student &t) //copy constructor
{
rollno=t.rollno;
marks=t.marks;
}
void getdata() //member function to get data from user
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void showdata() // member function to show data
{
cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;
}
~student() //destructor
{}
};

int main()
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked

44
st1.showdata(); //display data members of object st1
st2.showdata(); //display data members of object st2
st3.showdata(); //display data members of object st3
return 0;
}

INHERITANCE

Inheritance: It is the capability of one class to inherit properties from another class.

Base Class: It is the class whose properties are inherited by another class. It is also called
Super Class.

Derived Class: It is the class that inherit properties from base class(es).It is also called
Sub Class.
FORMS OF INHERITANCE

Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
one base class.

Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits
from multiple base class(es)

Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses


inherits from one base class.

Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base


class for other classes.

Hybrid Inheritance:The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.

45
Visibility Mode:It is the keyword that controls the visibility and availability of inherited
base class members in the derived class.It can be either private or protected or public.

Private Inheritance:It is the inheritance facilitated by private visibility mode.In private


inheritance ,the protected and public members of base class become private members of
the derived class.

Public Inheritance:It is the inheritance facilitated by public visibility mode.In public


inheritance ,the protected members of base class become protected members of the
derived class and public members of the base class become public members of derived
class.;

Protected Inheritance: It is the inheritance facilitated by protected visibility mode. In


protected inheritance ,the protected and public members of base class become protected
members of the derived class.
Base Class Visibility Derived class visibility
Public derivation Private derivation Protected derivation
Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected

Containership: When a class contains objects of other class types as its members, it is
called containership. It is also called containment, composition, aggregation.
Execution of base class constructor
Method of inheritace Order of execution
class B : public A { }; A(); base constructor
B(); derived constructor
class A : public B, public C B();base (first)
C();base (second)
A();derived constructor

46
When both derived and base class contains constructors, the base constructor is executed
first and then the constructor in the derived class is executed. In case of multiple
inheritances, the base classes are constructed in the order in which they appear in the
declaration of the derived class.
Overriding of method(function) in inheritance

We may face a problem in multiple inheritance, when a function with the same name
appears in more than one base class. Compiler shows ambiguous error when derived class
inherited by these classes uses this function.

We can solve this problem, by defining a named instance within the derived class, using
the class re operator with the function as below :

class P : public M, public N //multiple inheritance


{
public :
void display() //overrides display() of M and N
{
M::display()
}
};

we can now used the derived class as follows :


void main()
{
P obj;
obj.display();
}

47
BASIC OPERATION ON TEXT FILE IN C++

Program to write in a text file

#include<fstream.h>
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz";
fout<<str;
fout.close();
return 0;
}

Program to read from text file and display it

#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}

Program to count number of characters.

#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
clrscr();
char ch; int count=0;

48
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}

Program to count number of words

#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char word[30]; int count=0;
while(!fin.eof())
{
fin>>word;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}

Program to count number of lines

#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80]; int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<<count;

49
fin.close();
getch();
return 0;
}

Program to copy contents of file to another file.

#include<fstream.h>
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
return 0;
}
QUESTIONS SECTION

QUESTIONS ON Variable, Operator and Expression

Question 1

Write a program to print HELLO WORLD on screen.

Question 2

Write a program to display the following output using a single cout statement.

Subject Marks
Mathematics 90
Computer 77
Chemistry 69

Question 3

50
Write a program which accept two numbers and print their sum.

Question 4

Write a program which accept temperature in Farenheit and print it in centigrade.

Question 5

Write a program which accept principle, rate and time from user and print the
simple interest.

Question 6

Write a program which accepts a character and display its ASCII value.

Question 7

Write a program to swap the values of two variables.

Question 8

Write a program to calculate area of circle.

Question 9

Write a program to check whether the given number is positive or negative (using ?
: ternary operator )

Question 10

Write a program to check whether the given number is even or odd (using ? :
ternary operator )

Question 11

Write a program which accepts days as integer and display total number of years,
months and days in it.
for example : If user input as 856 days the output should be 2 years 4 months 6
days.

51
Question 12

What is the output of following program?

int x = 10;
cout<<x<<x++;

int x = 10;
cout<<++x<<x++<<x;

Question 13

Write a program to calculate the sum of first 10 natural number.

Question 14

Write a program to find the factorial value of any number entered through the
keyboard.

Question 15

Write a program to print following :

i)

**********
**********
**********
**********

ii)

*
**
***
****
*****

iii)

52
*
**
***
****
*****

iv)

1
222
33333
4444444
555555555

Question 16

Write the output of the following program :


#include <iostream.h>
void X(int &A, int &B)
{
A = A + B;
B = A - B;
A=A-B;
}
void main()
{
int a = 4, b =18;
X(a,b);
cout<<a<<”,”<<b;
}

Question 1

Write a C++ program to find the sum and average of one dimensional integer array.

Question 2

Write a C++ program to swap first and last element of an integer 1-d array.

Question 3

53
Write a C++ program to reverse the element of an integer 1-D array.

Question 4

Write a C++ program to find the largest and smallest element of an array.

Question 5

Write a menu driven C++ program with following option


a. Accept elements of an array
b. Display elements of an array
c. Sort the array using insertion sort method
d. Sort the array using selection sort method
e. Sort the array using bubble sort method
Write C++ functions for all options. The functions should have two parameters
name of the array and number of elements in the array.

Question 3

Given a binary file STUDENT.DAT, containing records of the following class


Student type
class Student
{
char S_Admno[lO]; //Admission number of student
char S_Name[30]; //Name of student
int Percentage; //Marks Percentage of student
public:
void EnterData()
{
gets(S_Admno);
gets(S_Name);
cin>>Percentage;
}
void DisplayData()
{
cout<<setw(12)<<S_Admno;
cout<<setw(32)<<S_Name;
cout<<setw(3)<<Percentage<<endl;
}
int ReturnPercentage()

54
{return Percentage;}
};
Write a function in C++, that would read contents of file STUDENT.DAT and
display the details of those Students whose Percentage is above 75.

Question 4

Observe the program segment given below carefully and fill the blanks marked as
Statement 1 and Statement 2 using seekg() and tellg() functions for performing the
required task.

#include <fstream.h>
class Employee
{
int Eno;
char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};

int Item::Countrec()
{
fstream File;
File.open("EMP.DAT",ios::binary|ios::in);
______________________ //Statement 1
int Bytes =______________________ //Statement 2
int Count = Bytes / sizeof(Item);
File.close();
return Count;
}

55

You might also like