0% found this document useful (0 votes)
29 views49 pages

C++ Controls, Ptrs

This document provides an overview of controls, pointers, and functions in C++. It discusses input/output streams in C++, common header files used for input/output like iostream and iomanip, and the standard output stream cout and standard input stream cin. It also covers basic and derived data types in C++, including integer, floating point, character, and boolean types. Finally, it defines functions as blocks of code that perform specific tasks, and describes library functions and user-defined functions in C++.

Uploaded by

bhushanjawale444
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)
29 views49 pages

C++ Controls, Ptrs

This document provides an overview of controls, pointers, and functions in C++. It discusses input/output streams in C++, common header files used for input/output like iostream and iomanip, and the standard output stream cout and standard input stream cin. It also covers basic and derived data types in C++, including integer, floating point, character, and boolean types. Finally, it defines functions as blocks of code that perform specific tasks, and describes library functions and user-defined functions in C++.

Uploaded by

bhushanjawale444
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/ 49

UNIT – 2

C++ CONTROLS, POINTERS & FUNCTIONS


 C++ Basic Input/Output
In C++ input and output are performed in the form of a sequence of bytes or
more commonly known as streams.
 Input Stream: If the direction of flow of bytes is from the device(for
example, Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.

 Header files available in C++ for Input/Output operations are:


 iostream:iostream stands for standard input-output stream. This header file
contains definitions of objects like cin, cout, cerr, etc.
 iomanip: iomanip stands for input-output manipulators. The methods
declared in these files are used for manipulating streams. This file contains
definitions of setw, setprecision, etc.
1) setw (val): It is used to set the field width in output operations.
2) setfill (c): It is used to fill the character „c‟ on output stream.
3) setprecision (val): It sets val as the new value for the precision of
floating-point values.
Example
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
const longdouble pi = 3.141592653589793239
cout<<"setprecision(10)"<<setprecision(10)<<pi<<endl;

cout<<setfill('*')<<setw(10);
cout<<15<<endl;

cout<<setfill('#')<<setw(5);
cout<<5<<endl;
getch();
}

Prof. Paurnima N. Patil. Page 1


 fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written
into the file as output.

1) The Standard Output Stream (cout)


The predefined object cout is an instance of ostream class. The cout object is said
to be "connected to" the standard output device, which usually is the display
screen. The cout is used in conjunction with the stream insertion operator, which is
written as << which are two less than signs as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Welcome to SYBCA Class";

cout<< "Value of str is : " <<str<<endl;


}

Output
Value of str is : Welcome to SYBCA Class

The << operator is overloaded to output data items of built-in types integer, float,
double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as
shown above and endl is used to add a new-line at the end of the line.

2) The Standard Input Stream (cin)


The predefined object cin is an instance of istream class. The cin object is said to
be attached to the standard input device, which usually is the keyboard. The cin is
used in conjunction with the stream extraction operator, which is written as >>
which are two greater than signs as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char name[50];
cout<< "Please enter your name: ";

Prof. Paurnima N. Patil. Page 2


cin>> name;
cout<< "Your name is: " << name
<<endl;
}

Output
Please enter your name: PoojaPatil
PoojaPatil

3) Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line
characters and flushes the stream.
#include <iostream>
using namespace std;
int main( ) {
cout<< "Good";
cout<< "Morning"<<endl;
cout<< "End of line"<<endl;
}

Output
GoodMorning
End of line

 Data Types in C++


There are 4 types of data types in C++ language.
Types Data Types
Basic Data Type int, char, float, double, etc
Derived Data Type function, array, pointer, etc
Enumeration Data Type enum
User Defined Data Type class,structure,union

Prof. Paurnima N. Patil. Page 3


1) Basic Data Types
The basic data types are integer-based and floating-point based. C++ language
supports both signed and unsigned literals.The memory size of basic data types
may change according to 32 or 64 bit operating system.
Data Types Memory Range
Size
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
float 4 byte
double 8 byte
long double 10 byte

Examples:
#include <iostream.h>
#include<conio.h>
void main() {
cout<< "Size of char : " <<sizeof(char) <<endl;
cout<< "Size of int : " <<sizeof(int) <<endl;
cout<< "Size of short int : " <<sizeof(short int) <<endl;
cout<< "Size of long int : " <<sizeof(long int) <<endl;
cout<< "Size of float : " <<sizeof(float) <<endl;
cout<< "Size of double : " <<sizeof(double) <<endl;
cout<< "Size of wchar_t : " <<sizeof(wchar_t) <<endl;
Prof. Paurnima N. Patil. Page 4
getch();
}

