Nothing Special   »   [go: up one dir, main page]

Unit 1 Principles of OOP: What Is OOPS?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

Unit 1

Principles of OOP

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods).

 What is OOPS?

Object-Oriented Programming System (OOPs) is a programming concept that works on the


principles of abstraction, encapsulation, inheritance, and polymorphism. It allows users to
create objects they want and create methods to handle those objects. The basic concept of
OOPs is to create objects, re-use them throughout the program, and manipulate these objects
to get results.

 Difference between OOP and POP

Procedure-oriented Programming (POP) and Object-oriented programming(OOP) both


are the programming approaches, which uses high-level language for programming. A
program can be written in both the languages, but if the task is highly complex, OOP operates
well as compared to POP. In POP, the ‘data security’ is at risk as data freely moves in the
program, as well as, ‘code reusability’ is not achieved which makes the programming
lengthy, and hard to understand.

 Comparison Chart

BASIS FOR
POP C OOP C++
COMPARISON

Basic Procedure/Structure oriented . Object oriented.

Approach Top-down. Bottom-up.

Basis Main focus is on "how to get Main focus is on 'data security'. Hence,
the task done" i.e. on the only objects are permitted to access the
procedure or structure of a entities of a class.
program .

Division Large program is divided into Entire program is divided into objects.
units called functions.

Entity accessing No access specifier observed. Access specifier are "public", "private",
mode "protected".

Overloading or Neither has it overloaded It overloads functions, constructors, and


Polymorphism functions nor operators. operators.

Inheritance There is no provision of Inheritance achieved in three modes public

1
BASIS FOR
POP C OOP C++
COMPARISON

inheritance. private and protected.

Data hiding & There is no proper way of Data is hidden in three modes public,
security hiding the data, so data is private, and protected. hence data security
insecure increases.

Data sharing Global data is shared among Data is shared among the objects through
the functions in the program. the member functions.

Friend functions No concept of friend function. Classes or function can become a friend of
or friend classes another class with the keyword "friend".
Note: "friend" keyword is used only in c++

Virtual classes or No concept of virtual classes . Concept of virtual function appear during
virtual function inheritance.

Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET.

2
 Advantages

POP (Procedure Oriented Programming)

 Provides an ability to reuse the same code at various places.


 Facilitates in tracking the program flow.
 Capable of constructing modules.

OOP (Object Oriented Programming)

 Objects help in task partitioning in the project.


 Secure programs can be built using data hiding.
 It can potentially map the objects.
 Enables the categorization of the objects into various classes.
 Data abstraction increases reliability.
 Flexible due to the dynamic binding concept.
 Decouples the essential specification from its implementation by using
information hiding.

 Disadvantages

POP (Procedure Oriented Programming)

 Global data are vulnerable.


 Data can move freely within a program
 It is tough to verify the data position.
 Real-world problems cannot be modelled.
 Parts of code are interdependent.
 One application code cannot be used in other application.
 Data is transferred by using the functions.

OOP (Object Oriented Programming)

 It requires more resources.


 Dynamic behaviour of objects requires RAM storage.
 Detection and debugging is harder in complex applications when the
message passing is performed.
 Inheritance makes their classes tightly coupled, which affects the
reusability of objects.

 Object-Oriented Concepts and Applications

 Objects: It is considered as a variable of type class and an instance of a


class.
 Class: It is a set of objects of similar type. A complete set of data and
code of an object creates an user-defined data type by using a class.
 Data abstraction and encapsulation: Abstraction is nothing but a
method of hiding background details and representing essential features.
The encapsulation is a method of packing the data and functions into a
single unit.

3
 Inheritance: Inheritance is a technique of acquiring features of objects
from one class to the other class objects. In other words, it helps in
deriving a new class from the existing one.
 Polymorphism: Polymorphism provides a method of creating multiple
forms of a function by using a single function name.
 Dynamic binding: It specifies that the code associated with a particular
procedure is not known until the moment of the call at run time.
 Message passing: This OOP concept enables interaction between
different classes by transmitting and receiving information.

 List of OOPs Concepts with Examples

1) Class
The class is one of the Basic concepts of OOPs which is a group of similar entities. It is only
a logical component and not the physical entity. Lets understand this one of the OOPs
Concepts with example, if you had a class called “Expensive Cars” it could have objects like
Mercedes, BMW, Toyota, etc. Its properties (data) can be price or speed of these cars. While
the methods may be performed with these cars are driving, reverse, braking etc.
M

2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a
class in a program. An Object is one of the Java OOPs concepts which contains both the data
and the function, which operates on the data. For example - chair, bike, marker, pen, table,
car, etc.

3) Inheritance
Inheritance is one of the Basic Concepts of OOPs in which one object acquires the properties
and behaviors of the parent object. It’s creating a parent-child relationship between two
classes. It offers robust and natural mechanism for organizing and structure of any software.

4) Polymorphism
Polymorphism refers to one of the OOPs concepts in Java which is the ability of a variable,
object or function to take on multiple forms. For example, in English, the verb run has a
different meaning if you use it with a laptop, a foot race, and business. Here, we understand
the meaning of run based on the other words used along with it. The same also applied to
Polymorphism.

