[go: up one dir, main page]

0% found this document useful (0 votes)
34 views16 pages

C++ II Sem 2020-21 Part-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views16 pages

C++ II Sem 2020-21 Part-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Introduction of C++

1. C++ is an object-oriented programming language. It was developed by Bjarne


Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the
early 1980’s.
2. Stroustrup wanted to combine the best of both the languages and create a more
powerful language that could support object-oriented programming features and
still retain the power and elegance of C. The result was C++.
3. Therefore, C++ is an extension of C with a major addition of the class construct
feature of Simula67. Since the class was a major addition to the original C
language, initially called the new language ‘C with classes’.
4. However, later in 1983, the name was changed to C++
5. C+ + is a superset of C. Almost all c programs are also C++ programs, however,
there are a few minor differences that will prevent a c program to run under C++
compiler.
6. The most important facilities that C++ adds on to C are classes, inheritance,
function overloading and operator overloading.
7. These features enable creating of abstract data types, inherit properties from
existing data types and support polymorphism, thereby making C++ a truly
object-oriented language.

Application of OOP:

The most popular application of object-oriented programming, up to now, has


been in the area of user interface design such as window. Hundreds of windowing
systems have been developed, using the OOP techniques.

The major applications of OOP’s are as follows:

• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI(Artificial Intelligence) and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems.
C++ Data Types

All variables use data-type during declaration therefore, we can say that
“data types are used to tell variables the type of data it can store”.

• Whenever a variable is defined in C++, the compiler allocates some


memory for that variable based on the data-type with which it is declared.
• Every data type requires different amount of memory.

The Data types in C++ are mainly divided into two types:

1. Primitive Data Types: These data types are built-in or predefined data types
and can be used directly by the user to declare variables. example: int, char ,
float, bool etc. Primitive data types available in C++ are:
o Integer
o Character
o Boolean
o Floating Point
o Double Floating Point
2. Abstract or user defined data type: These data types are defined by user itself.
Like, defining a class in C++ or a structure.

• Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space
and ranges from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data
type is bool.
• Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data type
is float. Float variables typically requires 4 byte of memory space.
• Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for
double floating point data type is double. Double variables typically requires 8
byte of memory space.
Data type Modifiers: As the name implies, data type modifiers are used with the built-
in data types to modify the length of data that a particular data type can hold. Data type
modifiers available in C++ are:

• Signed
• Unsigned
• Short
• Long

Based on the type of modifiers the size and range of the primitive/ primary data type is
may vary. The following table shows the data type and their respective size and range.

Data Type Size (in bytes) Range


short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to +2,147,483,647
long int 4 -2,147,483,648 to +2,147,483,647
unsigned long int 4 0 to 4,294,967,295
signed char 1 -128 to +127
unsigned char 1 0 to 255
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308 to 1.7e+308
long double 10 3.4e – 4932 to 3.4e +4932

C++ Tokens:
“Each individual word and punctuation is referred to as a token in C++. Tokens
are the smallest building block or smallest unit of a C++ program”.
These following tokens are available in C++:

1. Identifiers: “Identifiers are names given to different entries such as variables,


structures, classes, objects and functions”.

While using Identifiers we follow some rule as below.

a. Key words not use as Identifier.


b. Identifier name must be unique with no spaces and start with alphabet
c. The identifier may contain upper or lower case letters.
2. Keywords: key words are the reserved words for specific meaning and they
come from c++ programming. C++ provides some key words as below table.
unsigne
asm else new this const friend short
d
auto enum operator throw const_cast goto signed using
explici
bool private true continue if sizeof virtual
t
brea
export protected try default inline static void
k
static_cas
case extern public typedef delete int volatile
t
catch false register typeid do long struct wchar_t
reinterpret_cas typenam
char float double mutable switch while
t e
dynamic_cas namespac
class for return union template
t e

3. Constants: Constants are the fixed values that do not change their values thought
the c++ program execution. Constants may be like in the form of Numeric or
Character or Symbolic type.
4. Operators: An operator is a symbol that is used to perform a task. C++ has the
some operators like, arithmetic(+,-,*,/,%), logical(&&,||,!),
relational(<,>,<=,>=,==) operators etc.
5. Strings: A string is a sequence of character, which is also used as c++ token.