Output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of wchar_t : 4

#include <iostream.h>
#include<conio.h>
#include <string.h>

int main() {
// Integer data types
int a = 10;
short b = 20;
long c = 30;
long long d = 40;
cout<< "Integer data types: " <<endl;
cout<< "int: " << a <<endl;
cout<< "short: " << b <<endl;
cout<< "long: " << c <<endl;
cout<< "long long: " << d <<endl;

// Floating-point data types


float e = 3.14f;
double f = 3.141592;
long double g = 3.14159265358979L;
cout<< "Floating-point data types: " <<endl;
cout<< "float: " << e <<endl;
cout<< "double: " << f <<endl;
cout<< "long double: " << g <<endl;

Prof. Paurnima N. Patil. Page 5


// Character data types
char h = 'a';
wchar_t i = L'b';
char16_t j = u'c';
char32_t k = U'd';
cout<< "Character data types: " <<endl;
cout<< "char: " << h <<endl;
wcout<< "wchar_t: " << i <<endl;
cout<< "char16_t: " << j <<endl;
cout<< "char32_t: " << k <<endl;

// Boolean data type


bool l = true;
bool m = false;
cout<< "Boolean data type: " <<endl;
cout<< "true: " << l <<endl;
cout<< "false: " << m <<endl;

// String data type


string n = "Hello, world!";
cout<< "String data type: " <<endl;
cout<< n <<endl;
getch();
}

Output
int: 10
short: 20
long: 30
long long: 40
Floating-point data types:
float: 3.14
double: 3.14159
long double: 3.14159
Character data types:
char: a

Prof. Paurnima N. Patil. Page 6


wchar_t: b
char16_t: 99
char32_t: 100
Boolean data type:
true: 1
false: 0
String data type:
Hello, world!

2) Derived Data Types


 Functions
A function is a block of code or program-segment that is defined to perform a
specific well-defined task. A function is generally defined to save the user from
writing the same lines of code again and again for the same input. All the lines of
code are put together inside a single function and this can be called anywhere
required.
Syntax
return_type function_name( parameter list );
Example
#include <iostream.h>
#include <conio.h>

// max here is a function derived type


int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}

// main is the default function derived type


void main()
{
int a = 10, b = 20;

Prof. Paurnima N. Patil. Page 7


// Calling above function to
// find max of 'a' and 'b'
int m = max(a, b);
cout<< "m is " << m;
getch();
}

Output
m is 20

 Types of Functions
There are two types of functions in C++ programming:
1) Library Functions: are the functions which are declared in the C++ header
files such as ceil(x), cos(x), exp(x), etc.
2) User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a
big program and optimizes the code.

 Parameter Passing To Function / Passing Arguments To Function


A Function in C++ can be called in two ways.
 Call by value
 Call by reference
First of all we should understand the meaning of actual and formal
parameters.
Formal parameter : This is the argument which is used inside body of function
definition. It's is limited to the scope of function, it is visible to statements in
function's body only. It gets created when control enters function and gets
destroyed when control exits from function.
Actual parameter : This is the argument which is used while calling a function.

1) Call By Value
The call by value method of passing arguments to a function copies the
actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
Example:

Prof. Paurnima N. Patil. Page 8


#include<iostream.h>
#include<conio.h>

// function declaration
void swap(int x, int y);
void main ()
{
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

getch();
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

2) Call By Reference
The call by reference method of passing arguments to a function copies the
reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
Example
#include<iostream.h>
#include<conio.h>

// function declaration
void swap(int &x, int &y);
void main ()
{

Prof. Paurnima N. Patil. Page 9


int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

getch();
}
Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

 Array
An array is a collection of items stored at continuous memory locations. The
idea of array is to represent many instances in one variable.

Syntax:
DataType ArrayName[size_of_array];

Example
#include <iostream>
using namespace std;
int main()
{

// Array Derived Type


intarr[5];
Prof. Paurnima N. Patil. Page 10
arr[0] = 5;
arr[2] = -10;

// this is same as arr[1] = 2


arr[3 / 2] = 2;

arr[3] = arr[0];

cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];

return 0;
}

Output:
5 2 -10 5

 Pointers / Pointer to Variable


Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data
structures.
Syntax:
datatype *var_name;
How to use a pointer?
1) Establish a pointer variable.
2) employing the unary operator (&), which yields the address of the variable, to
assign a pointer to a variable's address.
3) Using the unary operator (*), which gives the variable's value at the address
provided by its argument, one can access the value stored in an address.
Example:
int *ptr;
Where ptr points to an address which holds int data