5) Abstraction
Abstraction is one of the OOP Concepts in Java which is an act of representing essential
features without including background details. It is a technique of creating a new data type
that is suited for a specific application. Lets understand this one of the OOPs Concepts with
example, while driving a car, you do not have to be concerned with its internal working. Here
you just need to concern about parts like steering wheel, Gears, accelerator, etc.

4
6) Encapsulation
Encapsulation is one of the best Java OOPs concepts of wrapping the data and code. In this
OOPs concept, the variables of a class are always hidden from other classes. It can only be
accessed using the methods of their current class. For example - in school, a student cannot
exist without a class.

7) Association
Association is a relationship between two objects. It is one of the OOP Concepts in Java
which defines the diversity between objects. In this OOP concept, all object have their
separate lifecycle, and there is no owner. For example, many students can associate with one
teacher while one student can also associate with multiple teachers.

8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such
that child object can’t belong to another parent object. For example consider class/objects
department and teacher. Here, a single teacher can’t belong to multiple departments, but even
if we delete the department, the teacher object will never be destroyed.

9) Composition
Composition is a specialized form of Aggregation. It is also called "death" relationship. Child
objects do not have their lifecycle so when parent object deletes all child object will also
delete automatically. For that, let’s take an example of House and rooms. Any house can have
several rooms. One room can’t become part of two different houses. So, if you delete the
house room will also be deleted.

 Advantages of OOPs (Object-Oriented Programming System):

 OOPs Concepts in Java offer easy to understand and a clear modular structure for
programs.
 Objects created for Object-Oriented Programs can be reused in other programs. Thus it
saves significant development cost.
 Large programs are difficult to write, but if the development and designing team follow
OOPS concepts, then they can better design with minimum flaws.
 It enhances program modularity because every object exists independently.

 C verses Cpp

No. C C++

1) C follows the procedural C++ is multi-paradigm. It supports


style programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for outside
users.

3) C follows the top-down C++ follows the bottom-up approach.

5
approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions In C++, you can use functions in structure.
in structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and C++ mainly uses stream cin and cout to


printf() are mainly used for perform input and output operations.
input/output.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided into functions


into procedures and and classes.
modules

10) C does not provide the C++ supports the feature of namespace.
feature of namespace.

11) Exception handling is not C++ provides exception handling using Try
easy in C. It has to perform and Catch block.
using other functions.

12) C does not support the C++ supports inheritance.


inheritance.

 Structure of a C++ program

A C++ program is structured in a specific and particular manner. In C++, a program is


divided into the following three sections:

1. Standard Libraries Section:


2. Main Function Section
3. Function Body Section

For example, let’s look at the implementation of the Hello World program:


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

void main() {
  cout << "Hello World!" << endl;
  getch();
}

Output
Hello World

6
Standard libraries section
#include <iostream>
using namespace std;
 #include is a specific preprocessor command that effectively copies and
pastes the entire text of the file, specified between the angle brackets, into the
source code.
 The file <iostream>, which is a standard file that should come with the C++
compiler, is short for input-output streams. This command contains code
for displaying and getting an input from the user.
 namespace is a prefix that is applied to all the names in a certain
set. iostream file defines two names used in this program - cout and endl.

 This code is saying: Use the cout and endl tools from the std toolbox.

Main function section


int main() {}

 The starting point of all C++ programs is the main function.

 This function is called by the operating system when your program is executed
by the computer.

 { signifies the start of a block of code, and } signifies the end.

Function body section


cout << "Hello World" << endl;
  return 0;

 The name cout is short for character output and displays whatever is


between the << brackets.

 Symbols such as << can also behave like functions and are used with the
keyword cout.

 The return keyword tells the program to return a value to the function int


main

 After the return statement, execution control returns to the operating system
component that launched this program.

 Execution of the code terminates here.

7
 Token
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:  
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying
to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using
C/C++ preprocessor directives. C language supports 32 keywords which are given below: 

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 31 additional keywords other than C Keywords they are: 

asm bool catch class


const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

2.. Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared, you can use the identifier in later
program statements to refer to the associated value. A special kind of identifier, called a
statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers: 
 They must begin with a letter or underscore(_).

8
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
 main: method name.
 a: variable name.
3.. Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals. Constants may belong to any of the data type. 
Syntax:
const data_type variable_name; (or) const data_type *variable_name; 
Types of Constants: 
 Integer constants – Example: 0, 1, 1218, 12482
 Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
 Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
 Character constants -Example: ‘a’, ‘A’, ‘z’
 String constants -Example: “GeeksforGeeks”
4.. Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double-
quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for
String: 
 char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;
 when we declare char as “string[20]”, 20 bytes of memory space is allocated
for holding the string value.
 When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5.. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = # 
 Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and
function parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon(;): It is known as a statement terminator.  It indicates the end of
one logical entity. That’s why each individual statement must be ended with a
semicolon.
 Asterisk (*): It is used to create a pointer variable.
 Assignment operator(=): It is used to assign values.

9
 Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