Input and Output operations:


C++ provides two operations to for input and output purpose they are explained
below:
cout<< :- This is a standard object of iostream class in C++, this is used as a output
operation in c++, here cout is pronounced (called) as c out and the symbol << is called
put to operator or insertion operator.

The general syntax of cout is as follows:

Syntax: cout<<”text string”; Ex:- cout<<” Enter calculation”;

(or)
cout<<variable; Ex: cout<<area;
(Or)
cout<<” the string”<< variable; Ex:- cout<<” area of square is: “<<area;

cin>> :- This is a standard object of iostream class in C++, this is used as a input
operation in c++, here cin is pronounced (called) as c in and the symbol >> is called
extraction or get from operator.

The general syntax of cin is as follows:


Syntax: cin>>variable Ex:- cin>>side;
(or)
cin>>variable1>>variable2; Ex: cin>>area>>side;

Operators in C++:

Types of operators

1. Assignment Operator
2. Arithmetic or Mathematical Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Shift Operators
7. Unary Operators
8. Ternary Operator
9. Comma Operator

Assignment Operator ( = )

Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy
it into the left-hand side (called lvalue). Assignment operator is the only operator which
can be overloaded but cannot be inherited.
Mathematical Operators

There are operators used to perform basic mathematical operations. Addition (+) ,
subtraction (-) , diversion (/) multiplication (*) and modulus (%) are the basic
mathematical operators. Modulus operator cannot be used with floating-point numbers.
Relational Operators

These operators establish a relationship between operands. The relational operators


are : less than (<) , grater thatn (>) , less than or equal to (<=), greater than equal to
(>=), equivalent (==) and not equivalent (!=).

You must notice that assignment operator is (=) and there is a relational operator, for
equivalent (==). These two are different from each other, the assignment operator
assigns the value to any variable, whereas equivalent operator is used to compare
values
Logical Operators

The logical operators are AND (&&) and OR (||). They are used to combine two
different expressions together.

These operators are mostly used in loops (especially while loop) and in Decision
making.
Bitwise Operators

There are used to change individual bits into a number. They work with only integral
data types like int and long and not with floating point values.

• Bitwise AND operators : &


• Bitwise OR operator: |
• And bitwise XOR operator: ^
• And, bitwise NOT operator: ~

Shift Operators

Shift Operators are used to shift Bits of any variable. It is of three types,

1. Left Shift Operator <<


2. Right Shift Operator >>
3. Unsigned Right Shift Operator >>>

Unary Operators

These are the operators which work on only one operand. There are many unary
operators, but increment ++and decrement -- operators are most used.

Other Unary Operators : address of &, dereference *, new and delete, bitwise not ~,
logical not !, unary minus - and unary plus +.
Ternary Operator

The ternary if-else ? : is an operator which has three operands.


Comma Operator(,):

This is used to separate variable names and to separate expressions. In case of


expressions, the value of last expression is produced and used.

Decision making in C++


Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met.
C++ handles decision-making by supporting the following statements,

• if statement
• switch statement
• conditional operator statement
• goto statement

Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested. The different forms of if statement is,

1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement

Simple if statement

The general form of a simple if statement is,


if( expression )
{
statement-inside;
}
statement-outside;

If the expression is true, then 'statement-inside' it will be executed, otherwise


'statement-inside' is skipped and only 'statement-outside' is executed.
Example : #include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
Output :
x is greater than y

if...else statement

The general form of a simple if...else statement is,


if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is
skipped and 'statement-block2' is executed.
Example :
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}
}
Output :
y is greater than x
Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to
perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is
executed otherwise 'statement-block2' is executed.
Example :
void main( )
{
int a,b,c;
clrscr();
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}
else
{
printf("c is greatest");
}
}
getch();
}

else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as the true
condition is found, the statement associated with it is executed.
Example :
void main( )

{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
getch();
}

Looping in C++
In any programming language, loops are used to execute a set of statements repeatedly
until a particular condition is satisfied.
How it works