Prof. Paurnima N. Patil. Page 11


#include <iostream.h>
#include <conio.h>
void main()
{
int number=30;
int *p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
getch();
}

Output
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

 Pointer Arithmetic
Pointer is an address which is a numeric value; therefore, you can perform
arithmetic operations on a pointer just as you can a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and -.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the
variable pointer can be incremented, unlike the array name which cannot be
incremented because it is a constant pointer.
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases
its value by the number of bytes
Example:
Program To Demonstrate The Incrementy And Decrement

#include <iostream.h>
#include<conio.h>
void main()
{
int num = 27;

Prof. Paurnima N. Patil. Page 12


int *ptr;
ptr = num;

cout << "Size of int: " << sizeof(int) << endl;

cout << "Before Increment: " << ptr<< endl;


// Increment pointer
ptr++;

cout << "After Increment: " << ptr << endl;

cout << "Before Decrement: " << ptr << endl;


// Decrement pointer
ptr--;

cout << "After Decrement: " << ptr << endl;


getch();
}
Output:
Size of int: 4
Before Increment: 0x7ffe3e7f56d4
After Increment: 0x7ffe3e7f56d8
Before Decrement: 0x7ffe3e7f56d8
After Decrement: 0x7ffe3e7f56d4

 Array Using the Pointer


Pointers store the memory location or address of variables. In other words,
pointers reference a memory location and obtaining the value stored at that
memory location is known as dereferencing the pointer.
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int arr[5] = {5, 2, 9, 4, 1};
int *ptr = &arr[2];
cout<<"The value in the second index of the array is: "<< *ptr;
getch();
}

Prof. Paurnima N. Patil. Page 13


Output
The value in the second index of the array is: 9

 Pointer to an array
It is also known as a locator or indicator that points to an address of a variable or
memory block. Pointers can store the address of a single variable, as well as it can
also store the address of indexes of an array.
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
cout <<"\n"<< ptr;
getch();
}
Output:
0x7fff16b7b6d0

 Pointer to Pointer (Double Pointer)


A pointer is a variable that points to the address of a variable in memory.
Often it happens that we need a pointer to point at the pointer itself (yeah it can
come to that). Such a pointer is known as a double pointer.
The first pointer stores the address of the assigned variable. And the second
pointer stores the address of the first pointer. That is why they are known as
double-pointers.
Syntax
int **ptr; //declaration of double pointer
Working
The first pointer, ptr_1, is pointing to the variable so this pointer has the
address of a variable. Then we declare another pointer, ptr_2, which points
to ptr_1. So, ptr_2 stores the address of ptr_1. This is how a double pointer works.

Prof. Paurnima N. Patil. Page 14


Example :
#include<iostream.h>
#include<conio.h>
void main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;

ptr = &var;
pptr = &ptr;

cout << "Value of var :" << var << endl;


cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
getch;
}
Output:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000

 Pointer to Function / Function Pointer


As we know that pointers are used to point some variables; similarly, the
function pointer is a pointer used to point functions. It is basically used to store the

Prof. Paurnima N. Patil. Page 15


address of a function. We can call the function by using the function pointer, or we
can also pass the pointer to another function as a parameter.
OR
The function pointer is used to point functions, similarly, the pointers are
used to point variables. It is utilized to save a function‟s address. The function
pointer is either used to call the function or it can be sent as an argument to another
function.

Syntax:
return_type (*FuncPtr) (parameter type, ....);
Example:

#include<iostream.h>
#include<conio.h>
int multiply(int a, int b)
{
return a * b;
}
void main()
{
int (*func)(int, int);
func = multiply;
int prod = func(15, 2);
cout << "The value of the product is: " << prod << endl;
getch();
}
Output:
The value of the product is: 30

Prof. Paurnima N. Patil. Page 16


 Pointer to Object
A pointer is a variable that stores the memory address of another variable (or
object) as its value. A pointer aims to point to a data type which may be int,
character, double, etc. Pointers to objects aim to make a pointer that can access the
object, not the variables. Pointer to object in C++ refers to accessing an object.
then we need to use the -> symbol, as shown in the below example.
Syntax
class_name * object_pointer_name
Example
#include<iostream.h>
#include<conio.h>
class student
{
public:
int empid;
float salary;
void getdata(int a,float b)
{
empid=a;
salary=b;
}
void disp()
{
cout<<"Empid"<<empid<<endl;
cout<<"Salary"<<salary<<endl;
}
};
void main()
{
student s;
student *ptrs;
ptrs = &s;
clrscr();
ptrs->getdata(10,42000);
ptrs->disp();
getch();

Prof. Paurnima N. Patil. Page 17


}