6.. Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands. 
Depending on the number of operands that an operator can act upon, operators can be
classified as follows: 
 Unary Operators: Those operators that require only a single operand to act
upon are known as unary operators.For Example increment and decrement
operators
 Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators are classified into : 
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
 Ternary Operators: ? :

 C++ Variables
Variables are containers for storing data values. In C++, there are different types of variables
(defined with different keywords), for example:
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 string - stores text, such as "Hello World". String values are surrounded by double
quotes
 bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:

10
 Basic Data Type and User Defined Data Types:
All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the 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 a different amount of memory.

11
Data types in C++ is mainly divided into three 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: 
 Integer

 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character
2. Derived Data Types: The data-types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely: 
 Function
 Array
 Pointer
 Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself.
Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes: 
 Class
 Structure

12
 Union
 Enumeration
 Typedef defined DataType
This article discusses primitive data types available in C++. 
 
 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. 
 
 void: Void means without any value. void datatype represents a valueless entity. Void
data type is used for those function which does not returns a value. 
 
 Wide Character: Wide character data type is also a character data type but this data
type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long. 

// C++ program to sizes of data types


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

void main()
{
    cout << "Size of char : " << sizeof(char)
      << " byte" << endl;
    cout << "Size of int : " << sizeof(int)
      << " bytes" << endl;
    cout << "Size of short int : " << sizeof(short int)
      << " bytes" << endl;
    cout << "Size of long int : " << sizeof(long int)
       << " bytes" << endl;
    cout << "Size of signed long int : " << sizeof(signed long int)
       << " bytes" << endl;
    cout << "Size of unsigned long int : " << sizeof(unsigned long int)
       << " bytes" << endl;
    cout << "Size of float : " << sizeof(float)
       << " bytes" <<endl;
    cout << "Size of double : " << sizeof(double)
       << " bytes" << endl;
    cout << "Size of wchar_t : " << sizeof(wchar_t)

13
       << " bytes" <<endl;
     
    Getch();
}

 Type Casting:
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to avoid
lose of data.
 All the data types of the variables are upgraded to the data type of the variable
with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
  
#include<iostream.h>
 #include<conio.h>
  
int main()
{
    int x = 10; // integer x
    char y = 'a'; // character c
  
    // y implicitly converted to int. ASCII
    // value of 'a' is 97
    x = x + y;
  
    // x is implicitly converted to float
    float z = x + 1.0;
  
    cout << "x = " << x << endl
         << "y = " << y << endl
         << "z = " << z << endl;
  
    getch();
}
Output:
x = 107
y = a
z = 108

14
2. Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:

// C++ program to demonstrate


// explicit type casting
  
#include <iostream>
using namespace std;
  
int main()
{
    double x = 1.2;
  
    // Explicit conversion from double to int
    int sum = (int)x + 1;
  
    cout << "Sum = " << sum;
  
    return 0;
}
Output:
Sum = 2

 Operators:
An operator is a symbol that operates on a value or a variable.
Operators are symbols that perform operations on variables and values. For
example,  +  is an operator used for addition, while  -  is an operator used for
subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators

15
1. C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and
data. For example,

a + b;

Here, the  +  operator is used to add two variables  a  and  b . Similarly there are
various other arithmetic operators in C++.
Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

#include <iostream>

16
using namespace std;

int main() {
int a, b;
a = 7;
b = 2;

// printing the sum of a and b


cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b


cout << "a - b = " << (a - b) << endl;

// printing the product of a and b


cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;

return 0;
}

Output

a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1

Here, the operators  + ,  -  and  *  compute addition, subtraction, and multiplication


respectively as we might have expected.
/ Division Operator
Note the operation  (a / b)  in our program. The  /  operator is the division operator.
As we can see from the above example, if an integer is divided by another integer,
we will get the quotient. However, if either divisor or dividend is a floating-point
number, we will get the result in decimals.

17
In C++,

7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
7.0 / 2.0 is 3.5

% Modulo Operator
The modulo operator  %  computes the remainder. When  a = 9  is divided by  b = 4,

the remainder is 1.


Note: The  %  operator can only be used with integers.

Increment and Decrement Operators

C++ also provides increment and decrement operators:  ++  and  --  respectively.  +


+  increases the value of the operand by 1, while  --  decreases it by 1.
For example,

int num = 5;

// increasing num by 1
++num;

Here, the value of  num  gets increased to 6 from its initial value of 5.
Example 2: Increment and Decrement Operators

// Working of increment and decrement operators

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a


result_a = ++a;
cout << "result_a = " << result_a << endl;

18
// decrementing b by 1 and storing the result in result_b
result_b = --b;
cout << "result_b = " << result_b << endl;

return 0;
}

Output

result_a = 11
result_b = 99

In the above program, we used  ++  and  --  operator as prefixes. We can also use
these operators as postfix.
There is a slight difference when these operators are used as a prefix versus when
they are used as a postfix.

2. C++ Assignment Operators


In C++, assignment operators are used to assign values to variables. For example,

// assign 5 to a
a = 5;

Here, we have assigned a value of  5  to the variable  a .


Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

19
Example 2: Assignment Operators