A sequence of statement is executed until a specified condition is true. This sequence of


statement to be executed is kept inside the curly braces { } known as loop body. After
every execution of loop body, condition is checked, and if it is found to be true the loop
body is executed again. When condition check comes out to be false, the loop body will
not be executed.
There are 3 type of loops in C++ language

1. while loop
2. for loop
3. do-while loop

while loop

while loop can be address as an entry control loop. It is completed in 3 steps.

• Variable initialization.( e.g int x=0; )


• condition( e.g while( x<=10) )
• Variable increment or decrement ( x++ or x-- or x=x+2 )

Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

for loop
for loop is used to execute a set of statement repeatedly until a particular condition is
satisfied. we can say it an open ended loop. General format is,
for(initialization; condition ; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after
condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. for loop can have only
one condition.
Nested for loop

We can also have nested for loop, i.e one for loop inside another for loop. Basic syntax
is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
do while loop

In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do statement
evaluates the body of the loop first and at the end, the condition is checked
using while statement. General format of do-while loop is,
do
{
....Body of the loop
.....
} while(condition);

Jumping out of loop


Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to
leave the loop as soon as certain condition becocmes true, that is jump out of loop. C
language allows jumping from one statement to another within a loop as well as
jumping out of the loop.
1) break statement

When break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
2) continue statement

It causes the control to go directly to the test-condition and then continue the loop
process. On encountering continue, cursor leave the current cycle of loop, and starts
with the next cycle.

C++ Function

C++ functions are basic building blocks in a program. All C++ programs are written
using functions to improve re-usability, understandability and to keep track on them.

1. What is C++ function?

“A C++ Function is a self contained block that is used to complete a task. A large C++
program is divided into basic building blocks called C++ function. C++ function contains
set of instructions enclosed by “{ }” which performs specific operation in a C++
program.

2. Uses of C++ functions:

• C++ functions are used to re-usability.


• Functions are used to divide the large program into meaningful sub programs
(modules).
• We can call same function repeatedly based on use.
• A large C++ program can easily be tracked when it is divided into functions.
• The core concept of C++ functions are, re-usability, dividing blocks achieve the
functionality and to improve understandability of very large C programs.

There are 3 steps used in each C++ function. They are,

1. Function declaration: This informs compiler about the function name, function
parameters and return value’s data type.
2. Function calling: It is nothing accessing the functionality of a function.

3. Function definition: Defining the functionality of the function is called function


definition. This contains lines of code to complete task.

C functions aspects Syntax: Example:


Return_type function_name (arguments list) void calculate(int a, int b)
{ {
function definition
Body of function; body of the function;
} }
function calling function_name (arguments list); calculate(int a, int b);
void calculate(int a, int b);
function declaration return_type function_name (argument list);

4. How to call C functions in a program?

There are two ways that a C function can be called from a program. They are,

1. Call by value
2. Call by reference

1. Call by value:

• In call by value method, the value of the variable is passed to the function as
parameter.
• The value of the actual parameter cannot be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because,
value of actual parameter is copied to formal parameter.

Note:

• Actual parameter – This is the argument which is used in function call.


• Formal parameter – This is the argument which is used in function definition

Example program for C function (using call by value):

#include<iostream.h>
#include<conio.h>
void swap(int a, int b);
void main()
{
int m = 22, n = 44;
cout<<" values before swap”<< m<<n;
swap(m, n);
getch();
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
cout<<”values after swap <<a<<b;

Output:
values before swap 22 44
values after swap 44 22

2. Call by reference:

• In call by reference method, the address of the variable is passed to the function
as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address
is used by both parameters.

Example program for C function (using call by reference):

• In this program, the address of the variables “m” and “n” are passed to the
function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.

#include<iostream.h>
#include<conio.h>
void swap(int *a, int *b);
void main()
{
int m = 22, n = 44;
cout<<" values before swap”<< m<<n;
swap(&m, &n);
getch();
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
cout<<”values after swap <<a<<b;
}

Output:

values before swap 22 44


values after swap 44 22

You might also like