Output:
Empid10
Salary42000

3) Enumeration Data Type


 Enumerations are a user-defined data types which can be assigned some
limited values.
 In this, you can specify a set of values for a variable and the variable can
select only one of the set. It has a fixed set of constants.
 To define an enumeration, keyword 'enum' is used.
 These values are defined by the programmer at the time of declaring the
enumerated type.
 Enumerations can be used to define days of a week, months, weathers, etc.
The enum constants are static and final implicitly.
Syntax
enumenum_name{ element1, element2, element3, element4,};

Examples
#include <iostream.h>
#include <conio.h>

enum direction { North, South, East, West };


void main(){
direction dir;
dir = East;
cout<< "Direction: " << dir;
getch();
}

Output
Day 4

Prof. Paurnima N. Patil. Page 18


#include <iostream.h>
#include <conio.h>
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
void main(){
week today;
today = Monday;
cout<< "Day " << today+1;
getch();
}

Output
Day 2

4) User Defined Data Types


 Class: The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
OR
A C++ class combines data and methods for manipulating the data
into one. Classes also determine the forms of objects. The data and methods
contained in a class are known as class members. A class is a user-defined
data type. To access the class members, we use an instance of the class. You
can see a class as a blueprint for an object.

Syntax:

Prof. Paurnima N. Patil. Page 19


#include<iostream.h>
#include<conio.h>
class Student
{
public:
int rollno;
char name[50];
float marks;
void display()
{
cout<<"Roll Number: "<< rollno <<endl;
cout<<"Name: "<< name <<endl;
cout<<"Marks: "<< marks <<endl;
}
};
void main()
{
Student S= {1, "Harry", 91.5};
S.display();
getch();
}

Output
Roll Number: 1
Name: Harry
Marks: 91.5

 Class Definitions or Access Modifiers


You must have come across these three keywords. They are access
modifiers.
1) Private:
When the private keyword is used to define a function or class, it
becomes private. Such are only accessible from within the class.

2) Protected:
The protected keyword is used to create protected members (data and
function). The protected members can be accessed within the class and from
the derived class

Prof. Paurnima N. Patil. Page 20


3) Public:
The public keyword, on the other hand, makes data/functions public.
These are accessible from outside the class.
OR
The public keyword is used to create public members (data and
functions). The public members are accessible from any part of the program.

 Member Functions in Classes


There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
Inside class example
#include<iostream.h>
#include<conio.h>
class area
{
public:
int side;
int getarea() //function declaration
{
return side * side; //function defination
}
};
void main()
{
area a1,a2; //create objs of class
a1.side=7;
a2.side=10;
int i=a1.getarea(); //function call
int j=a2.getarea();
cout<<"Area of side 4 is"<<i<<endl;
cout<<"Area of side 10 is"<<j<<endl;
getch();
}

Output
Area of side 4 is49
Area of side 10 is100

Prof. Paurnima N. Patil. Page 21


Outside class example
#include<iostream.h>
#include<conio.h>
class area
{
public:
int side;
int getarea(); //function declaration
};
int area::getarea()
{
return side*side;
}
void main()
{
area a1; //create obj of class
a1.side=7;
int i=a1.getarea(); //function call
cout<<i;
getch();
}

Output
49

 Structure: A structure creates a data type that can be used to group items of
possibly different types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Examples:

Prof. Paurnima N. Patil. Page 22


#include <iostream.h>
#include <string.h>
#include <conio.h>

struct Books {
char title[50];
char author[50];
char subject[100];
intbook_id;
};

void main()
{
struct Books Book1; // Declare Book1 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Print Book1 info


cout<< "Book 1 title : " << Book1.title <<endl;
cout<< "Book 1 author : " << Book1.author <<endl;
cout<< "Book 1 subject : " << Book1.subject <<endl;
cout<< "Book 1 id : " << Book1.book_id <<endl;

getch();
}

Output
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407

 Unions: A union is a type of structure that can be used where the amount of
memory used is a key factor. Similarly to the structure, the union can contain
different types of data types.Each time a new variable is initialized from the
union it overwrites the previous in C language but in C++ we also don‟t

Prof. Paurnima N. Patil. Page 23


need this keyword and uses that memory location.It is declared by using the
keyword “union“.
Syntax:
The syntax of using Union in C++ language is written below:
union <Name of the union>
{
Define the members;
} variable names ;