#include <iostream>
using namespace std;

int main() {
int a, b, temp;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

// value of a is assigned to temp


temp = a; // temp will be 2
cout << "temp = " << temp << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}

Output

temp = 2
a = 9

3. C++ Relational Operators


A relational operator is used to check the relationship between two operands. For
example,

// checks if a is greater than b


a > b;

Here,  >  is a relational operator. It checks if  a  is greater than  b  or not.
If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
Operator Meaning Example

20
== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

Example 4: Relational Operators

#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}

21
Output

3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

Note: Relational operators are used in decision making and loops.


4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the
expression is true, it returns 1 whereas if the expression is false, it returns 0.
Operato
Example Meaning
r

expression1 && Logical AND.


&&
expression2 True only if all the operands are true.

Logical OR.
expression1 ||
|| True if at least one of the operands is
expression2
true.

Logical NOT.
! !expression
True only if the operand is false.

In C++, logical operators are commonly used in decision making. To further


understand the logical operators, let's see the following examples,

Suppose,
a = 5
b = 8

Then,

(a > 3) && (b > 5) evaluates to true


(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true


(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

22
!(a == 3) evaluates to true
!(a > 3) evaluates to false

Example 5: Logical Operators

#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true


cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true


cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false


cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true


cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false


cout << "!(5 == 5) is " << result << endl;

return 0;
}

Output

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0

23
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 < 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Explanation of logical operator program


 (3 != 5) && (3 < 5)  evaluates to 1 because both operands  (3 != 5)  and  (3

< 5)  are 1 (true).

 (3 == 5) && (3 < 5)  evaluates to 0 because the operand  (3 ==

5)  is 0 (false).

 (3 == 5) && (3 > 5)  evaluates to 0 because both operands  (3 == 5)  and  (3

> 5)  are 0 (false).

 (3 != 5) || (3 < 5)  evaluates to 1 because both operands  (3 != 5)  and  (3

< 5)  are 1 (true).

 (3 != 5) || (3 > 5)  evaluates to 1 because the operand  (3 !=

5)  is 1 (true).

 (3 == 5) || (3 > 5)  evaluates to 0 because both operands  (3 == 5)  and  (3

> 5)  are 0 (false).

 !(5 == 2)  evaluates to 1 because the operand  (5 == 2)  is 0 (false).


 !(5 == 5)  evaluates to 0 because the operand  (5 == 5)  is 1 (true).

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits. They
can only be used alongside  char  and  int  data types.
Operator Description

& Binary AND

| Binary OR

^ Binary XOR

24
~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

 Expressions:

What is an Expression and What are the types of Expressions?

Expression: An expression is a combination of operators, constants and variables. An


expression may consist of one or more operands, and zero or more operators to produce a
value.

Example:
a+b
c
s-1/7*f
.
.
etc
Types of Expressions:
Expressions may be of the following types:

25
 Constant expressions: Constant Expressions consists of only constant values. A constant
value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
 Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
 Floating expressions: Float Expressions are which produce floating point results after
implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool which takes a value
true or false. When arithmetic expressions are used on either side of a relational operator, they
will be evaluated first and then the results compared. Relational expressions are also known as
Boolean expressions.
Examples:
x <= y, x + y > 2
 Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5

26
 Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
 Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.

 Control Structures:

A program is usually not limited to a linear sequence of instructions. During its


process it may bifurcate, repeat code or take decisions. For that purpose, C++
provides control structures that serve to specify what has to be done to perform
our program.

With the introduction of control sequences we are going to have to introduce a new
concept: the block of instructions. A block of instructions is a group of
instructions separated by semicolons ( ;) but grouped in a block delimited by curly
bracket signs: { and }.

27
Most of the control structures that we will see in this section allow a
generic statement as a parameter, this refers to either a single instruction or a block
of instructions, as we want. If we want the statement to be a single instruction we
do not need to enclose it between curly-brackets ( {}). If we want the statement to
be more than a single instruction we must enclose them between curly brackets
({}) forming a block of instructions.

Conditional structure: if and else
It is used to execute an instruction or block of instructions only if a condition is
fulfilled. Its form is:
if (condition) statement

where condition is the expression that is being evaluated. If this condition


is true, statement is executed. If it is false, statement is ignored (not executed) and
the program continues on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value
stored in variable x is indeed 100:
if (x == 100)
  cout << "x is 100";

If we want more than a single instruction to be executed in case


that condition is true we can specify a block of instructions using curly
brackets { }:
if (x == 100)
 {
  cout << "x is ";
  cout << x;
 }

We can additionally specify what we want that happens if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2

For example:

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

prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only
if not- it prints out x is not 100.

28
The if + else structures can be concatenated with the intention of verifying a range
of values. The following example shows its use telling if the present value stored
in x is positive, negative or none of the previous, that is to say, equal to zero.
if (x > 0)
  cout << "x is positive";
else if (x < 0)
  cout << "x is negative";
else
  cout << "x is 0";

Remember that in case we want more than a single instruction to be executed,


we must group them in a block of instructions by using curly brackets { }.

Repetitive structures or loops

Loops have as objective to repeat a statement a certain number of times or while


a condition is fulfilled.
The while loop.
Its format is:
while (expression) statement

and its function is simply to repeat statement while expression is true.

For example, we are going to make a program to count down using


a while loop:

// custom countdown using while Enter the starting number > 8


#include <iostream.h> 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
int main ()
{
int n;
cout << "Enter the starting
number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!";
return 0;
}

When the program starts the user is prompted to insert a starting number for
the countdown. Then the while loop begins, if the value entered by the user

29
fulfills the condition n>0 (that n be greater than 0 ), the block of instructions
that follows will execute an indefinite number of times while the
condition (n>0) remains true.

All the process in the program above can be interpreted according to the
following script: beginning in main:

 1. User assigns a value to n.


 2. The while instruction checks if (n>0). At this point there are two
possibilities:
o true: execute statement (step 3,)
o false: jump statement. The program follows in step 5..
 3. Execute statement:
cout << n << ", ";

--n;
(prints out n on screen and decreases n by 1).

 4. End of block. Return Automatically to step 2.


 5. Continue the program after the block: print out FIRE! and end of
program.

We must consider that the loop has to end at some point, therefore, within
the block of instructions (loop's statement) we must provide some method
that forces condition to become false at some moment, otherwise the loop
will continue looping forever. In this case we have included --n; that causes
the condition to become false after some loop repetitions:
when n becomes 0, that is where our countdown ends.

Of course this is such a simple action for our computer that the whole
countdown is performed instantly without practical delay between numbers.

The do-while loop.
Format:
do statement while (condition);

Its functionality is exactly the same as the while loop except


that condition in the do-while is evaluated after the execution
of statement instead of before, granting at least one execution
of statement even if condition is never fulfilled. For example, the following
program echoes any number you enter until you enter 0.
// number echoer Enter number (0 to end): 12345

30
#include <iostream.h> You entered: 12345
int main () Enter number (0 to end): 160277
{ You entered: 160277
unsigned long n; Enter number (0 to end): 0
do { You entered: 0
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
return 0;
}

The do-while loop is usually used when the condition that has to determine


its end is determined within the loop statement, like in the previous case,
where the user input within the block of intructions is what determines the
end of the loop. If you never enter the 0 value in the previous example the
loop will never end.

The for loop.
Its format is:
for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true,


like the while loop. But in addition, for provides places to specify
an initialization instruction and an increase instruction. So this loop is
specially designed to perform a repetitive action with a counter.

It works the following way:

1, initialization is executed. Generally it is an initial value setting for a


counter varible. This is executed only once.
2, condition is checked, if it is true the loop continues, otherwise the loop
finishes and statement is skipped.
3, statement is executed. As usual, it can be either a single instruction or a
block of instructions enclosed within curly brackets { }.
4, finally, whatever is specified in the increase field is executed and the
loop gets back to step 2.
Here is an example of countdown using a for loop.
// countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
#include <iostream.h> FIRE!
int main ()

31
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}

The initialization and increase fields are optional. They can be avoided


but not the semicolon signs among them. For example we could write: for
(;n<10;) if we want to specify no initialization and no increase; or for
(;n<10;n++) if we want to include an increase field but not
an initialization.

Optionally, using the comma operator (,) we can specify more than one
instruction in any of the fields included in a for loop, like
in initialization, for example. The comma operator (,) is an instruction
separator, it serves to separate more than one instruction where only one
instruction is generally expected. For example, suppose that we wanted to
intialize more than one variable in our loop:
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}
This loop will execute 50 times if neither n nor i are modified within the
loop:

n starts with 0 and i with 100, the condition is (n!=i) (that n be not equal


to i). Because n is increased by one and i decreased by one, the loop's
condition will become false after the 50th loop, when both n and i will be
equal to 50.

Bifurcation of control and jumps.


The break instruction.
Using break we can leave a loop even if the condition for its end is not
fulfilled. It can be used to end an infinite loop, or to force it to end before
its natural end. For example, we are going to stop the count down before it
naturally finishes (an engine failure maybe):

32
// break loop example 10, 9, 8, 7, 6, 5, 4, 3,
#include <iostream.h> countdown aborted!
int main ()
{
int n;
for (n=10; n>0; n--) {
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
return 0;
}

The continue instruction.
The continue instruction causes the program to skip the rest of the loop in
the present iteration as if the end of the statement block would have been
reached, causing it to jump to the following iteration. For example, we are
going to skip the number 5 in our countdown:
// break loop example 10, 9, 8, 7, 6, 4, 3, 2, 1,
#include <iostream.h> FIRE!
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}

The goto instruction.
It allows making an absolute jump to another point in the program. You
should use this feature carefully since its execution ignores any type of
nesting limitation.

The destination point is identified by a label, which is then used as an


argument for the goto instruction. A label is made of a valid identifier
followed by a colon (:).

This instruction does not have a concrete utility in structured or object


oriented programming aside from those that low-level programming fans
may find for it. For example, here is our countdown loop using goto:

33
// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
#include <iostream.h> FIRE!
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!";
return 0;
}

