C++ Notes
C++ Notes
Tokens
A token is the smallest element of a C++ program that is meaningful to the compiler. It act as
building blocks of a program.
The following tokens are available in C++
Keywords
Identifiers
Constants
Operators
Keywords:
Keywords are reserved words which have fixed meaning, and its meaning cannot be changed.
The meaning and working of these keywords are already known to the compiler. These reserved
keywords cannot be used as identifiers in a program.
All keywords are written in lower case.
The reserved words of C++ may be conveniently placed into several groups. In the first group we
put those that were also present in the C programming language and have been carried over into
C++. and here they are:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
While in C++ there are some additional keywords other than C Keywords they are:
Identifiers:
C++ allows the programmer to assign names of his own choice to variables, arrays, functions,
structures, classes, objects called identifiers.
The identifier is a sequence of characters taken from C++ character set.These are the
fundamental requirement of any language.
Constants:
Constants (often referred to as Literals) are data items that never change their value during the
execution of the program.
Type of Constants:
The following types of constants are available in C++.
Integer Constants
Character Constants
Floating Point 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 . 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. For
example 0x4a
Character Constants:
A character constant in C++ must contain 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 etc. These characters can be represented by using an escape
sequence. An escape sequence represents a single character.For example '\b' for backspace that
cursor moves towards left by one position.
String Constants
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.
;
Operators:
Operators are special symbols used for specific purposes. C++ provides many operators for
manipulating mathematical or logical data.
Types of Operators:
The following types of operators are available in C++.
Arithmetic Operators
Relational Operators
Logical Operators
Increment and Decrement Operators
Assignment Operators
Bitwise Operators
Misc Operators
Arithmetic Operators: Arithmetical operators are used to performs an arithmetic (numeric)
operation.The following table shows the arithmetic operators
Operators Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Relational Operators: The relational operators are used to test the relation between two values.
These operator returns zero when the relation is false and a non-zero
when it is true. The following table shows the relational operators
Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to
Logical Operators: The logical operators are used to combine one or more relational expression
The following table shows the logical operators
Operators Meaning
|| Logical AND. Performs logical conjunction of two expressions.(if
both expressions evaluate to True, result is True. If either
expression evaluates to False, the result is False)
&& Logical OR. Performs a logical disjunction on two expressions.(if
either or both expressions evaluate to True, the result is True)
! Logical NOT. Performs logical negation on an expression.
Increment and Decrement Operators:
C++ provides two special operators '++' (Increment)and '--'(Decrement) 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
For Example:
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
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.
C++ also support compound assignment operators. The following table shows the
compound assignment operators
Bitwise Operators:
The bitwise operators are those are used to perform bit level operations . The
following table shows the relational operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left Shift
>> Right Shift
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;
If the value of conditional expression is true then the expression1 is evaluated,
otherwise expression2 is evaluated.
For example
int a = 5, b = 6;
big = (a > b) ? a : b;
The condition evaluates to false, therefore big gets the value from b and it
becomes 6.
Special Operator:
Special operators are those operators which have special purpose.They are as
follows-
Operator Description
Scope Resolution Operator (::) It is used to identify and disambiguate identifiers used in
different scopes.
Casting Operator ( () ) It is used for type conversion.
Address of Operator ( & ) It returns the address of a memory location.
sizeof() Operator It returns the size of a memory location.
Comma ( , ) Operator It allows grouping two statements where one is expected.
Indirection Operator or Value of It defines pointer to a variable.
Operator ( * )
new It is used to allocate the memory space dynamically
followed by a data type specifier.
delete It deallocates the memory previously allocated by the new
operator.
Basic Structure of C++ Program:
Declaration section includes different library functions and header files. All preprocessor
directives are written in this section.
Global declaration includes structure, class, variable. All global variables are declared here.
Main() function is an entry point for all the function. Every C++ program starts with main()
function.
Example :
/* First C++ Program /*...*/ comments are used for the documentation to understand the code to others. These comments
are ignored by the compiler.
*/
#include<iostream.h> It is a preprocessor directive. It contains the contents of iostream header file in the program before
compilation. This header file is required for input output statements.
int/void Integer (int) returns a value. In the above program it returns value 0. Void does not return a value so
there is no need to write return keyword.
main() It is an entry point of all the function where program execution begins.
cout The C++ cout statement is the instance of the ostream class. It is used to produce output on the
standard output device which is usually the display screen
"Welcome" The words in inverted commas are called a String. Each letter is called a character and series of
characters that is grouped together is called a String.
String always be put between inverted commas.
<< It is the insertion stream operator. This operator sends the content of variables on its right to the
object on its left.
In the above program, right operand is the string "Welcome" and left operand is cout object. So it
sends the string to the cout object and then cout object displays the string as a output on the screen.
Unit-2
Control Structures in C++
Control structures determine the order in which the statements are executed.There are various
control structure in C++ as follows-
Decision Making Structure
Looping Structure
1. If Statement:
If statement is the simplest way to modify the control flow of program.
It is a conditional branching statement.
This statement consists of a expression followed by one or more statements.
Syntax:
if (condition)
{
Statement 1;
Statement 2;
.
.
.
}
#include <iostream.h>
int main()
{
int num1=10, num2=20;
if(num1 < num2)
{
cout<<"Num2 is greater";
}
return 0;
}
Output:
Num2 is greater
2. If . . . Else Statement
It is a two-way decision making statement.
When the expression becomes false then else block will be executed.
It is used to make decisions and execute statements conditionally.
Syntax:
if(Condition)
{
Statements;
}
else
{
Statements;
}
#include <iostream.h>
int main()
{
int num1=10, num2=20;
if(num1 > num2)
{
cout<<"Num2 is greater";
}
else
cout<<"Num1 is smaller";
return 0;
}
Output:
Num1 is smaller
#include <iostream.h>
int main()
{
int num1=20, num2=10;
if(num1 > num2)
{
cout<<"Num2 is greater";
}
else if (num1 < num2)
{
cout<<"Num1 is smaller";
}
else
{
cout<<"Num1 and Num2 are equal";
}
return 0;
}
Output:
Num2 is greater
4. Switch Statement
Switch statement is used to perform different actions on different conditions.
This statement compares the same expression to several different values.
Following are the rules for Switch statement:
Syntax
switch (Expression)
{
case condition1:
//Statements;
break;
case condition2:
//Statements;
break;
case condition3:
//Statements;
break;
.
.
case condition n;
//Statements;
break;
default:
//Statement;
}
#include <iostream.h>
int main()
{
char color='O';
switch(color)
{
case 'R': cout<<"Red"<<endl;
break;
case 'G': cout<<"Green"<<endl;
break;
case 'B': cout<<"Blue"<<endl;
break;
case 'O': cout<<"Orange"<<endl;
break;
case 'P': cout<<"Pink"<<endl;
break;
case 'W': cout<<"White"<<endl;
break;
case 'Y' : cout<<"Yellow"<<endl;
break;
default: cout<<"Inavlid Color"<<endl;
}
return 0;
}
Output:
Orange
Looping Structure
Looping structure allows to execute a statement or group of statements multiple
times.It provides the following types of loops to handle the looping requirements:
While Loop
For Loop
Do . . . While Loop
1. While Loop
While loop allows to repeatedly run the same block of code, until a given condition
becomes true.
It is called an entry-controlled loop statement and used for repetitive execution of the
statements.
The loop iterates while the condition is true. If the condition becomes false, the program
control passes to the next line of the code.
Syntax:
while (Condition)
{
//Statements;
}
Output:
Fibonacci Series:
1
2
3
5
8
13
2. For Loop
For loop is a compact form of looping.
It is used to execute some statements repetitively for a fixed number of times.
It is also called as entry-controlled loop.
It is similar to while loop with only difference that it continues to process block of code
until a given condition becomes false and it is defined in a single line.
It includes three important parts:
1. Loop Initialization
2. Test Condition
3. Iteration
All the above parts come in a single line separated by semicolon (;).
#include <iostream.h>
int main()
{
int i = 1, j = 5;
for(i=1; i<=j; i++)
{
cout<<"For Loop Execution"<<i<<endl;
}
return 0;
}
Output:
For Loop Execution:1
For Loop Execution:2
For Loop Execution:3
For Loop Execution:4
For Loop Execution:5
3. Do . . . While Loop
Do . . . While loop is executed at least once, even if the condition is false.
It is called as an exit-controlled loop statement.
This loop does not test the condition before going into the loop. The condition will be
checked after the execution of the body that means at the time of exit.
It is guaranteed to execute the program at least one time.
Flow Diagram of Do . . . While Loop
Syntax:
do
{
//Statements;
}
while(Condition);
In Do-while loop, while condition should always have a semi-colon at the end.
#include <iostream>
using namespace std;
int main()
{
int num=0;
do
{
cout<<“Do While Loop Execution:”<<num<<endl;
num++;
}
while(num<=5);
return 0;
}
Output:
Do While Loop Execution:0
Do While Loop Execution:1
Do While Loop Execution:2
Do While Loop Execution:3
Do While Loop Execution:4
Do While Loop Execution:5
Unit-2
Data Types
Data types are used to define the variables that the same of type data it can store in memory. The
data types determine the type of data to be stored in memory. The data types are used to
represent the different values to be stored in the variable. The variable is a name that refers the
memory location which means whenever you create a variable you reserve the space in the
memory and based on the data type of the variable the operating system allocates the memory.
1. Integer (int)
Integer data types are used to sore integer value. Integer data type holds 2
bytes of memory space and range from 2147483648 to 2147483647.
Syntax:
int variable = value;
2. Character (char)
Character data types are used to store character values. Character types
hold 1 byte of memory space and range from 128 to 127 or 0 to 255.
Syntax:
char variable = 'val';
3. Float (float)
Float data types are used to store single-precision data values i.e. decimal
values. It holds 4 bytes of memory space.
Syntax:
float variable = val;
4. Double (double)
Double data types are used to store double-precision floating-point data
values. It holds 8 bytes of memory space.
Syntax:
double variable = val;
5. Boolean
Boolean types store and represent logical values. They represent the result
in the form of True or False.
6. Void
Void types represent entities without any value. They are used as a data
type for functions that do not return any value.
2. Function
Functions are a block of statements that particularly perform a set of tasks
under it. They make the code more efficient and readable.
Syntax:
Data_type function_Name(Arguments)
3. Pointers
Pointer types represent the address of the data members. They hold the
address of another data member to which they point.
Syntax:
data_type *variable;
4. Reference
A reference is an alternative name for an object.It provides an alias for a
previously defined variable.
1. Structure
2. Union
3. Enumeration
4. Class
1. Structure
Structure type, groups elements of different data types under a custom data
type (structure) and is represented by a single structure name.
Syntax:
struct Structure_Name
{
Datatype data_member1;
Datatype data_member2;
.
.
Datatype data_memberN;
};
Example:
struct Student_info
{
char name[100];
char address[100];
char division[50];
int roll_num;
};
2. Union
Union types serve the same functionality as that of the Structures.
The only difference is that in Unions, all the data members share the same space
of memory which is equivalent to the size of the largest variable, during the
execution of the program.
Syntax:
Union Union_Name
{
Datatype data_member1;
Datatype data_member2;
.
.
Datatype data_memberN;
};
Example:
union Student_info
{
char name[100];
char address[100];
char division[50];
int roll_num;
};
In the above piece of code, name and address are largest among all the data
members declared because we specified their size to 100.
So, the compiler will allocate the size of the largest variable i.e. name or address,
to the memory storage to accommodate them and all the variables will share the
same memory space (100) and address.
3. Enumeration
Enumeration types help increase the readability of the code. It assigns names to
the integers from the program.
These types are indexed from zero resembling the indexing fashion of arrays.
Syntax:
enum enumeration_type_name{value1, value2,..valueN};
Example:
#include <iostream.h>
enum Days { Mon,
Tue,
Wed,
};
int main()
{
return 0;
}
Output:
0 12
4.Class
Class represents a group of similar object.
Syntax:
Class Class_name
{
private:
variable declarations
function() declarations;
public:
variable declarations;
function() declarations;
};
Example:
Class emp
{
private:
int eno;
char name[20];
public:
void get();
void put();
};