Where:
Name of the union – One can use any name as the union‟s name. After
writing the union, name the union according to the requirement.
Define the members − Here, the coder has to define the member variables.
Union objects − Here, the coder can write the objects of the union.

Example
#include<iostream.h>
#include<conio.h>
union product
{
intproductid;
char name[20];
float price;
};

void main()
{
union product obj;
cout<< "Enter product-id: ";
cin>>obj.productid;
cout<< "Enter name of product: ";
cin>> obj.name;
cout<< "Enter price of product: ";
cin>>obj.price;
cout<< "Product-id is: " <<obj.productid<<endl;
cout<< "Product name is: " << obj.name <<endl;

Prof. Paurnima N. Patil. Page 24


cout<< "Product price is: " <<obj.price;
getch();
}

Output:
Enter product-id: 12
Enter name of product: Phone
Enter price of product: 1200.89
Product-id is: 1150688379
Product name is: {ûDe
Product price is: 1200.89
Above program show a union can have many members but only one of its
members will have a value at any given time. Here, we stored the last value in the
price. So, only the price variable will have the correct value.

 Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

1) Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an B % A will give 0
integer division
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by A-- will give 9
one

Prof. Paurnima N. Patil. Page 25


Example:

#include <iostream.h>
#include <conio.h>

void main() {
int a = 21;
int b = 10;
int c ;

c = a + b;
cout<< "addition is :" << c <<endl ;

c = a - b;
cout<< "substraction is :" << c <<endl
;
c = a * b;
cout<< "multiplication is :" << c <<endl ;

c = a / b;
cout<< "division is :" << c <<endl ;

c = a % b;
cout<< "modulo is :" << c <<endl ;

c = a++;
cout<< "increment operator is :" << c <<endl ;

c = a--;
cout<< "decrement operator is :" << c <<endl ;

getch();
}

Output
addition is :31

Prof. Paurnima N. Patil. Page 26


substraction is :11
multiplication is :210
division is :2
modulo is :1
increment operator is :21
decrement operator is :22

2) Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example
== Checks if the values of two operands are (A == B) is not true.
equal or not, if yes then condition becomes
true.
!= Checks if the values of two operands are (A != B) is true.
equal or not, if values are not equal then
condition becomes true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand,
if yes then condition becomes true.
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand,
if yes then condition becomes true.

Example:
#include <iostream.h>
#include <conio.h>
void main() {
int a = 21;
int b = 10;
int c ;
Prof. Paurnima N. Patil. Page 27
if( a == b ) {
cout<< "a is equal to b" <<endl ;
} else {
cout<< "a is not equal to b" <<endl ;
}

if( a < b ) {
cout<< "a is less than b" <<endl ;
} else {
cout<< "a is not less than b" <<endl ;
}

if( a > b ) {
cout<< "a is greater than b" <<endl ;
} else {
cout<< "a is not greater than b" <<endl ;
}

/* Let's change the values of a and b */


a = 5;
b = 20;
if( a <= b ) {
cout<< "a is either less than \ or equal to b" <<endl ;
}

if( b >= a ) {
cout<< "b is either greater than \ or equal to b" <<endl ;
}

getch();
}

Output
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b

Prof. Paurnima N. Patil. Page 28


3) Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If (A && B) is false.
both the operands are non-zero, then
condition becomes true.
|| Called Logical OR Operator. If any (A || B) is true.
of the two operands is non-zero,
then condition becomes true.
! Called Logical NOT Operator. Use !(A && B) is true.
to reverses the logical state of its
operand. If a condition is true, then
Logical NOT operator will make
false.

Example:
#include <iostream.h>
#include <conio.h>
void main() {
int a = 5;
int b = 20;
int c ;

if(a && b) {
cout<< "Condition is true"<<endl ;
}

if(a || b) {
cout<< "Condition is true"<<endl ;
}

/* Let's change the values of a and b */


a = 0;
b = 10;

if(a && b) {
cout<< "Condition is true"<<endl ;
} else {
Prof. Paurnima N. Patil. Page 29
cout<< "Condition is not true"<<endl ;
}

if(!(a && b)) {


cout<< "Condition is true"<<endl ;
}

getch();
}

Output
Condition is true
Condition is true
Condition is not true
Condition is true

4) Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

Assume variable A holds 60 and variable B holds 13, then −


Operator Description Example
& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100

Prof. Paurnima N. Patil. Page 30


| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011
exists in either operand. 1101
^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
it is set in one operand but not both. 0001
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100
unary and has the effect of 'flipping' 0011 in 2's complement form due
bits. to a signed binary number.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111
operands value is moved left by the 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15 which is 0000
operands value is moved right by the 1111
number of bits specified by the right
operand.