The exit function.
exit is a function defined in cstdlib (stdlib.h) library.

The purpose of exit is to terminate the running program with an specific exit
code. Its prototype is:
void exit (int exit code);

The exit code is used by some operating systems and may be used by


calling programs. By convention, an exit code of 0 means that the program
finished normally and any other value means an error happened.

The selective Structure: switch.


The syntax of the switch instruction is a bit peculiar. Its objective is to check
several possible constant values for an expression, something similar to what we
did at the beginning of this section with the linking of several if and else
if sentences. Its form is the following:
switch (expression) {
  case constant1:
    block of instructions 1
    break;
  case constant2:
    block of instructions 2
    break;
  .
  .
  .
  default:
    default block of instructions
  }

It works in the following way: switch evaluates expression and checks if it is


equivalent to constant1, if it is, it executes block of instructions 1 until it finds
the break keyword, then the program will jump to the end of the switch selective

34
structure.
If expression was not equal to constant1 it will check if expression is equivalent
to constant2. If it is, it will execute block of instructions 2 until it finds
the break keyword.
Finally, if the value of expression has not matched any of the previously specified
constants (you may specify as many case sentences as values you want to check),
the program will execute the instructions included in the default: section, if this
one exists, since it is optional.

Both of the following code fragments are equivalent:

