C Notes
C Notes
Digits 0-9
Formatting backspace, horizontal tab, vertical tab, form feed, and carriage
characters 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:
1
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
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
2
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++.
Opening and closing braces indicate the start and end of a compound
Braces { }
statement.
5. Operators
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
3
Type Byte Range Description
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
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 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.
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.
4
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
order
long double
double
(highest)
float
To
long
int
(lowest)
char
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';
5
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
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;
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;
6
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, 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
== Equal to
!= Not equal to
Logical operators
The logical operators are used to combine one or more relational expression. The logical
operators are
Operators Meaning
|| OR
&& AND
! NOT
7
Unary operators
C++ provides two unary operators for which only one variable is required.
For Examplea = - 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
Conditional operator
8
The conditional operator ?: is called ternary operator as it requires three operands. The
format of the conditional operator is:
Conditional_ expression ? expression1 : expression2;
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 iWould 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 ()
Second *, /, %
Third +, -
The following table shows the precedence of operators.
*,/, %
+, -
==,!=
&&
?:
9
=
Comma operator
FLOW OF CONTROL
Statements
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
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 statement
syntax of the if - else statement
10
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 (x == 100) if (x == 100)
cout << "x is 100"; cout << "x is 100";
else
cout << "x is not 100";
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" ;
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;
11
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
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.
do-while loop
Syntax of do-while loop
do
{
statements;
} while (condition);
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-
12
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
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 loopfor (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 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;
13
}
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 FUNCTION
C++ provides many built in functions that saves the programming time
Mathematical Functions
Some of the important mathematical functions in header file math.h are
Function Meaning
log(x) logarithm of x
14
abs(x) Absolute value of integer number x
Character Functions
All the character functions require ctype.h header file. The following table lists the function.
Function Meaning
String Functions
The string functions are present in the string.h header file. Some string functions are given
below:
strcmp((S1, S2)==0)
strcmp((S1, S2)>0) It compares S1 and S2 and finds out whether S1 equal
strcmp((S1, S2) <0) to S2, S1 greater than S2 or S1 less than S2.
strcmpi((S1, S2)==0)
strcmpi((S1, S2)>0) It compares S1 and S2 ignoring case and finds out
strcmpi((S1, S2) <0) whether S1 equal to S2, S1 greater than S2 or S1 less
15
than S2.
randomize() It initializes / seeds the random number generator with a random number
16
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.
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 calledactual
parameters. The variable which receive the value from called statement are
termed formal parameters.
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)
{
17
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>
ARRAY
An array is a collection of data elements of same data type. It is described by a single name
and each element of an array is referenced by using array name and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example,int Age[5] ;
float cost[30];
It can be used to take input of a value of It can be used to take input of a string.
any data type.
25
It takes the white space i.e. a blank, a tab, It does not take the white space i.e. a
or a new line character as a string blank, a tab, or a new line character, as a
terminator. string terminator.
Example: Example:
char S[80]; char S[80];
cout<<"Enter a string:”; cout<<"Enter a string:";
cin>>S; gets(S);
cout puts()
It can be used to display the value of any It can be used to display the value of a
data type. string.
It does not take a line feed after displaying It takes a line feed after displaying the
the string. string.
It requires the header file iostream.h It requires the header file stdio.h
Example: Example:
char S[80]="Computers"; char S[80]="Computers";
cout<<S<<S; puts(S);
puts(S);
Output:
ComputersComputers Output:
Computers
Computers
Counting the number of characters in a string and printing it backwards
#include<iostream.h>
#include<stdio.h>
int main( )
{
char str[80];
cout<<"Enter a string:";
gets(str);
for(int l=0; str[l]!='\0';l++); //Loop to find length
cout<<"The length of the string is : "<<l<<endl ;
for(int i=l-1;i>=0;i--) //Loop to display the string backwards
cout<<str[i];
return 0;
}
Function to count the number of words in a string
void count(char S[])
{
int words=0;
for(int i=0;S[i]!='\0';i++)
{
if (S[i]==' ')
words++; //Checking for spaces
26
}
cout<<"The number of words="<<words+1<<endl;
}
Function to find the length of a string
int length(char S[ ])
{
for(int i=0;S[i]!='\0';i++);
return i;
}
Function to copy the contents of string S2 to S1
void copy(char S1[ ], char S2[ ])
{
for(int i=0;S2[i]!='\0';i++)
S1[i]=S2[i];
S1[i]='\0';
}
Function to concatenate the contents of string S2 to S1
void concat(char S1[ ], char S2[ ])
{
for(int l=0;S1[l]!='\0';l++);
for(int i=0;S2[i]!='\0';i++)
S1[l++]=S2[i];
S1[l]='\0';
}
Function to compare strings STR1 to STR2. The function returns a value>0 if
//STR1>STR2, a value<0 if STR1<STR2, and value 0 if STR1=STR2
int compare(char STR1[ ],char STR2[])
{
for(int I=0;STR1[I]==STR2[I] && STR1[I]!='\0'&&STR2[I]!='\0'; I++);
return STR1[I]-STR2[I];
}
To reverse the contents of string S and store it in string Rev
void Reverse(char S[], char Rev[])
{
for(int C1=0; S[C1]!='\0'; C1++);
C1--;
for(int C2=0;C1>=0;C2++,C1--)
Rev[C2]=S[C1];
Rev[C2]='\0';
}
Function to check whether a string S is a palindrome or not
int Palin(char S[])
{
for(int L=0;S[L]!='\0';L++); //To find length
for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++);
return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
}
Function to change the case of string S to uppercase
void Upper(char S[])
{
for(int i=0;S[i]!='\0';i++)
S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
}
Function to change the case of string S to lower case
void Lower(char S[])
{
for(int i=0;S[i]!='\0';i++)
27
S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
}
Function to extract n characters from left side of the string and store it in a
different string. Example: 4 characters from ENVIRONMENT=ENVI
int SLeft(char S[ ], int n, char result[ ])
{
for(int l=0;S[l]!='\0';l++);
if(n<=I) //characters extracted should be <=length
{
for(int i=0;i<n;i++)
result[i]=S[i];
result[i]='\0';
return 1;
}
else
return 0;
}
Function to extract n characters from right side of the string and store it in a
different string. Example: 4 characters from ENVIRONMENT=MENT
int SRight(char S[ ], int n, char result[ ])
{
for(int l=0;S[l]!='\0';l++);
if(n<=I) //characters extracted should be <=length
{
for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
result[j]=S[i];
result[j]='\0';
return 1;
}
else
return 0;
}
Function to extract n characters from specified location loc of the string and store
it in a different string. Example: 4 characters from third location in string
ENVIRONMENT= VIRO
int substring(char S[ ], int n, int loc, char result[ ])
{
for(int l=0;S[l]!='\0';l++);
if(n<=I) //characters extracted should be <=length
{
for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
result[j]=S[i];
result[j]='\0';
return 1;
}
else
return 0;
}
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.
28
struct STUDENT
{
int rollno, age;
char name[80];
float marks;
};
int main()
{
// declare two variables of the new type
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.
int main()
{
// declare two variables of the new type
STUDENT s1, s3;
………
………
return 0;
}
29
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:
structure variable.member name
for examplecin>>s1.rollno>>s1.age>>s1.name>>s1.marks;
Initialization of structure variable
Initialization is done at the time of declaration of a variable. For exampleSTUDENT s2 =
{100,17,”Aniket”,92};
Structure variable in assignment statement
s3=s2;The statement assigns the value of each member of s2 to the corresponding member
of s3. Note that one structure variable can be assigned to another only when they are of the
same structure type, otherwise complier will give an error.
Nested structure (Structure within structure)
It is possible to use a structure to define another structure. This is called nesting of
structure. Consider the following program
struct DAY
{
int month, date, year;
};
struct STUDENT
{
int rollno, age;
char name[80];
day date_of_birth;
float marks;
};
typedef
It is used to define new data type for an existing data type. It provides and alternative name
for standard data type. It is used for self documenting the code by allowing descriptive name
for the standard data type.
OOP CONCEPTS
30
Paradigm-: It means organizing principle of a program. It is an approach to programming.
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.
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
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;
};
31
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.
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
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 resolution 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 funcitons getdata() and showdata() defined
outside the class.
class student //specify a class
{
32
private :
int rollno; //class data members
float marks;
public:
void initdata(int r, int m)
{
rollno=r;
marks=m;
}
void getdata(); //member function to get data from user
void showdata();// member function to show data
};
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;
}
student :: student(int r)
{
rollno=r;
}
33
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() { }
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>
int main()
34
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked
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.
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.;
35
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.
Derived class visibility
Base Class
Visibility Public Private Protected
derivation derivation derivation
Private
Not inherited Not inherited Not inherited
Protected
Protected Private Protected
Public
Public Private Protected
B();base (first)
class A : public B, public C C();base (second)
A();derived constructor
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 resolution 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();
}
Virtual Base Class
Multipath inheritance may lead to duplication of inherited members from a grandparent
base class. This may be avoided by making the common base class a virtual base class.
When a class is made a virtual base class, C++ takes necessary care to see that only one
copy of that class is inherited.
36
class A
{
....
....
};
class B1 : virtual public A
{
....
....
};
class B2 : virtual public A
{
....
....
};
class C : public B1, public B2
{
.... // only one copy of A
.... // will be inherited
};
ifstream ifile;
ifile.open(“data2”);
File mode parameter Meaning
37
ios::binary file open in binary mode
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
CLOSING FILE
fout.close();
fin.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function
get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION RETURN VALUE AND MEANING
38
good() returns true if no error has occurred.
These internal stream pointers that point to the reading or writing locations within a stream
can be manipulated using the following member functions:
39
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;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}
POINTER
C++ Memory Map
Once a program is compiled, C++ creates four logically distinct regions of memory:
Code Area : Area to hold the compiled program code
Data Area : Area to hold global variables
Stack Area : Area to hold the return address of function calls, argument passed to the
functions, local variables for functions and the current state of the CPU.
Heap : Area from which the memory is dynamically allocated to the program.
Accessing address of a variable
Computer’s memory is organized as a linear collection of bytes. Every byte in the
computer’s memory has an address. Each variable in program is stored at a unique address.
We can use address operator & to get address of a variable:
int num = 23;
cout << # // prints address in hexadecimal
POINTER
A pointer is a variable that holds a memory address, usually the location of another variable
in memory.
Defining a Pointer Variable
int *iptr;
iptr can hold the address of an int
Pointer Variables Assignment:
int num = 25;
int *iptr;
iptr = #
Memory layout
43
- Integers can be added to or subtracted from
pointers using the operators +, -, +=, and -=
Each time a pointer is incremented by 1, it points to the memory location of the next
element of its base type.
If “p” is a character pointer then “p++” will increment “p” by 1 byte.
If “p” were an integer pointer its value on “p++” would be incremented by 2 bytes.
Pointers and Arrays
Array name is base address of array
int vals[] = {4, 7, 11};
cout << vals; // displays 0x4a00
cout << vals[0]; // displays 4
Lets takes an example:
int arr[]={4,7,11};
int *ptr = arr;
What is ptr + 1?
It means (address in ptr) + (1 * size of an int)
cout << *(ptr+1); // displays 7
cout << *(ptr+2); // displays 11
Array Access
Array notation arr[i] is equivalent to the pointer notation *(arr + i)
Assume the variable definitions
int arr[]={4,7,11};
int *ptr = arr;
Examples of use of ++ and --
ptr++; // points at 7
ptr--; // now points at 4
Character Pointers and Strings
Initialize to a character string.
char* a = “Hello”;
a is pointer to the memory location where ‘H’ is stored. Here “a” can be viewed as a
character array of size 6, the only difference being that a can be reassigned another
memory location.
char* a = “Hello”;
a gives address of ‘H’
*a gives ‘H’
a[0] gives ‘H’
a++ gives address of ‘e’
*a++ gives ‘e’
Pointers as Function Parameters
A pointer can be a parameter. It works like a reference parameter to allow change to
argument from within function
Pointers as Function Parameters
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
swap(&num1, &num2);
Pointers to Constants and Constant Pointers
Pointer to a constant: cannot change the value that is pointed at
Constant pointer: address in pointer cannot change once pointer is initialized
Pointers to Structures
We can create pointers to structure variables
struct Student {int rollno; float fees;};
Student stu1;
Student *stuPtr = &stu1;
44
(*stuPtr).rollno= 104;
-or-
Use the form ptr->member:
stuPtr->rollno = 104;
Static allocation of memory
In the static memory allocation, the amount of memory to be allocated is predicted and
preknown. This memory is allocated during the compilation itself. All the declared variables
declared normally, are allocated memory statically.
Dynamic allocation of memory
In the dynamic memory allocation, the amount of memory to be allocated is not known. This
memory is allocated during run-time as and when required. The memory is dynamically
allocated using new operator.
Free store
Free store is a pool of unallocated heap memory given to a program that is used by the
program for dynamic allocation during execution.
Dynamic Memory Allocation
We can allocate storage for a variable while program is running by using new operator
To allocate memory of type integer
int *iptr=new int;
To allocate array
double *dptr = new double[25];
To allocate dynamic structure variables or objects
Student sptr = new Student; //Student is tag name of structure
Releasing Dynamic Memory
Use delete to free dynamic memory
delete iptr;
To free dynamic array memory
delete [] dptr;
To free dynamic structure
delete Student;
Memory Leak
If the objects, that are allocated memory dynamically, are not deleted using delete, the
memory block remains occupied even at the end of the program. Such memory blocks are
known as orphaned memory blocks. These orphaned memory blocks when increase in
number, bring adverse effect on the system. This situation is called memory leak
Self Referential Structure
The self referential structures are structures that include an element that is a pointer to
another structure of the same type.
struct node
{
int data;
node* next;
}
STATIC STACK
#include<iostream.h>
#include<conio.h>
#define size 4
class stack
{
int data[size];
int top;
public:
stack()
{
top=-1;
}
45
void push();
void pop();
void display();
};
void stack::push()
{
if(top==size-1)
{
cout<<"\nStack is full";
return;
}
else
{
top++;
cout<<"Enter Data : ";
cin>>data[top];
}
}
void stack::pop()
{
if(top==-1)
cout<<"\n Stack is empty";
else
{
cout<<data[top]<<"deleted "<<endl;
top--;
}
}
void stack::display()
{
int t=top;
while(t>=0)
{
cout<<data[t]<<endl;
t--;
}
}
void main()
{
stack st;
int ch;
do
{
cout<<"\n1. Push\n2. Pop\n3. Display \n4.Quit\nEnter Choice(1-4) ";
cin>>ch;
switch(ch)
{
case 1: st.push();break;
case 2: st.pop();break;
case 3: st.display();
}
}while(ch!=4);
}
46
#include<iostream.h>
#include<conio.h>
#define size 4
class cqueue
{
int data[size];
int front,rear;
public:
cqueue()
{
front=-1;rear=-1;
}
void insert();
void remove();
};
void cqueue::insert()
{
if(rear==size-1&&front==0 || front==rear+1)
{
cout<<"\nCircular queue is full";
return;
}
else if(rear==-1)
{
rear++;
front++;
}
else if(rear==size-1)
rear=0;
else
rear++;
cout<<"Enter Data : ";
cin>>data[rear];
}
void cqueue::remove()
{
if(front==-1)
{
cout<<"\n Circular Queue is empty";return;
}
cout<<data[front]<<" deleted"<<endl;
if(front==rear)
{
front=-1;rear=-1;
}
else if(front==size-1)
front=0;
else
front++;
}
void main()
{
cqueue cq;
int ch;
do
{
47
cout<<"\n1. Insert\n2. Remove\n3. Quit\nEnter Choice(1-3) ";
cin>>ch;
switch(ch)
{
case 1: cq.insert();break;
case 2: cq.remove();break;
}
}while(ch!=3);
}
DYNAMIC STACK
Stack is a linear data structure in which insertion and deletion of elements takes place only
one end known as TOP.
#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node *next;
};
class stack
{
node *top;
public :
stack()
{ top=NULL;}
void push();
void pop();
void display();
~stack();
};
void stack::push()
{
node *temp;
temp=new node;
cout<<"Enter data :";
cin>>temp->data;
temp->next=top;
top=temp;
}
void stack::pop()
{
if(top!=NULL)
{
node *temp=top;
top=top->next;
cout<<temp->data<<"deleted";
delete temp;
}
else
cout<<"Stack empty";
}
void stack::display()
{
node *temp=top;
while(temp!=NULL)
48
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
stack::~stack()
{
while(top!=NULL)
{
node *temp=top;
top=top->next;
delete temp;
}
}
void main()
{
stack st;
char ch;
do
{
cout<<"stack options\nP for push \nO for Pop \nD for Display \nQ for quit";
cin>>ch;
switch(ch)
{
case 'P': st.push();break;
case 'O': st.pop();break;
case 'D': st.display();break;
}
}while(ch!='Q');
}
49