Example:
#include <iostream.h>
#include <conio.h>
void main() {
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;

c = a & b; // 12 = 0000 1100


cout<< "Value of c is : " << c <<endl ;

c = a | b; // 61 = 0011 1101
cout<< "Value of c is: " << c <<endl ;

c = a ^ b; // 49 = 0011 0001
cout<< "Value of c is: " << c <<endl ;

c = ~a; // -61 = 1100 0011


cout<< "Value of c is: " << c <<endl ;

c = a << 2; // 240 = 1111 0000


cout<< "Value of c is: " << c <<endl ;

Prof. Paurnima N. Patil. Page 31


c = a >> 2; // 15 = 0000 1111
cout<< "Value of c is: " << c <<endl ;

getch();
}

Output
Value of c is : 12
Value of c is: 61
Value of c is: 49
Value of c is: -61
Value of c is: 240
Value of c is: 15

5) Assignment Operators
There are following assignment operators supported by C++ language −
Operator Description Example
= Simple assignment operator, Assigns C = A + B will assign value of A
values from right side operands to left + B into C
side operand.
+= Add AND assignment operator, It adds C += A is equivalent to C = C +
right operand to the left operand and A
assign the result to left operand.
-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A
subtracts right operand from the left
operand and assign the result to left
operand.
*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A
multiplies right operand with the left
operand and assign the result to left
operand.
/= Divide AND assignment operator, It C /= A is equivalent to C = C / A
divides left operand with the right
operand and assign the result to left
operand.
%= Modulus AND assignment operator, It C %= A is equivalent to C = C %
takes modulus using two operands and A

Prof. Paurnima N. Patil. Page 32


assign the result to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2
operator.
|= Bitwise inclusive OR and assignment C |= 2 is same as C = C | 2
operator.

Example:
#include <iostream.h>
#include <conio.h>
void main() {
int a = 21;
int c ;

c = a;
cout<< "= Operator, Value of c = : " <<c<<endl ;

c += a;
cout<< "+= Operator, Value of c = : " <<c<<endl ;

c -= a;
cout<< "-= Operator, Value of c = : " <<c<<endl ;

c *= a;
cout<< "*= Operator, Value of c = : " <<c<<endl ;

c /= a;
cout<< "/= Operator, Value of c = : " <<c<<endl ;

c = 200;
c %= a;
cout<< "%= Operator, Value of c = : " <<c<<endl ;

c <<= 2;
cout<< "<<= Operator, Value of c = : " <<c<<endl ;

c >>= 2;
cout<< ">>= Operator, Value of c = : " <<c<<endl ;
Prof. Paurnima N. Patil. Page 33
c &= 2;
cout<< "&= Operator, Value of c = : " <<c<<endl ;

c ^= 2;
cout<< "^= Operator, Value of c = : " <<c<<endl ;

c |= 2;
cout<< "|= Operator, Value of c = : " <<c<<endl ;

getch();
}

Output
= Operator, Value of c = : 21
+= Operator, Value of c = : 42
-= Operator, Value of c = : 21
*= Operator, Value of c = : 441
/= Operator, Value of c = : 21
%= Operator, Value of c = : 11
<<= Operator, Value of c = : 44
>>= Operator, Value of c = : 11
&= Operator, Value of c = : 2
^= Operator, Value of c = : 0
|= Operator, Value of c = : 2

6) Misc Operators
The following table lists some other operators that C++ supports.
Sr.No Operator & Description
1. sizeof
sizeof operator returns the size of a variable. For example,sizeof(a), where „a‟
is integer, and will return 4.

2. Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X
otherwise returns value of Y.
3. Cast
Casting operators convert one data type to another. For example,int(2.2000)
would return 2.

Prof. Paurnima N. Patil. Page 34


4. &
Pointer operator & returns the address of a variable. For example&a; will give
actual address of the variable.
5. *
Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.

Examples of Misc Operator


sizeof Condition ? X : Y
#include <iostream.h> #include <iostream.h>
#include<conio.h> #include <conio.h>
void main() { void main () {
cout<< "Size of char : " <<sizeof(char) // Local variable declaration:
<<endl; int x, y = 10;
cout<< "Size of int : " <<sizeof(int) <<endl;
cout<< "Size of short int : " <<sizeof(short x = (y < 10) ? 30 : 40;
int) <<endl; cout<< "value of x: " << x <<endl;
cout<< "Size of long int : " <<sizeof(long
int) <<endl; getch();
cout<< "Size of float : " <<sizeof(float) }
<<endl;
cout<< "Size of double : " <<sizeof(double) Output:
<<endl; value of x: 40
cout<< "Size of wchar_t : "
<<sizeof(wchar_t) <<endl;

getch();
}
Output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