switch example if-else equivalent

switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
break; else {
default: cout << "value of x unknown";
cout << "value of x }
unknown";
}

I have commented before that the syntax of the switch instruction is a bit peculiar.


Notice the inclusion of the break instructions at the end of each block. This is
necessary because if, for example, we did not include it after block of
instructions 1 the program would not jump to the end of the switch selective
block (}) and it would continue executing the rest of the blocks of instructions until
the first appearance of the break instruction or the end of the switch selective
block. This makes it unnecessary to include curly brackets { } in each of the cases,
and it can also be useful to execute the same block of instructions for different
possible values for the expression evaluated. For example:

switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}

35
Notice that switch can only be used to compare an expression with
different constants. Therefore we cannot put variables (case (n*2):) or ranges
(case (1..3):) because they are not valid constants.

If you need to check ranges or values that are not constants use a concatenation
of if and else if sentences.

 Scope Resolution Operator:

The :: (scope resolution) operator is used to get hidden names due to variable
scopes so that you can still use them. The scope resolution operator can be used as
both unary and binary. You can use the unary scope operator if a namespace scope
or global scope name is hidden by a particular declaration of an equivalent name
during a block or class. For example, if you have a global variable of name my_var
and a local variable of name my_var, to access global my_var, you'll need to use
the scope resolution operator.
Example
#include <iostream>  

using namespace std;  

int my_var = 0;

int main(void) {

   int my_var = 0;

   ::my_var = 1;  // set global my_var to 1

   my_var = 2;    // set local my_var to 2

   cout << ::my_var << ", " << my_var;

   return 0;

Output
This will give the output −

1, 2

The declaration of my_var declared in the main function hides the integer named
my_var declared in global namespace scope. The statement ::my_var = 1 accesses
the variable named my_var declared in global namespace scope.
36
You can also use the scope resolution operator to use class names or class member
names. If a class member name is hidden, you can use it by prefixing it with its class
name and the class scope operator. For example,

Example
#include <iostream>

using namespace std;

class X {

   public:

   static int count;

};

int X::count = 10;  // define static data member

int main () {

   int X = 0;   // hides class type X

   cout << X::count << endl;   // use static member of class X

Output
This will give the output −

10

Other information about Scop Resolution operator:

1) To access a global variable when there is a local variable with same name:

// C++ program to show that we can access a global variable


// using scope resolution operator :: when there is a local 
// variable with same name 
#include<iostream> 
using namespace std;
int x;  // Global x

   
int main()

37
{
  int x = 10; // Local x
  cout << "Value of global x is " << ::x;
  cout << "\nValue of local x is " << x;  
  return 0;
}

Output:
Value of global x is 0
Value of local x is 10

2) To define a function outside a class.

// C++ program to show that scope resolution operator :: is used

// to define a function outside a class

#include<iostream> 

using namespace std;

  

class A 

public: 

  

   // Only declaration

   void fun();

};

  

// Definition outside class using ::

void A::fun()

   cout << "fun() called";

 int main()

   A a;

   a.fun();

38
   return 0;

Output:
fun() called

3) To access a class’s static variables.

// C++ program to show that :: can be used to access static

// members when there is a local variable with same name

#include<iostream>

using namespace std;

   

class Test

    static int x;  

public:

    static int y;   

  

    // Local parameter 'a' hides class member

    // 'a', but we can access it using ::

    void func(int x)  

    { 

       // We can access class's static variable

       // even if there is a local variable

       cout << "Value of static x is " << Test::x;

  

       cout << "\nValue of local x is " << x;  

    }

};

   

// In C++, static members must be explicitly defined 

// like this

int Test::x = 1;

int Test::y = 2;

39
   

int main()

    Test obj;

    int x = 3 ;

    obj.func(x);

   

    cout << "\nTest::y = " << Test::y;

  

    return 0;

Output:
Value of static x is 1
Value of local x is 3
Test::y = 2;

4) In case of multiple Inheritance:


If same variable name exists in two ancestor classes, we can use scope resolution operator to
distinguish.

// Use of scope resolution operator in multiple inheritance.

#include<iostream>

using namespace std;

  

class A

protected:

    int x;

public:

    A() { x = 10; }

};

  

class B

40
protected:

    int x;

public:

    B() { x = 20; }

};

  

class C: public A, public B

public:

   void fun()

   {

      cout << "A's x is " << A::x;

      cout << "\nB's x is " << B::x;

   }

};

  

int main()

    C c;

    c.fun();

    return 0;

Output:
A's x is 10
B's x is 20
5) For namespace
If a class having the same name exists inside two namespace we can use the namespace name
with the scope resolution operator to refer that class without any conflicts

// Use of scope resolution operator for namespace.

#include<iostream>

  

  

int main(){

    std::cout << "Hello" << std::endl;

41
  

Here, cout and endl belong to the std namespace.


6) Refer to a class inside another class:
If a class exists inside another class we can use the nesting class to refer the nested class using
the scope resolution operator

// Use of scope resolution class inside another class.

#include<iostream>

using namespace std;

class outside

public:

      int x;

      class inside

      {

      public:

            int x;

            static int y; 

            int foo();

  

      };

};

int outside::inside::y = 5; 

  int main(){

    outside A;

    outside::inside B;

  

 Memory Management Operators:

 Arrays can be used to store multiple homogenous data but there are serious drawbacks of
using arrays.
 Programmer should allocate the memory of an array when they declare it but most of time,
the exact memory needed cannot be determined until runtime.
 The best thing to do in this situation is to declare the array with maximum possible memory
required (declare array with maximum possible size expected) but this wastes memory.

42
 So, To avoid wastage of memory, you can dynamically allocate the memory required during
runtime using new and delete operator.
 
What are memory management operators?
There are two types of memory management operators in C++:

 new
 delete

These two memory management operators are used for allocating and freeing memory blocks in efficient
and convenient ways.
 
New operator:
 The new operator in C++ is used for dynamic storage allocation. This operator can be used to
create object of any type.

General syntax of new operator in C++:


pointer variable = new datatype;

 In the above statement, new is a keyword and the pointer variable is a variable of type datatype.

 For example:
1. int *a = new int;

2. *a = 20;
      or
3.  int *a = new int(20);

 In the above example, the new operator allocates sufficient memory to hold the object of
datatype int and returns a pointer to its starting point.
 the pointer variable a holds the address of memory space allocated.

 delete operator:
 The delete operator in C++ is used for releasing memory space when the object is no longer
needed. 
 Once a new operator is used, it is efficient to use the corresponding delete operator for release
of memory.

General syntax of delete operator in C++:


delete pointer variable;

  Example:

#include <iostream>

43
 void main()
{
//Allocates using new operator memory space in memory for storing a integer
datatype
int *a= new int;
*a=100;
cout << " The Output is:a= " << *a;
//Memory Released using delete operator
delete a; 
}

Output:
The Output is:a=100

In the above program, the statement:


int *a= new a;

Holds memory space in memory for storing a integer datatype.

 Arrays

Arrays in C/C++
An array in C or C++ is a collection of items stored at contiguous memory locations and
elements can be accessed randomly using indices of an array. They are used to store similar
type of elements as in the data type must be the same for all elements. They can be used to store
collection of primitive data types such as int, float, double, char, etc of any particular type. To
add to it, an array in C or C++ can store derived data types such as the structures, pointers etc.

44
Given below is the picturesque representation of an array.
 

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we
want to store a large number of instances, it becomes difficult to manage them with normal
variables. The idea of an array is to represent many instances in one variable.
Array declaration in C/C++:
 

Note: In above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete since
GCC 2.5
There are various ways in which we can declare an array. It can be done by specifying its type
and size, by initializing it or both.
Array declaration by specifying size 

// Array declaration by specifying size

int arr1[10];

45
 
// With recent C/C++ versions, we can also

// declare an array of user specified size

int n = 10;

int arr2[n];

Array declaration by initializing elements

// Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 }

 // Compiler creates an array of size 4.


// above is same as  "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements

// Array declaration by specifying size and initializing

// elements

int arr[6] = { 10, 20, 30, 40 }

 // Compiler creates an array of size 6, initializes first


// 4 elements as specified by user and rest two elements as

// 0. above is same as  "int arr[] = {10, 20, 30, 40, 0, 0}"

Advantages of an Array in C/C++: 


1. Random access of elements using array index.
2. Use of less line of code as it creates a single array of multiple elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C/C++: 
1. Allows a fixed number of elements to be entered which is decided at the time of declaration.
Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to be managed
in accordance with the new memory allocation.
Facts about Array in C/C++: 

 Accessing Array Elements: 


Array elements are accessed by using an integer index. Array index starts with 0 and goes till
size of array minus 1. 
 

46
Example: 

#include <stdio.h>

 
int main()

    int arr[5];

    arr[0] = 5;

    arr[2] = -10;

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

    arr[3] = arr[0];

 
    printf("%d %d %d %d", arr[0],

           arr[1], arr[2], arr[3]);

 
    return 0;

No Index Out of bound Checking: 


There is no index out of bounds checking in C/C++, for example, the following program
compiles fine but may produce unexpected output when run.  

// This C program compiles fine

// as index out of bound

// is not checked in C.

47
#include <stdio.h>

 int main()
{

    int arr[2];

     printf("%d ", arr[3]);


    printf("%d ", arr[-2]);

 
    return 0;

Output
-449684907 4195777
In C, it is not compiler error to initialize an array with more elements than the specified size.
For example, the below program compiles fine and shows just Warning.

#include <stdio.h>

int main()

 
    // Array declaration by initializing it

    // with more elements than specified size.

    int arr[2] = { 10, 20, 30, 40, 50 };

 
    return 0;

Warnings: 
prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:33: note: (near initialization for 'arr')

48
 Note: The program won’t compile in C++. If we save the above program as a .cpp, the
program generates compiler error “error: too many initializers for ‘int [2]'”. 
 
The elements are stored at contiguous memory locations 
Example: 

// C program to demonstrate that

// array elements are stored

// contiguous locations

 
#include <stdio.h>

int main()

    // an array of 10 integers. 

    // If arr[0] is stored at

    // address x, then arr[1] is

    // stored at x + sizeof(int)

    // arr[2] is stored at x +

    // sizeof(int) + sizeof(int)

    // and so on.

    int arr[5], i;

 
    printf("Size of integer in this compiler is %lu\n",

           sizeof(int));

 
    for (i = 0; i < 5; i++)

        // The use of '&' before a variable name, yields

        // address of variable.

        printf("Address arr[%d] is %p\n", i, &arr[i]);

 
    return 0;

Output
Size of integer in this compiler is 4
Address arr[0] is 0x7ffe75c32210
Address arr[1] is 0x7ffe75c32214
Address arr[2] is 0x7ffe75c32218

49
Address arr[3] is 0x7ffe75c3221c
Address arr[4] is 0x7ffe75c32220

Another way to traverse the array

#include<bits/stdc++.h>

using namespace std;

 
int main()

    int arr[6]={11,12,13,14,15,16};

    // Way -1

    for(int i=0;i<6;i++)

        cout<<arr[i]<<" ";

   

  cout<<endl;

      // Way 2

    cout<<"By Other Method:"<<endl;

    for(int i=0;i<6;i++)  

        cout<<i[arr]<<" ";

   

    cout<<endl;

     return 0;
}

 
// Contributed by Akshay Pawar ( Username - akshaypawar4)

Output
11 12 13 14 15 16
By Other Method:
11 12 13 14 15 16

 String

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double


quotes:

50
Example 1

#include <iostream>
#include <string>
using namespace std;

int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}