Prof. Paurnima N. Patil. Page 35


Cast
#include <iostream.h>
#include <conio.h>
void main() {
double a = 21.09399;
float b = 10.20;
int c ;

c = (int) a;
cout<< "Value of (int)a is :" << c <<endl ;

c = (int) b;
cout<< "Value of (int)b is :" << c <<endl ;

getch();
}

Output:
Value of (int)a is :21
Value of (int)b is :10

 Control and Conditional Statements


 Selection Statements
 if__else
 switch___ case
 Iteration Statements
 while
 do__while
 for
 Jump Statements
 break
 goto
 continue

Prof. Paurnima N. Patil. Page 36


 Selection Statements
 if Statement
 if-else Statement
 Nested if Statement
 if-else-if Ladder
 switch Statement

1) if statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statements is executed otherwise
not.
Syntax
if(condition)
{
// Statements to execute
if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. If we do not provide the curly braces „{„ and „}‟
after if(condition) then by default if statement will consider the first immediately
below statement to be inside its block.

Example
#include <iostream.h>
#include <conio.h>
void main () {
int number = 10;
if (number % 2 == 0)
{
cout<< "The Number you have Enter it is Even";
}
getch();
}

Output
The Number you have Enter it is Even

Prof. Paurnima N. Patil. Page 37


2) if-else
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won‟t. But what if we want to do
something else when the condition is false? Here comes the C else statement. We
can use the else statement with the if statement to execute a block of code when the
condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
#include<iostream.h>
#include<conio.h>
void main () {
int number = 15;
if (number % 2 == 0)
{
cout<< "The Number you have Enter it is Even";
}
else
{
cout<< "The Number you have Enter it is Odd";
}
getch(),;
}

Output
The Number you have Enter it is Odd

3) Nested if-else
A nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes, both C

Prof. Paurnima N. Patil. Page 38


and C++ allow us to nested if statements within if statements, i.e, we can place an
if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
Example

// C++ program to illustrate nested-if statement


#include <iostream.h>
#include<conio.h>
void main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
cout<< "i is smaller than 15\n";
if (i < 12)
cout<< "i is smaller than 12
too\n";
else
cout<< "i is greater than 15";
}
getch();
}

Output
i is smaller than 15
i is smaller than 12 too

Prof. Paurnima N. Patil. Page 39


4) if-else-if Ladder
The if else if statements are used when the user has to decide among
multiple options. The C if statements are executed from the top down. As soon as
one of the conditions controlling the if is true, the statement associated with that if
is executed, and the rest of the C else-if ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed. if-else-if ladder is
similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
………
………
else
statement;
Example

#include <iostream.h>
#include <conio.h>
voidmain(){
int number;
cout<<"To Check Grade Enter a Number:";
cin>> number;
if(number <0|| number >100)
{
cout<<"wrong No";
}
elseif(number >=0&& number <40)
{
cout<<"Fail";
}
elseif(number >=40&& number <59)
{
cout<<"D Grade";
}
elseif(number >=60&& number <70)
{
cout<<" C Grade";
}
Prof. Paurnima N. Patil. Page 40
elseif(number >=71&& number <79)
{
cout<<"B Grade";
}
elseif(number >=80&& number <89)
{
cout<<"A Grade";
}
elseif(number >=90&& number <=100)
{
cout<<"A+ Grade";
}
getch();
}

Output
To Check Grade Enter a Number:40
D Grade

5) Switch Statement
The switch case statement is an alternative to the if else if ladder that can be
used to execute the conditional code based on the value of the variable specified in
the switch statement. The switch block consists of cases to be executed based on
the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;}
Example

#include<iostream.h>
#include<conio.h>
void main () {
int number;
Prof. Paurnima N. Patil. Page 41
cout<< "To check the grade enter a number:";
cin>> number;
switch (number)
{
case 2: cout<< "It is 2"; break;
case 3: cout<< "It is 3"; break;
case 4: cout<< "It is 4"; break;
default: cout<< "Not 2, 3 or 4"; break;
}
getch();
}

Output
To check the grade enter a number:3
It is 3

 Iteration Statements
1) While Loop
In C++, the loop is used several times for the iteration of a part of the
program. If the iteration number is not set, it is advisable to use the loop rather than
the loop.
Syntax
While(condition0
{
//code should be executed;
}
Example
#include<iostream.h>
#include<conio.h>
void main() {
int i = 5;
while(i <= 10)
{
cout<< i << "\t";
i++;
}
getch();

Prof. Paurnima N. Patil. Page 42


}

Output
5 6 7 8 9 10

2) Do while loop
C++ is used many times to iterate a part of the software. It is advised that
you use a do-while loop, if the number of iteration is not known and the loop must
be performed at least once.
Syntax
do
{
//code should be executed;
}
While(condition);
Example
#include<iostream.h>
#include<conio.h>
void main() {
int j = 2;
do{
cout<< j << "\t";
j++;
} while (j <= 10) ;
getch();
}

Output
2 3 4 5 6 7 8 9 10

3) For Loop
The C++ loop is used multiple times to iterate a part of the program. It is
recommended that you use for loops when the iteration number is set. For loops, it
is recommended.
Syntax
For(initialization; condition;

Prof. Paurnima N. Patil. Page 43


incr/decr){
//code should be executed;
}

Example
#include <iostream.h>
#include <conio.h>
void main() {
for(int i = 3; i <= 10; i++){
cout<< i << "\t";
}
getch();
}

3 4 5 6 7 8 9

 Jump Statements
1) Break Statement
The break C++ is used for loop breakage or statement switching. It breaks
the program‟s current flow in the given state. In the case of an inner loop, only an
internal loop splits.
Syntax
Jump-statement;
break;
Example
#include<iostream.h>
#include<conio.h>
void main() {
for (int j = 1; j <= 20; j++)
{
if (j == 15)
{
break;
}
cout<< j << "\t";
}

Prof. Paurnima N. Patil. Page 44


getch();
}

Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14

2) Continue Statement
The declaration C++ is used for the continuation of the loop. The current
program flow continues and the remaining code is omitted at a specified state. If
there is an inner loop, only an inner loop continues.
Syntax
Jump-statement;
Continue;
Example
#include<iostream.h>
#include<conio.h>
void main()
{

for (int i = 1; i <= 10; i++) {

if (i == 6)
continue;

else
cout<< i << " ";
}

getch();
}
Output
1 2 3 4 5 7 8 9 10

Prof. Paurnima N. Patil. Page 45


3) Goto statement
The C+ + goto declaration is also called a jump declaration. The control to
the other part of the program is transferred. It saves to the specified label
unconditionally.
Example
#include<iostream.h>
#include<conio.h>
void printNumbers()
{
int n = 1;
label:
cout<< n << " ";
n++;
if (n <= 10)
goto label;
}

void main()
{
printNumbers();
getch();
}

Output
1 2 3 4 5 6 7 8 9 10

 Recursive Function
A function that calls itself is called a recursive function. When a recursive
function is called, it executes a set of instructions and then calls itself to execute
the same set of instructions with a smaller input. This process continues until a
base case is reached, which is a condition that stops the recursion and returns a
value.
Example
#include<iostream.h>
#include<conio.h>
int factorial(int);

Prof. Paurnima N. Patil. Page 46


void main()
{
int n, result;
cout << "Enter a number: ";
cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
getch();
}
int factorial(int n)
{
if (n > 1)
{
return n * factorial(n - 1);
}
else
{
return 1;
}
}
Output:
Enter a non-negative number: 4
Factorial of 4 = 24

 Inline Function
1) If a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time.
2) Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
3) To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
OR

Prof. Paurnima N. Patil. Page 47


Inline function is defined as copies the function to the location of the
function call in compile-time and may make the program execution faster.
Syntax
inline returnType functionName(parameters)
{
// code
}
Example:
#include<iostream.h>
#include<conio.h>
inline int add(int a, int b)
{
return(a+b);
}
void main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
getch();
}

 Function Overloading
Function overloading is a feature of object-oriented programming where two
or more functions can have the same name but different parameters. When a
function name is overloaded with different jobs it is called Function Overloading.
In Function Overloading “Function” name should be the same and the arguments
should be different.
Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the function such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you to
understand the behavior of the function because its name differs.
Declaration
add(int a, int b)
add(double a, double b)

Prof. Paurnima N. Patil. Page 48


Example:
#include<iostream.h>
#include<conio.h>
class Addition
{
public:
int sum(int num1,int num2)
{
return num1+num2;
}
int sum(int num1,int num2, int num3)
{
return num1+num2+num3;
}
};
void main
{
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
getch();
}
Output:
35
191

Prof. Paurnima N. Patil. Page 49

You might also like