Example 2

#include <iostream>

using namespace std;

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

Sr.No Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0

51
if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

#include <iostream>
#include <cstring>

using namespace std;

int main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

getch();
}

When the above code is compiled and executed, it produces result something as
follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

 Structures in c++
Structure is a compound data type that contains different variables of different types.
For example, you want to store Student details like student name, student roll num,
student age. You have two ways to do it, one way is to create different variables for
each data, but the downfall of this approach is that if you want to store the details of

52
multiple students, in that case it is not feasible to create separate set of variables for
each student.

The second and best way of doing it by creating a structure like this:

struct Student
{
char stuName[30];
int stuRollNo;
int stuAge;
};
Now these three members combined will act like a separate variable and you can
create structure variable like this:

structure_name variable_name
So if you want to hold the information of two students using this structure then you
can do it like this:

Student s1, s2;


Then I can access the members of Student structure like this:

//Assigning name to first student


s1.stuName = "Ajeet";
//Assigning age to the second student
s2.stuAddr = 22;

Similarly I can set and get the values of other data members of the structure for
every student. Lets see a complete example to put this up all together:

Structure Example in C++

#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
 cout<<"ENter Student Roll No: ";
  cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;

53
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
return 0;
}
Output:

Enter Student Name: Negan


ENter Student Roll No: 4101003
Enter Student Age: 22
Student Record:
Name: Negan
Roll No: 4101003
Age: 22

The Syntax Of Structure

1. struct structure_name  
2. {  
3.      // member declarations.  
4. }   

Example:
1. struct Student  
2. {  
3.     char name[20];  
4.      int id;  
5.      int age;  
6. }  

1. #include <iostream>    
2. using namespace std;    
3.  struct Rectangle    {      
4.    int width, height;      
5.   Rectangle(int w, int h)      
6.     {      
7.         width = w;      
8.         height = h;      
9.     }      
10.   void areaOfRectangle() {       
11.     cout<<"Area of Rectangle is: "<<(width*height); }      
12.  };      
13. int main(void) {    
14.     struct Rectangle rec=Rectangle(4,6);    
15.     rec.areaOfRectangle();    

54
16.    return 0;    
17. }    

Output:

Area of Rectangle is: 24

55

You might also like