You are on page 1of 107

Basic programming elements and concepts, Problem Solving & Program Design, Components of

a programming language, Program development and execution, Program structure, Data types
and variable declarations, Standard I/O streams, and statements, Control structures, Standard
library functions, User defined functions and parameter passing, Arrays, pointers, and strings,
Structures, unions, and bit manipulation operators

Contents
1 Computer programming language...........................................................................................1
1.1 Language Types................................................................................................................1
1.1.1 Low level...................................................................................................................1
1.1.2 High level...................................................................................................................1
2 Elements of Programming.......................................................................................................2
2.1 5 Basic elements of Programming....................................................................................2
2.1.1 Variables:...................................................................................................................2
2.1.2 Loops:........................................................................................................................2
2.1.3 Conditionals:..............................................................................................................2
2.1.4 Input/output:..............................................................................................................3
2.1.5 Subroutines and functions:........................................................................................3
3 Programming language components........................................................................................3
3.1 Syntax:..............................................................................................................................3
3.2 Semantics:.........................................................................................................................3
3.3 statements:.........................................................................................................................3
3.4 variables:...........................................................................................................................4
4 Problem solving and program design.....................................................................................4
4.1 Problem solving................................................................................................................4
4.2 Design an Algorithm If problem was broken into subproblems.......................................4
4.3 Write the Code Once the algorithm is designed and correctness verified........................4
5 Program structure of C language.............................................................................................5
5.1 Following is the basic structure of a program...................................................................5
5.2 Hello World Program in C++............................................................................................5
5.2.1 Comments..................................................................................................................5
5.2.2 #include<iostream>...................................................................................................6
5.2.3 Using namespace std;................................................................................................6
5.2.4 int main()...................................................................................................................6
5.2.5 cout << “Hello World!”;............................................................................................6
6 Data types and Variable declaration in C++............................................................................7
6.1 Built in data types.............................................................................................................7
6.1.1 char:...........................................................................................................................7
6.1.2 int:..............................................................................................................................7
6.1.3 float:...........................................................................................................................7
6.1.4 double:.......................................................................................................................8
6.1.5 bool:...........................................................................................................................8
6.1.6 wchar_t:.....................................................................................................................8
6.2 User-defined data types.....................................................................................................8
6.2.1 Derived data types in C++.........................................................................................8
7 Variables in C++......................................................................................................................8
7.1 Syntax of declaring a variable in C++..............................................................................8
7.2 Types of variables.............................................................................................................9
7.2.1 int: These type of variables holds integer value........................................................9
7.2.2 char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc...........................................9
7.2.3 bool: holds boolean value true or false......................................................................9
7.2.4 double: double-precision floating point value...........................................................9
7.2.5 float: Single-precision floating point value...............................................................9
7.3 Types of variables based on their scope............................................................................9
7.3.1 Global Variable..........................................................................................................9
7.3.2 Global variable example..........................................................................................10
7.3.3 Local variable..........................................................................................................10
7.3.4 Local variable example............................................................................................10
7.3.5 Can global and local variable have same name in C++?.........................................11
8 Standard I/O streams in c++..................................................................................................11
8.1 Streams............................................................................................................................12
8.2 Standard streams in C++.................................................................................................13
9 Control Statements.................................................................................................................14
9.1 If else Statement in C++..................................................................................................14
9.2 Switch Case statement in C++ with example..................................................................23
9.2.1 Example of Switch Case..........................................................................................24
9.2.2 Switch Case Flow Diagram.....................................................................................25
9.2.3 Break statement in Switch Case..............................................................................25
9.2.4 Why didn’t I use break statement after default?......................................................27
9.2.5 Important Notes.......................................................................................................28
9.3 LOOP:.............................................................................................................................29
9.3.1 For loop in C++ with example.................................................................................29
9.3.2 Syntax of for loop....................................................................................................29
9.3.3 Flow of Execution of the for Loop..........................................................................29
9.3.4 Example of a Simple For loop in C++.....................................................................30
9.3.5 Infinite for loop in C++...........................................................................................30
9.3.6 Example: display elements of array using for loop.................................................31
9.4 while-loop:......................................................................................................................31
9.4.1 While loop in C++ with example.............................................................................32
9.4.2 Syntax of while loop................................................................................................32
9.4.3 How while Loop works?..........................................................................................32
9.4.4 Flow Diagram of While loop...................................................................................33
9.4.5 While Loop example in C++...................................................................................33
9.4.6 Infinite While loop...................................................................................................34
9.4.7 Example: Displaying the elements of array using while loop.................................34
9.5 Do-while Loop................................................................................................................34
9.5.1 do-while loop in C++ with example........................................................................34
9.5.2 Syntax of do-while loop...........................................................................................35
9.5.3 How do-while loop works?......................................................................................35
9.5.4 do-while loop example in C++................................................................................35
9.5.5 Example: Displaying array elements using do-while loop......................................36
9.6 Continue Statement.........................................................................................................37
9.6.1 Continue Statement in C++ with example...............................................................37
9.6.2 Syntax of continue statement...................................................................................37
9.6.3 Example: continue statement inside for loop...........................................................37
9.6.4 Flow Diagram of Continue Statement.....................................................................38
9.6.5 Example: Use of continue in While loop.................................................................38
9.6.6 Example of continue in do-While loop....................................................................39
9.7 Break statement:..............................................................................................................39
9.7.1 Break statement in C++ with example.....................................................................39
9.7.2 Syntax of break statement........................................................................................39
9.7.3 break statement flow diagram..................................................................................40
9.7.4 Example – Use of break statement in a while loop.................................................40
9.7.5 Example: break statement in for loop......................................................................41
9.7.6 Example: break statement in Switch Case...............................................................41
9.8 Go to statement...............................................................................................................42
9.8.1 goto statement in C++ with example.......................................................................42
9.8.2 Program structure:...................................................................................................42
9.8.3 Example of goto statement in C++..........................................................................42
10 Functions in C++...................................................................................................................43
10.1 Syntax of Function......................................................................................................43
10.2 A simple function example..........................................................................................43
10.3 Function Declaration:..................................................................................................44
10.3.1 syntax of function declaration:................................................................................44
10.4 Function definition:.....................................................................................................45
10.4.1 syntax of function definition:...................................................................................45
10.5 Types of function.........................................................................................................45
10.5.1 1) Build-it functions.................................................................................................45
10.5.2 Example: C++ built-in function example................................................................46
10.6 2) User-defined functions............................................................................................46
10.7 User-defined functions................................................................................................46
10.8 Parameters Pass:..........................................................................................................47
10.8.1 Parameter Passing Techniques in C/C++................................................................47
10.8.2 Terminology............................................................................................................47
10.8.3 Important methods of Parameter Passing................................................................48
10.8.4 Pass by reference(aliasing) :....................................................................................49
10.8.5 Other methods of Parameter Passing.......................................................................49
10.9 C++ Recursion with example......................................................................................50
10.9.1 C++ recursion example: Factorial...........................................................................51
10.9.2 Base condition.........................................................................................................51
10.9.3 Direct recursion vs indirect recursion......................................................................51
10.9.4 Indirect Recursion Example in C++........................................................................52
11 Arrays....................................................................................................................................52
11.1 Arrays in C++..............................................................................................................52
11.2 Declaring an array in C++...........................................................................................53
11.3 Accessing Array Elements..........................................................................................53
11.4 Multidimensional Arrays in C++................................................................................55
11.5 A two dimensional array:............................................................................................55
11.6 A three dimensional array:..........................................................................................55
11.6.1 Two dimensional array............................................................................................55
11.6.2 How to declare a two dimensional array?................................................................55
11.6.3 Three dimensional array..........................................................................................56
11.6.4 Declaring a three dimensional array:.......................................................................56
11.7 Passing Array to Function in C++...............................................................................57
11.7.1 Example: Passing arrays to a function.....................................................................57
11.7.2 Example 2: Passing multidimensional array to function.........................................58
12 Strings:...................................................................................................................................59
12.1 Strings in C++.............................................................................................................59
12.2 1) Array of Characters – Also known as C Strings.....................................................59
12.3 Example 2: Getting user input as string......................................................................60
12.4 Example 3: Correct way of capturing user input string using cin.get.........................60
12.5 Drawback of this method............................................................................................61
12.5.1 String object in C++................................................................................................61
13 Pointers..................................................................................................................................62
13.1 Pointers in C++............................................................................................................62
13.2 Syntax of pointer.........................................................................................................62
13.3 How to Use Pointers?..................................................................................................63
13.4 NULL Pointers............................................................................................................63
13.5 Pointers in Detail.......................................................................................................64
13.6 How to declare a pointer?............................................................................................65
13.7 Assignment..................................................................................................................65
13.8 How to use it?..............................................................................................................65
13.9 Example of Pointer......................................................................................................66
13.10 Pointer and arrays........................................................................................................66
13.11 Example: Traversing the array using Pointers............................................................67
13.12 How to increment pointer address and pointer’s value?.............................................67
13.13 C++ ‘this’ Pointer........................................................................................................68
13.14 C++ Example: this pointer..........................................................................................68
13.15 Example 2: function chaining calls using this pointer................................................69
14 Structures, Union in C++.......................................................................................................69
14.1 Syntax for declaring union..........................................................................................70
14.2 Accessing the union members.....................................................................................70
14.3 Syntax for creating object of union.............................................................................70
14.4 Example for creating object & accessing union members..........................................71
14.5 Example of comparing size of union and structure.....................................................74
15 Structure in C++....................................................................................................................75
15.1 Syntax for declaring structure.....................................................................................76
15.2 Example for declaring structure..................................................................................76
15.3 Accessing the structure members................................................................................76
15.4 Syntax for creating object............................................................................................77
15.5 Example for creating object & accessing structure members.....................................77
15.6 Initialization of structure.............................................................................................78
15.7 Example for declaring & initializing structure at same time.......................................79
15.8 Array of Structure........................................................................................................80
15.9 Syntax for declaring structure array............................................................................80
15.10 Example for declaring structure array.........................................................................80
15.11 Array within Structure.................................................................................................83
15.12 Syntax for array within structure.................................................................................83
15.13 Example for array within structure..............................................................................83
15.14 Nested Structure in C++..............................................................................................85
15.15 Syntax for structure within structure or nested structure............................................85
15.16 Example for structure within structure or nested structure.........................................86
15.17 Structure and Function in C++....................................................................................88
15.18 Passing structure as function argument.......................................................................88
15.19 Passing Structure by Value..........................................................................................89
15.20 Example for passing structure object by value............................................................89
15.21 Passing Structure by Reference...................................................................................90
15.22 Example for passing structure object by reference.....................................................90
15.23 Function Returning Structure......................................................................................91
15.24 Example for passing structure object by reference.....................................................92
16 Bit manipulation....................................................................................................................94
16.1 Bits manipulation........................................................................................................94
16.2 Bitwise Operators:.......................................................................................................94
16.3 Bit Fields.....................................................................................................................97
16.4 (Important tactics).......................................................................................................97
https://www.tutorialspoint.com/computer_programming/
computer_programming_overview.html

1 Computer programming language


 Computer programming language, any of various languages for expressing a set of
detailed instructions for a digital computer.
 Such instructions can be executed directly when they are in the computer manufacturer-
specific numerical form known as machine language, after a simple substitution process
when expressed in a corresponding assembly language, or after translation from some
“higher-level” language. Although there are many computer languages, relatively few are
widely used.

1.1 Language Types

1.1.1 Low level


o Machine languages
 A machine language consists of the numeric codes for the operations that a
particular computer can execute directly.
 The codes are strings of 0s and 1s, or binary digits (“bits”), which are
frequently converted both from and to hexadecimal (base 16) for human
viewing and modification.
 Machine language instructions typically use some bits to represent
operations, such as addition, and some to represent operands, or perhaps
the location of the next instruction.
 Machine language is difficult to read and write, since it does not resemble
conventional mathematical notation or human language, and its codes vary
from computer to computer.
o Assembly languages
 Assembly language is one level above machine language.
 It uses short mnemonic codes for instructions and allows the programmer
to introduce names for blocks of memory that hold data.
 One might thus write “add pay, total” instead of “0110101100101000” for
an instruction that adds two numbers.

1.1.2 High level


o C,C++
o Java
o Cobol
o Fortran
o C#

2 Elements of Programming
 Process to develop various sets of instruction is known as programming.
 To develop any instruction there are some elements are needed or we can essentially
present in all language.
 So any programming language is made up of 5 basic elements of the instructions

3 5 Basic elements of Programming


3.1.1 Variables: 

 Variables in programming tell how the data is represented which can be range from very
simple value to complex one.
 The value they contain can be change depending on condition.
 As we know program consist of instructions that tell the computer to do things and data
the program use when it is running.
 Data is constant with the fixed values or variable.
 They can hold a very simplex value like an age of the person to something very complex
like a student track record of his performance of whole year.

3.1.2 Loops:

 We can define loop as a sequence of instructions that are repeated continuously till a
certain condition is not satisfied.
 How a loop start understand this first a certain process is done, to get any data and
changing it after that applied condition on the loop is checked whether counter reached
to prescribed number or not.
o Basically a loop carry out execution of a group of instruction of commands a
certain number of times.
o There is also a concept of infinite loop which is also termed as endless loop is a
piece of code that lack from functional exit and goes to repeat indefinitely.

3.1.3 Conditionals: 

 Conditionals specify the execution of the statements depending on the whether condition
is satisfied or not.
 Basically it refers to an action that only fulfill when the applied condition on instructions
satisfied. They are one of the most important components of the programming language
because they give freedom to program to act differently every time when it execute that
depends on input to the instructions.

3.1.4 Input/output:

 The element of computer programming that allows interaction of the program with the
external entities.
o Example of input/output element are printing something out to the terminal
screen, capturing some text that user input on the keyboard and can be include
reading and writing files.
o Let’s take a language example to understand the concept of input and output. C+
+ use streams to perform input and output operation in sequential media in terms
of screen, the keyboard or a file. We can define stream as an entity that can insert
or extract characters and there is no need to know details about the media
associated to the stream or any of its internal specification. We need to know
about streams is that they are source or destination of characters and the
characters are accepted sequentially.

3.1.5 Subroutines and functions: 

 The element of the programming allows a programmer to use snippet of code into one
location which can be used over and over again.
 The primary purpose of the functions is to take arguments in numbers of values and do
some calculation on them after that return a single result.
 Functions are required where you need to do complicated calculations and the result of
that may or may not be used subsequently used in an expression.
 If we talk about subroutines that return several results. Where calls to subroutines cannot
be placed in an expression whether it is in the main program where subroutine is
activated by using CALL statement which include the list of inputs and outputs that
enclosed in the open and closed parenthesis and they are called the arguments of the
subroutines.
 There are some of the rules follow by both to define name like less than six letters and
start with the letters. The name should be different that used for variables and functions.

Few other Programming language components


Syntax (Grammar rules for defining legal statements )

Semantics: (What things mean – what do they compute?)

Statements (Instructions that say what to do – compute values, make decisions, repeat sequences
of operations)

variables: (places to hold data in memory while program is running – numbers, text, ...)
 most languages are higher-level and more expressive than the assembly language for the
toy machine –
 statements are much richer, more varied, more expressive
 variables are much richer, more varied –
 grammar rules are more complicated –
 semantics are more complicated
 but it's basically the same idea Why study / use Javascript?

4 Problem solving and program design

4.1 Problem solving

 Problem Solving Programming is a process of solving the problems


 Problem solving techniques
o Analyze the problem
oOutline the problem requirements
o Design steps (algorithm) to solve the problem
 Algorithm:
 It is a process of Step-by-step problem-solving
 Solution achieved in finite amount of time
 Problem Solving Process
o Step 1 - Analyze the problem
 Outline the problem and its requirements
 Design steps (algorithm) to solve the problem
o Step 2 - Implement the algorithm
 Implement the algorithm in code
 Verify that the algorithm works
o Step 3 - Maintenance
 Use and modify the program if the problem domain changes

4.2 Design an Algorithm If problem was broken into sub-problems


 Design algorithms for each sub problem
 Check the correctness of algorithm
 Can test using sample data
 Some mathematical analysis might be required
4.3 Write the Code Once the algorithm is designed and correctness verified
 Write the equivalent code in high-level language
 Enter the program using text editor

5 Program structure of C language

5.1 Following is the basic structure of a program.


In this guide we will write and understand the first program in C++ programming. We are
writing a simple C++ program that prints “Hello World!” message. Lets see the program first
and then we will discuss each and every part of it in detail.

5.2 Hello World Program in C++


/*
* Multiple line
* comment
*/
#include<iostream>

//Single line comment


using namespace std;

//This is where the execution of program begins


int main()
{
// displays Hello World! on screen
cout<<"Hello World!";

return 0;
}
Output:

Hello World!
Let’s discuss each and every part of the above program.

5.2.1 Comments 
You can see two types of comments in the above program

// This is a single line comment


/* This is a multiple line comment
* suitable for long comments
*/
 Comments as the names suggests are just a text written by programmer during code
development.
 Comment doesn’t affect your program logic in any way, you can write whatever you
want in comments but it should be related to the code and have some meaning
 so that when someone else look into your code, the person should understand what you
did in the code by just reading your comment.

For example:

/* This function adds two integer numbers


* and returns the result as an integer value
*/
int sum(int num1, int num2) {
return num1+num2;
}
Now if someone reads my comment he or she can understand what I did there just by reading my
comment. This improves readability of your code and when you are working on a project with
your team mates, this becomes essential aspect.

5.2.2 #include<iostream> 
 This statement tells the compiler to include iostream file.
 This file contains pre-defined input/output functions that we can use in our program.

5.2.3 Using namespace std;


 A namespace is like a region, where we have functions, variables etc and their scope is
limited to that particular region.
 Here std is a namespace name, this tells the compiler to look into that particular region
for all the variables, functions, .

5.2.4 Int main() 


 As the name suggests this is the main function of a program
 the execution of program begins with this function
 the int here is the return type which indicates to the compiler that this function will return
a integer value. That is the main reason we have a return 0 statement at the end of main
function.

5.2.5 cout << “Hello World!”; 


 The cout object belongs to the iostream file and the purpose of this object is to display the
content between double quotes as it is on the screen. This object can also display the
value of variables on screen.
6. return 0; – This statement returns value 0 from the main() function which indicates that the
execution of main function is successful. The value 1 represents failed execution

6 Data types and Variable declaration in C++


 Data types define the type of data a variable can hold, for example an integer
variable can hold integer data, a character type variable can hold character data
etc.
 Data types in C++ are categorized in three groups: Built-in, user-
defined and Derived.

6.1 Built in data types

6.1.1 char:
For characters. Size 1 byte.

char ch = 'A';
6.1.2 int:
For integers. Size 2 bytes.

int num = 100;


6.1.3 float:
For single precision floating point. Size 4 bytes.

float num = 123.78987;


6.1.4 double:
For double precision floating point. Size 8 bytes.

double num = 10098.98899;


6.1.5 bool:
For booleans, true or false.

bool b = true;
6.1.6 wchar_t:
Wide Character. This should be avoided because its size is implementation defined and not
reliable.

6.2 User-defined data types


We have three types of user-defined data types in C++
1. Struct
2. Union
3. Enum

6.2.1 Derived data types in C++


We have three types of derived-defined data types in C++
1. Array
2. Function
3. Pointer

7 Variables in C++
 A variable is a name which is associated with a value that can be changed.
 For example when I write int num=20; here variable name is num which is associated
with value 20, int is a data type that represents that this variable can hold integer values.

7.1 Syntax of declaring a variable in C++


data type variable1_name = value1, variable2_name = value2;
For example:

int num1=20, num2=100;


We can also write it like this:
int num1,num2;
num1=20;
num2=100;

7.2 Types of variables


Variables can be categorized based on their data type. For example, in the above example we
have seen integer types variables. Following are the types of variables available in C++.

7.2.1 int: These type of variables holds integer value.

7.2.2 char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.

7.2.3 bool: holds boolean value true or false.

7.2.4 double: double-precision floating point value.

7.2.5 float: Single-precision floating point value.

7.3 Types of variables based on their scope


 What is scope first. When we discussed the Hello World Program, we have seen the curly
braces in the program like this:

int main {

//Some code

}
 Any variable declared inside these curly braces have scope limited within these curly
braces, if you declare a variable in main() function and try to use that variable outside
main() function then you will get compilation error.

Now that we have understood what is scope. Lets move on to the types of variables based on the
scope.

1. Global variable
2. Local variable

7.3.1 Global Variable


 A variable declared outside of any function (including main as well) is called global
variable. Global variables have their scope throughout the program, they can be accessed
anywhere in the program, in the main, in the user defined function, anywhere.
Lets take an example to understand it:

7.3.2 Global variable example


Here we have a global variable myVar, that is declared outside of main. We have accessed the
variable twice in the main() function without any issues.

#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:

Value of myVar: A
Value of myVar: Z
7.3.3 Local variable
 Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope limited
inside those braces.

7.3.4 Local variable example


#include <iostream>
using namespace std;

char myFuncn() {
// This is a local variable
char myVar = 'A';
}
Int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Compile time error, because we are trying to access the variable myVar outside of its scope. The
scope of myVar is limited to the body of function myFuncn(), inside those braces.
7.3.5 Can global and local variable have same name in C++?
Lets see an example having same name global and local variable.

#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0;
}
Output:

Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
As you can see that when I changed the value of myVar in the main function, it only changed the
value of global variable myVar because local variable myVar scope is limited to the
function myFuncn().

8 Standard I/O streams in C++


Input and output functionality is not defined as part of the core C++ language, but rather is
provided through the C++ standard library (and thus resides in the std namespace). You included
the iostream library header and made use of the CIN and COUT objects to do simple I/O.

The iostream library

When you include the iostream header, you gain access to a whole hierarchy of classes
responsible for providing I/O functionality (including one class that is actually named iostream).
The class hierarchy for the non-file-I/O classes looks like this:
The first thing you may notice about this hierarchy is that it uses multiple inheritance (that thing
we told you to avoid if at all possible). However, the iostream library has been designed and
extensively tested in order to avoid any of the typical multiple inheritance problems, so you can
use it freely without worrying.

8.1 Streams

 The second thing you may notice is that the word “stream” is used an awful lot.
At its most basic, I/O in C++ is implemented with streams. Abstractly, a stream is
just a sequence of bytes that can be accessed sequentially. Over time, a stream
may produce or consume potentially unlimited amounts of data.

 Typically we deal with two different types of streams. Input streams are used to
hold input from a data producer, such as a keyboard, a file, or a network. For
example, the user may press a key on the keyboard while the program is currently
not expecting any input. Rather than ignore the users key press, the data is put
into an input stream, where it will wait until the program is ready for it.

 Conversely, output streams are used to hold output for a particular data consumer,
such as a monitor, a file, or a printer. When writing data to an output device, the
device may not be ready to accept that data yet -- for example, the printer may
still be warming up when the program writes data to its output stream. The data
will sit in the output stream until the printer begins consuming it.

Some devices, such as files and networks, are capable of being both input and output sources.

 The nice thing about streams is the programmer only has to learn how to interact
with the streams in order to read and write data to many different kinds of
devices. The details about how the stream interfaces with the actual devices they
are hooked up to is left up to the environment or operating system.

Although the IOS class is generally derived from ios_base, IOS is typically the most base class
you will be working directly with. The ios class defines a bunch of stuff that is common to both
input and output streams. We’ll deal with this stuff in a future lesson.

The istream class is the primary class used when dealing with input streams. With input streams,
the extraction operator (>>) is used to remove values from the stream. This makes sense: when
the user presses a key on the keyboard, the key code is placed in an input stream. Your program
then extracts the value from the stream so it can be used.

The ostream class is the primary class used when dealing with output streams. With output
streams, the insertion operator (<<) is used to put values in the stream. This also makes sense:
you insert your values into the stream, and the data consumer (eg. monitor) uses them.

The iostream class can handle both input and output, allowing bidirectional I/O.

Finally, there are a bunch of classes that end in “_withassign”. These stream classes are derived
from istream, ostream, and iostream (respectively) with an assignment operator defined, allowing
you to assign one stream to another. In most cases, you won’t be dealing with these classes
directly.

8.2 Standard streams in C++

A standard stream is a pre-connected stream provided to a computer program by its environment.


C++ comes with four predefined standard stream objects that have already been set up for your
use. The first three, you have seen before:

cin -- an istream_withassign class tied to the standard input (typically the keyboard)

cout -- an ostream_withassign class tied to the standard output (typically the monitor)
cerr -- an ostream_withassign class tied to the standard error (typically the monitor), providing
unbuffered output

clog -- an ostream_withassign class tied to the standard error (typically the monitor), providing
buffered output

Unbuffered output is typically handled immediately, whereas buffered output is typically stored
and written out as a block. Because clog isn’t used very often, it is often omitted from the list of
standard streams.

9 Control Statements
 If, if..else-if statement
  Switch Case in C++
 For loop
  while loop
  do while loop
 Continue statement
 Break statement
 goto statement

9.1 If else Statement in C++


Sometimes we need to execute a block of statements only when a particular condition is met or
not met. This is called decision making, as we are executing a certain code after making a
decision in the program logic. For decision making in C++, we have four types of control
statements (or control structures), which are as follows:

 if statement

 nested if statement

 if-else statement

 if-else-if statement

 If statement in C++

If statement consists a condition, followed by statement or a set of statements as shown below:


 Syntax:

if(condition){

Statement(s);

The statements inside if parenthesis (usually referred as if body) gets executed only when the
given condition is true. If the condition is false then the statements inside if body are completely
ignored.

 Flow diagram of If statement


 Example of if statement

#include <iostream>

using namespace std;

int main(){

int num=70;

if( num < 100 ){

/* This cout statement will only execute,

* if the above condition is true

*/

cout<<"number is less than 100";

if(num > 100){

/* This cout statement will only execute,

* if the above condition is true

*/

cout<<"number is greater than 100";

return 0;

Output:

number is less than 100


 Nested if statement in C++

When there is an if statement inside another if statement then it is called the nested if statement.

 The structure of nested if looks like this:

if(condition_1) {

Statement1(s);

if(condition_2) {

Statement2(s);

Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the
conditions( condition_1 and condition_2) are true.

 Example of Nested if statement


 #include <iostream>
 using namespace std;
 int main(){
 int num=90;
 /* Nested if statement. An if statement
 inside another if body
 */
 if( num < 100 ){
 cout<<"number is less than 100"<<endl;
 if(num > 50){
 cout<<"number is greater than 50";
 }
 }
 return 0;
 }
 Output:
 number is less than 100
 number is greater than 50

 If else statement in C++

Sometimes you have a condition and you want to execute a block of code if condition is true and
execute another piece of code if the same condition is false. This can be achieved in C++ using
if-else statement.

 This is how an if-else statement looks:

if(condition) {

Statement(s);

else {

Statement(s);

The statements inside “if” would execute if the condition is true, and the statements inside “else”
would execute if the condition is false.

 Flow diagram of if-else


If else flow diagram

 Example of if-else statement

#include <iostream>

using namespace std;

int main(){

int num=66;

if( num < 50 ){

//This would run if above condition is true

cout<<"num is less than 50";

else {
//This would run if above condition is false

cout<<"num is greater than or equal 50";

return 0;

Output:

num is greater than or equal 50

 if-else-if Statement in C++

if-else-if statement is used when we need to check multiple conditions. In this control structure
we have only one “if” and one “else”, however we can have multiple “else if” blocks.

 This is how it looks:

if(condition_1) {

/*if condition_1 is true execute this*/

statement(s);

else if(condition_2) {

/* execute this if condition_1 is not met and

* condition_2 is met

*/

statement(s);
}

else if(condition_3) {

/* execute this if condition_1 & condition_2 are

* not met and condition_3 is met

*/

statement(s);

else {

/* if none of the condition is true

* then these statements gets executed

*/

statement(s);

Note: The most important point to note here is that in if-else-if, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is
met then the statements inside “else” gets executed.

 Example of if-else-if

#include <iostream>

using namespace std;

int main(){
int num;

cout<<"Enter an integer number between 1 & 99999: ";

cin>>num;

if(num <100 && num>=1) {

cout<<"Its a two digit number";

else if(num <1000 && num>=100) {

cout<<"Its a three digit number";

else if(num <10000 && num>=1000) {

cout<<"Its a four digit number";

else if(num <100000 && num>=10000) {

cout<<"Its a five digit number";

else {

cout<<"number is not between 1 & 99999";

return 0;

}
Output:

Enter an integer number between 1 & 99999: 8976

Its a four digit number

9.2 Switch Case statement in C++ with example

 Switch case statement is used when we have multiple conditions and we need to perform
different action based on the condition.
 When we have multiple conditions and we need to execute a block of statements when a
particular condition is satisfied. In such case either we can use lengthy if. Else-if
statement or switch case.
 The problem with lengthy if..else-if is that it becomes complex when we have several
conditions. The switch case is a clean and efficient method of handling such scenarios.

 The syntax of Switch case statement:

switch (variable or an integer expression)

case constant:

//C++ code

case constant:

//C++ code

default:

//C++ code

;
}

Switch Case statement is mostly used with break statement even though the break statement is
optional. We will first see an example without break statement and then we will discuss switch
case with break

9.2.1 Example of Switch Case

#include <iostream>

using namespace std;

int main(){

int num=5;

switch(num+2) {

case 1:

cout<<"Case1: Value is: "<<num<<endl;

case 2:

cout<<"Case2: Value is: "<<num<<endl;

case 3:

cout<<"Case3: Value is: "<<num<<endl;

default:

cout<<"Default: Value is: "<<num<<endl;

return 0;

}
Output:

Default: Value is: 5

Explanation: In switch I gave an expression, you can give variable as well. I gave the expression
num+2, where num value is 5 and after addition the expression resulted 7. Since there is no case
defined with value 4 the default case got executed.

9.2.2 Switch Case Flow Diagram

It evaluates the value of expression or variable (based on whatever is given inside switch braces),
then based on the outcome it executes the corresponding case.

9.2.3 Break statement in Switch Case

Before we discuss about break statement, Let’s see what happens when we don’t use break
statement in switch case. See the example below:

#include <iostream>

using namespace std;

int main(){
int i=2;

switch(i) {

case 1: cout<<"Case1 "<<endl;

case 2: cout<<"Case2 "<<endl;

case 3: cout<<"Case3 "<<endl;

case 4: cout<<"Case4 "<<endl;

default: cout<<"Default "<<endl;

return 0;

Output:

Case2

Case3

Case4

Default

In the above program, we have the variable i inside switch braces, which means whatever the
value of variable i is, the corresponding case block gets executed. We have passed integer value
2 to the switch, so the control switched to the case 2, however we don’t have break statement
after the case 2 that caused the flow to continue to the subsequent cases till the end. However this
is not what we wanted, we wanted to execute the right case block and ignore rest blocks. The
solution to this issue is to use the break statement in after every case block.

Break statements are used when you want your program-flow to come out of the switch body.
Whenever a break statement is encountered in the switch body, the execution flow would
directly come out of the switch, ignoring rest of the cases. This is why you must end each case
block with the break statement.
Let’s take the same example but this time with break statement.

#include <iostream>

using namespace std;

int main(){

int i=2;

switch(i) {

case 1:

cout<<"Case1 "<<endl;

break;

case 2:

cout<<"Case2 "<<endl;

break;

case 3:

cout<<"Case3 "<<endl;

break;

case 4:

cout<<"Case4 "<<endl;

break;

default:

cout<<"Default "<<endl;
}

return 0;

Output:

Case2

Now you can see that only case 2 got executed, rest of the subsequent cases were ignored.

9.2.4 Why didn’t I use break statement after default?

The control would itself come out of the switch after default so I didn’t use break statement after
it, however if you want you can use it, there is no harm in doing that.

9.2.5 Important Notes

1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after
case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them
in any order based on the requirement.

2) You can also use characters in switch case. for example –

#include <iostream>

using namespace std;

int main(){

char ch='b';

switch(ch) {

case 'd': cout<<"Case1 ";

break;

case 'b': cout<<"Case2 ";


break;

case 'x': cout<<"Case3 ";

break;

case 'y': cout<<"Case4 ";

break;

default: cout<<"Default ";

return 0;

3) Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.

9.3 LOOP:
Repeat again and again until getting the desire result.

 Do loop
 Do while loop
 For loop

9.3.1 For loop in C++ with example


A loop is used for executing a block of statements repeatedly until a particular condition is
satisfied. For example, when you are displaying number from 1 to 100 you may want set the
value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration.

9.3.2 Syntax of for loop


for(initialization; condition ; increment/decrement)
{
C++ statement(s);
}
9.3.3 Flow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement is about to be
executed. We call this the control flow, or the flow of execution of the program.

 First step: In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
 Second step: Condition in for loop is evaluated on each loop iteration, if the condition is
true then the statements inside for for loop body gets executed. Once the condition
returns false, the statements in for loop does not execute and the control gets transferred
to the next statement in the program after for loop.
 Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
 Fourth step: After third step, the control jumps to second step and condition is re-
evaluated.

The steps from second to fourth repeats until the loop condition returns false.

9.3.4 Example of a Simple For loop in C++


Here in the loop initialization part I have set the value of variable i to 1, condition is i<=6 and on
each loop iteration the value of i increments by 1.

#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Output:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
9.3.5 Infinite for loop in C++
A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by
mistake. When you set the condition in for loop in such a way that it never return false, it
becomes infinite loop.

For example:

#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
This is an infinite loop as we are incrementing the value of i so it would always satisfy the
condition i>=1, the condition would never return false.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}
9.3.6 Example: display elements of array using for loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,9,56,99, 202};
/* We have set the value of variable i
* to 0 as the array index starts with 0
* which means the first element of array
* starts with zero index.
*/
for(int i=0; i<5; i++){
cout<<arr[i]<<endl;
}
return 0;
}
Output:

21
9
56
99
202

9.4 while-loop:

9.4.1 While loop in C++ with example


As discussed earlier, loops are used for executing a block of program statements repeatedly until
the given loop condition returns false.

9.4.2 Syntax of while loop


while(condition)
{
statement(s);
}
9.4.3 How while Loop works?
In while loop, condition is evaluated first and if it returns true then the statements inside while
loop execute, this happens repeatedly until the condition returns false. When condition returns
false, the control comes out of loop and jumps to the next statement in the program after while
loop.
Note: The important point to note when using while loop is that we need to use increment or
decrement statement inside while loop so that the loop variable gets changed on each iteration,
and at some point condition returns false. This way we can end the execution of while loop
otherwise the loop would execute indefinitely.

9.4.4 Flow Diagram of While loop

9.4.5 While Loop example in C++


#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}
Output:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
9.4.6 Infinite While loop
A while loop that never stops is said to be the infinite while loop, when we give the condition in
such a way so that it never returns false, then the loops becomes infinite and repeats itself
indefinitely.
An example of infinite while loop:
This loop would never end as I’m decrementing the value of i which is 1 so the condition i<=6
would never return false.

#include <iostream>
using namespace std;
int main(){
int i=1; while(i<=6) {
cout<<"Value of variable i is: "<<i<<endl; i--;
}
}
9.4.7 Example: Displaying the elements of array using while loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,87,15,99, -12};
/* The array index starts with 0, the
* first element of array has 0 index
* and represented as arr[0]
*/
int i=0;
while(i<5){
cout<<arr[i]<<endl;
i++;
}
}
Output:

21
87
15
99
-12
9.5 Do-while Loop

9.5.1 do-while loop in C++ with example


 while loop, a loop is used for repeating a block of statements until the given loop condition
returns false. do-while loop is similar to while loop, however there is a difference between them:
In while loop, condition is evaluated first and then the statements inside loop body gets executed,
on the other hand in do-while loop, statements inside do-while gets executed first and then the
condition is evaluated.

9.5.2 Syntax of do-while loop


do
{
statement(s);
} while(condition);
9.5.3 How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated, if the condition
returns true then the control jumps to the “do” for further repeated execution of it, this happens
repeatedly until the condition returns false. Once condition returns false control jumps to the next
statement in the program after do-while.

9.5.4 do-while loop example in C++


#include <iostream>
using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
Output:

Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6
9.5.5 Example: Displaying array elements using do-while loop
Here we have an integer array which has four elements. We are displaying the elements of it
using do-while loop.

#include <iostream>
using namespace std;
int main(){
int arr[]={21,99,15,109};
/* Array index starts with 0, which
* means the first element of array
* is at index 0, arr[0]
*/
int i=0;
do{
cout<<arr[i]<<endl;
i++;
}while(i<4);
return 0;
}
Output:

21
99
15
109
9.6 Continue Statement

9.6.1 Continue Statement in C++ with example


Continue statement is used inside loops. Whenever a continue statement is encountered inside a
loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration.

9.6.2 Syntax of continue statement


continue;
9.6.3 Example: continue statement inside for loop
As you can see that the output is missing the value 3, however the for loop iterate though the
num value 0 to 6. This is because we have set a condition inside loop in such a way, that the
continue statement is encountered when the num value is equal to 3. So for this iteration the loop
skipped the cout statement and started the next iteration of loop.

#include <iostream>
using namespace std;
int main(){
for (int num=0; num<=6; num++) {
/* This means that when the value of
* num is equal to 3 this continue statement
* would be encountered, which would make the
* control to jump to the beginning of loop for
* next iteration, skipping the current iteration
*/

if (num==3) {
continue;
}
cout<<num<<" ";
}
return 0;
}
Output:

012456
9.6.4 Flow Diagram of Continue Statement

9.6.5 Example: Use of continue in While loop


#include <iostream>
using namespace std;
int main(){
int j=6;
while (j >=0) {
if (j==4) {
j--;
continue;
}
cout<<"Value of j: "<<j<<endl;
j--;
}
return 0;
}
Output:

Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0
9.6.6 Example of continue in do-While loop
#include <iostream>
using namespace std;
int main(){
int j=4;
do {
if (j==7) {
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j<10);
return 0;
}
Output:

j is: 4
j is: 5
j is: 6
j is: 8
j is: 9

9.7 Break statement:

9.7.1 Break statement in C++ with example


The break statement is used in following two scenarios:

 Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used
along with if statement, whenever used inside loop(see the example below) so that it
occurs only for a particular condition.
 It is used in switch case control structure after the case blocks. Generally all cases in
switch case are followed by a break statement to avoid the subsequent cases (see the
example below) execution. Whenever it is encountered in switch-case block, the control
comes out of the switch-case body.

9.7.2 Syntax of break statement


break;
9.7.3 break statement flow diagram

9.7.4 Example – Use of break statement in a while loop


In the example below, we have a while loop running from 10 to 200 but since we have a break
statement that gets encountered when the loop counter variable value reaches 12, the loop gets
terminated and the control jumps to the next statement in program after the loop body.

#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
Value of num is: 10
Value of num is: 11
Value of num is: 12
Hey, I'm out of the loop
9.7.5 Example: break statement in for loop
#include <iostream>
using namespace std;
int main(){
int var;
for (var =200; var>=10; var --) {
cout<<"var: "<<var<<endl;
if (var==197) {
break;
}
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:

var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop
9.7.6 Example: break statement in Switch Case
#include <iostream>
using namespace std;
int main(){
int num=2;
switch (num) {
case 1: cout<<"Case 1 "<<endl;
break;
case 2: cout<<"Case 2 "<<endl;
break;
case 3: cout<<"Case 3 "<<endl;
break;
default: cout<<"Default "<<endl;
}
cout<<"Hey, I'm out of the switch case";
return 0;
}
Output:
Case 2
Hey, I'm out of the switch case
In this example, we have break statement after each Case block, this is because if we don’t have
it then the subsequent case block would also execute. The output of the same program without
break would be:

Case 2
Case 3
Default
Hey, I'm out of the switch case

9.8 Go to statement

9.8.1 goto statement in C++ with example


The goto statement is used for transferring the control of a program to a given label. The syntax
of goto statement looks like this:

goto label_name;
9.8.2 Program structure:
label1:
...
...
goto label2;
...
..
label2:
...
In a program we have any number of goto and label statements, the goto statement is followed by
a label name, whenever goto statement is encountered, the control of the program jumps to the
label specified in the goto statement.

goto statements are almost never used in any development as they are complex and makes your
program much less readable and more error prone. In place of goto, you can
use continue and break statement.

9.8.3 Example of goto statement in C++


#include <iostream>
using namespace std;
int main(){
int num; cout<<"Enter a number: "; cin>>num;
if (num % 2==0){
goto print;
}
else {
cout<<"Odd Number";
}

print:
cout<<"Even Number";
return 0;
}

Output:

Enter a number: 42
Even Number

10 Functions in C++
A function is block of code which is used to perform a particular task, for example let’s say you
are writing a large C++ program and in that program you want to do a particular task several
number of times, like displaying value from 1 to 10, in order to do that you have to write few
lines of code and you need to repeat these lines every time you display values. Another way of
doing this is that you write these lines inside a function and call that function every time you
want to display values. This would make you code simple, readable and reusable.

10.1 Syntax of Function


return_type function name (parameter_list)
{
//C++ Statements
}
Let’s take a simple example to understand this concept.

10.2 A simple function example


#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/int
sum(int num1, int num2){
int num3 = num1+num2; return num3;
}

int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Output:

100
The same program can be written like this: Well, I am writing this program to let you
understand an important term regarding functions, which is function declaration. Lets see the
program first and then at the end of it we will discuss function declaration, definition and calling
of function.

#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);

//Main function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method 
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}

10.3 Function Declaration:


 You have seen that I have written the same program in two ways, in the first program I didn’t
have any function declaration and in the second program I have function declaration at the
beginning of the program. The thing is that when you define the function before the main()
function in your program then you don’t need to do function declaration but if you are writing
your function after the main() function then you e need to declare the function first, else you will
get compilation error.

10.3.1 syntax of function declaration:


return_type function_name(parameter list);
Note: While providing parameter_list you can avoid the parameter names, just like I did in the
above example. I have given int sum(int,int); instead of int sum(int num1,int num2);.
10.4 Function definition:
 Writing the full body of function is known as defining a function.

10.4.1
syntax of function definition:
return_type function_name(parameter_list) {
//Statements inside function
}
Calling function: We can call the function like this:

function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++

10.5 Types of function


We have two types of function in C++:

1) Built-in functions
2) User-defined functions

10.5.1 1) Build-it functions


Built-in functions are also known as library functions. We need not to declare and define these
functions as they are already written in the C++ libraries such as iostream, cmath etc. We can
directly call them when we need.
10.5.2 Example: C++ built-in function example
Here we are using built-in function pow(x,y) which is x to the power y. This function is declared
in cmath header file so we have included the file in our program using #include directive.

#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}

Output:

32

10.6 2) User-defined functions

We have already seen user-defined functions, the example we have given at the beginning of this
tutorial is an example of user-defined function. The functions that we declare and write in our
programs are user-defined functions. Lets see another example of user-defined functions.

10.7 User-defined functions


#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);

int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;

cout<<"enter second number: ";


cin>>y;

cout<<"Sum of these two :"<<sum(x,y);


return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output:

enter first number: 22


enter second number: 19
Sum of these two :41

10.8 Parameters Pass:

10.8.1 Parameter Passing Techniques in C/C++


There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
10.8.2 Terminology
 Formal Parameter : A variable and its type as they appear in the prototype of the function
or method.
 Actual Parameter : The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
 Modes:
 IN: Passes info from caller to calle.
 OUT: Callee writes values in caller.
 IN/OUT: Caller tells callee value of variable, which may be updated by callee.
10.8.3 Important methods of Parameter Passing

Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not
get transmitted back to the caller. Any modifications to the formal parameter variable inside the
called function or method affect only the separate storage location and will not be reflected in the
actual parameter in the calling environment. This method is also called as call by value.

// C program to illustrate
// call by value
#include <stdio.h>

void func(int a, int b)


{
    a += b;
    printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
    int x = 5, y = 7;

    // Passing parameters


    func(x, y);
    printf("In main, x = %d y = %d\n", x, y);
    return 0;
}
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Languages like C, C++, Java support this type of parameter passing. 
Shortcomings:
 Inefficiency in storage allocation
 For objects and arrays, the copy semantics are costly
10.8.4 Pass by reference(aliasing) : 
This technique uses in/out-mode semantics. Changes made to formal parameter do get
transmitted back to the caller through parameter passing. Any changes to the formal parameter
are reflected in the actual parameter in the calling environment as formal parameter receives a
reference (or pointer) to the actual data. This method is also called as <em>call by reference.
This method is efficient in both time and space.

filter_none
edit
play_arrow
brightness_4
// C program to illustrate
// call by reference
#include <stdio.h>

void swapnum(int* i, int* j)


{
    int temp = *i;
    *i = *j;
    *j = temp;
}

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

    // passing parameters


    swapnum(&a, &b);

    printf("a is %d and b is %d\n", a, b);


    return 0;
}
Output:
a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java does’nt
support call by reference.
Shortcomings:
 Many potential scenarios can occur
 Programs are difficult to understand sometimes

10.8.5 Other methods of Parameter Passing


These techniques are older and were used in earlier programming languages like Pascal, Algol
and Fortran. These techniques are not applicable in high level languages.
1. Pass by Result : This method uses out-mode semantics. Just before control is transfered
back to the caller, the value of the formal parameter is transmitted back to the actual
parameter.T his method is sometimes called call by result. In general, pass by result
technique is implemented by copy.

2. Pass by Value-Result : This method uses in/out-mode semantics. It is a combination of


Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller,
the value of the formal parameter is transmitted back to the actual parameter. This method
is sometimes called as call by value-result

3. Pass by name : This technique is used in programming language such as Algol. In this
technique, symbolic “name” of a variable is passed, which allows it both to be accessed and
update.
Example:
To double the value of C[j], you can pass its name (not its value) into the following
procedure.
4. procedure double(x);
5. real x;
6. begin
7. x:=x*2
8. end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call
for the corresponding parameter in the body of the procedure.
Implications of Pass-by-Name mechanism:

 The argument expression is re-evaluated each time the formal parameter is passed.
 The procedure can change the values of variables used in the argument expression and
hence change the expression’s value.

10.9 C++ Recursion with example


The process in which a function calls itself is known as recursion and the corresponding function
is called the recursive function. The popular example to understand the recursion is factorial
function.

Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1.

In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
10.9.1 C++ recursion example: Factorial
#include <iostream>
using namespace std;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
   if (n <= 1)
        return 1;
   else 
      return n*f(n-1);
}
int main(){
int num;
  cout<<"Enter a number: ";
   cin>>num;
   cout<<"Factorial of entered number: "<<f(num);
return 0;
}
Output:

Enter a number: 5
Factorial of entered number: 120
10.9.2 Base condition
In the above program, you can see that I have provided a base condition in the recursive
function. The condition is:

if (n <= 1)
        return 1;
The purpose of recursion is to divide the problem into smaller problems till the base condition is
reached. For example in the above factorial program I am solving the factorial function f(n) by
calling a smaller factorial function f(n-1), this happens repeatedly until the n value reaches base
condition(f(1)=1). If you do not define the base condition in the recursive function then you will
get stack overflow error.

10.9.3 Direct recursion vs indirect recursion


Direct recursion: When function calls itself, it is called direct recursion, the example we have
seen above is a direct recursion example.
Indirect recursion: When function calls another function and that function calls the calling
function, then this is called indirect recursion. For example: function A calls function B and
Function B calls function A.

10.9.4 Indirect Recursion Example in C++


#include <iostream>
using namespace std;
int fa(int);
int fb(int);
int fa(int n){
if(n<=1)
return 1;
else
return n*fb(n-1);
}
int fb(int n){
if(n<=1)
return 1;
else
return n*fa(n-1);
}
int main(){
int num=5;
   cout<<fa(num);
return 0;
}
Output:

120

11 Arrays

11.1 Arrays in C++


An array is a collection of similar items stored in contiguous memory locations. In programming,
sometimes a simple variable is not enough to hold all the data. For example, lets say we want to
store the marks of 500 students, having 500 different variables for this task is not feasible, we
can define an array with size 500 that can hold the marks of all students.

11.2 Declaring an array in C++


There are couple of ways to declare an array.
Method 1:

int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Method 2:

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


Method 3:

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

11.3 Accessing Array Elements


Array index starts with 0, which means the first array element is at index 0, second is at index 1
and so on. We can use this information to display the array elements. See the code below:

#include <iostream>
using namespace std;

int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:

11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is not
recommended. When you want to access a particular array element then this is fine but if you
want to display all the elements then you should use a loop like this:

#include <iostream>
using namespace std;

int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=0;
while(n<=4){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
11.4 Multidimensional Arrays in C++
Multidimensional arrays are also known as array of arrays. The data in multidimensional array
is stored in a tabular form as shown in the diagram below:

11.5 A two dimensional array:


int arr[2][3];
This array has total 2*3 = 6 elements.

11.6 A three dimensional array:


int arr[2][2][2];
This array has total 2*2*2 = 8 elements.

11.6.1 Two dimensional array


Lets see how to declare, initialize and access Two Dimensional Array elements.

11.6.2 How to declare a two dimensional array?


int myarray[2][3];
Initialization:
We can initialize the array in many ways:
Method 1:

int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};

Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.

int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};


Accessing array elements:
arr[0][0] – first element
arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element

Example: Two dimensional array in C++

#include <iostream>
Using namespace std;
Int main (){
Int arr [2][3] = {{11, 22, 33}, {44, 55, 66}};
for (int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:

arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
11.6.3 Three dimensional array
Lets see how to declare, initialize and access Three Dimensional Array elements.

11.6.4 Declaring a three dimensional array:


int myarray[2][3][2];
Initialization:
We can initialize the array in many ways:
Method 1:

int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};


Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.

int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
Three dimensional array example

#include <iostream>
using namespace std;

int main(){
// initializing the array
int arr[2][3][2] = {
{ {1,-1}, {2,-2}, {3,-3} },
{ {4,-4}, {5,-5}, {6,-6} }
};
// displaying array values
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 2; z++) {
cout<<arr[x][y][z]<<" ";
}
}
}
return 0;
}
Output:

1 -1 2 -2 3 -3 4 -4 5 -5 6 -6

11.7 Passing Array to Function in C++


You can pass array as an argument to a function just like you pass variables as arguments. In
order to pass array to the function you just need to mention the array name during function
call like this:

function_name(array_name);
11.7.1 Example: Passing arrays to a function
In this example, we are passing two arrays a & b to the function sum(). This function adds the
corresponding elements of both the arrays and display them.

#include <iostream>
using namespace std;
/* This function adds the corresponding
 * elements of both the arrays and
 * displays it.
 */
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}
Output:

11
22
33
44
55
11.7.2 Example 2: Passing multidimensional array to function
In this example we are passing a multidimensional array to the function square which displays
the square of each element.

#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
 * of the elements of multidimensional array
 */
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
       {1, 2, 3},
      {4, 5, 6}
};
square(arr);
return 0;
}
Output:

1
4
9
16
25
36

12 Strings:

12.1 Strings in C++


Strings are words that are made up of characters, hence they are known as sequence of
characters.

In C++ we have two ways to create and use strings:

1) By creating char arrays and treat them as string 2


2) By creating string object

Lets discuss these two ways of creating string first and then we will see which method is better
and why.

12.2 1) Array of Characters – Also known as C Strings


Example 1:
A simple example where we have initialized the char array during declaration.

#include <iostream>
using namespace std;
int main(){
char book[50] = "A Song of Ice and Fire";
  cout<<book;
return 0;
}
Output:
A Song of Ice and Fire

12.3 Example 2: Getting user input as string

This can be considered as inefficient method of reading user input, why? Because when we read
the user input string using cin then only the first word of the string is stored in char array and rest
get ignored. The cin function considers the space in the string as delimiter and ignore the part
after it.

#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
//reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;
}
Output:

Enter your favorite book name:The Murder of Roger Ackroyd


You entered: The
You can see that only the “The” got captured in the book and remaining part after space got
ignored. How to deal with this then? Well, for this we can use cin.get function, which reads the
complete line entered by user.

12.4 Example 3: Correct way of capturing user input string using cin.get
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";

//reading user input


cin.get(book, 50);
cout<<"You entered: "<<book;
return 0;
}
Output:

Enter your favorite book name:The Murder of Roger Ackroyd


You entered: The Murder of Roger Ackroyd
12.5 Drawback of this method
1) Size of the char array is fixed, which means the size of the string created through it is fixed in
size, more memory cannot be allocated to it during runtime.

 For example, lets say you have created an array of character with the size 10 and user
enters the string of size 15 then the last five characters would be truncated from the
string.
On the other hand if you create a larger array to accommodate user input then the
memory is wasted if the user input is small and array is much larger then what is needed.

2) In this method, you can only use the in-built functions created for array which don’t help
much in string manipulation.

What is the solution of these problems?


We can create string using string object. Lets see how we can do it.

12.5.1 String object in C++


Till now we have seen how to handle strings in C++ using char arrays. Lets see another and
better way of handling strings in C++ – string objects.

#include<iostream>
using namespace std;
int main(){
// This is how we create string object
string str;
cout<<"Enter a String:";
/* This is used to get the user input
* and store it into str
*/
getline(cin,str);
cout<<"You entered: ";
cout<<str<<endl;

/* This function adds a character at


* the end of the string
*/
str.push_back('A');
cout<<"The string after push_back: "<<str<<endl;
/* This function deletes a character from
* the end of the string
*/
str.pop_back();
cout << "The string after pop_back: "<<str<<endl;
return 0;
}
Output:

Enter a String:XYZ
You entered: XYZ
The string after push_back: XYZA
The string after pop_back: XYZ
The advantage of using this method is that you need not to declare the size of the string, the size
is determined at run time, so this is better memory management method. The memory is
allocated dynamically at runtime so no memory is wasted.

13 Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation, cannot
be performed without using pointers. So it becomes necessary to learn pointers to
become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes
an address in memory. Consider the following example, which prints the address of the
variables defined −
#include <stdio.h>

int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

13.1 Pointers in C++


 Pointer is a variable in C++ that holds the address of another variable.
 They have data type just like variables, for example an integer type pointer can hold the
address of an integer variable and an character type pointer can hold the address of char
variable.

13.2 Syntax of pointer


data_type *pointer_name;
13.3 How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very
frequently. 
(a) We define a pointer variable, 
(b) assign the address of a variable to a pointer and 
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand. The following example makes use of these
operations –
#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

13.4 NULL Pointers


It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program −
Live Demo

#include <stdio.h>

int main () {
int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}

When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system.
However, the memory address 0 has special significance; it signals that the pointer is
not intended to point to an accessible memory location. But by convention, if a pointer
contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

13.5 Pointers in Detail


Pointers have many but easy concepts and they are very important to C programming.
The following important pointer concepts should be clear to any C programmer −

Sr.No Concept & Description


.

1 Pointer arithmetic

There are four arithmetic operators that can be used in pointers: ++, --, +, -

2 Array of pointers

You can define arrays to hold a number of pointers.

3 Pointer to pointer

C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C


Passing an argument by reference or by address enable the passed argument to
be changed in the calling function by the called function.

5 Return pointer from functions in C

C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.

13.6 How to declare a pointer?


/* This pointer p can hold the address of an integer
* variable, here p is a pointer and var is just a
* simple integer variable
*/
int *p, var

13.7 Assignment

As I mentioned above, an integer type pointer can hold the address of another int variable. Here
we have an integer variable var and pointer p holds the address of var. To assign the address of
variable to pointer we use ampersand symbol (&).

/* This is how you assign the address of another variable


* to the pointer
*/
p = &var;

13.8 How to use it?

// This will print the address of variable var


cout<<&var;

/* This will also print the address of variable


* var because the pointer p holds the address of var
*/
cout<<p;

/* This will print the value of var, This is


* important, this is how we access the value of
* variable through pointer
*/
cout<<*p;

13.9 Example of Pointer


Lets take a simple example to understand what we discussed above.

#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p, var=101;

//Assignment
p = &var;

cout<<"Address of var: "<<&var<<endl;


cout<<"Address of var: "<<p<<endl;
cout<<"Address of p: "<<&p<<endl;
cout<<"Value of var: "<<*p;
return 0;
}
Output:

Address of var: 0x7fff5dfffc0c


Address of var: 0x7fff5dfffc0c
Address of p: 0x7fff5dfffc10
Value of var: 101

13.10 Pointer and arrays


While handling arrays with pointers you need to take care few things.

 First and very important point to note regarding arrays is that the array name alone
represents the base address of array so while assigning the address of array to pointer
don’t use ampersand sign(&). Do it like this:

Correct: Because arr represent the address of array.

p = arr;
Incorrect:

p = &arr;
13.11 Example: Traversing the array using Pointers
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p;
//Array declaration
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment
p = arr;
for(int i=0; i<6;i++){
    cout<<*p<<endl;
//++ moves the pointer to next int position
    p++;
   }
return 0;
}
Output:

1
2
3
4
5
6

13.12 How to increment pointer address and pointer’s value?


When we are accessing the value of a variable through pointer, sometimes we just need to
increment or decrement the value of variable though it or we may need to move the pointer to
next int position(just like we did above while working with arrays). The ++ operator is used for
this purpose. One of the example of ++ operator we have seen above where we traversed the
array using pointer by incrementing the pointer value using ++ operator. Lets see few more
cases.

// Pointer moves to the next int position (as if it was an array)


p++;
// Pointer moves to the next int position (as if it was an array)
++p;

/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);
13.13 C++ ‘this’ Pointer
The this pointer holds the address of current object, in simple words you can say that
this pointer points to the current object of the class. Let’s take an example to understand this
concept.

13.14 C++ Example: this pointer


Here you can see that we have two data members num and ch. In member function
setMyValues() we have two local variables having same name as data members name. In such
case if you want to assign the local variable value to the data members then you won’t be able to
do until unless you use this pointer, because the compiler won’t know that you are referring to
object’s data members unless you use this pointer. This is one of the example where you must
use this pointer.

#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
  obj.displayMyValues();
return 0;
}
Output:

100
A
13.15 Example 2: function chaining calls using this pointer
Another example of using this pointer is to return the reference of current object so that you can
chain function calls, this way you can call all the functions for the current object in one go.
Another important point to note in this program is that I have incremented the value of object’s
num in the second function and you can see in the output that it actually incremented the value
that we have set in the first function call. This shows that the chaining is sequential and the
changes made to the object’s data members retains for further chaining calls.

#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
Demo &setNum(int num){
this->num =num;
return *this;
}
Demo &setCh(char ch){
this->num++;
this->ch =ch;
return *this;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
//Chaining calls
obj.setNum(100).setCh('A');
obj.displayMyValues();
return 0;
}
Output:

101
A

14 Structures, Union in C++

 Both structure and union are collection of different data type.


 They are used to group number of variables of different type in a single unit. Structure
and union.
 Declaration and Initialization of structure starts with struct keyword.
 Declaration and Initialization of union starts with union keyword.
 Structure allocates different memory locations for all its members while union allocates
common memory location for all its members.
 The memory occupied by a union will be large enough to hold the largest member of the
union. Union declaration

Declaration of union must start with the keyword union followed by the union name and
union's member variables are declared within braces.

14.1 Syntax for declaring union

Union union-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

14.2 Accessing the union members


We have to create an object of union to access its members. Object is a variable of type union.
Union members are accessed using the dot operator(.) between union's object and union's
member name.

14.3 Syntax for creating object of union

union union-name obj;


14.4 Example for creating object & accessing union members

#include<iostream.h>

union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

Employee E;

cout << "\nEnter Employee Id : ";


cin >> E.Id;

cout << "\nEnter Employee Name : ";


cin >> E.Name;

cout << "\nEnter Employee Age : ";


cin >> E.Age;

cout << "\nEnter Employee Salary : ";


cin >> E.Salary;

cout << "\n\nEmployee Id : " << E.Id;


cout << "\nEmployee Name : " << E.Name;
cout << "\nEmployee Age : " << E.Age;
cout << "\nEmployee Salary : " << E.Salary;

Output :

Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000

Employee Id : -20536
Employee Name : ?$?$ ?
Employee Age : -20536
Employee Salary : 45000

In the above example, we can see that values of Id, Name and Age members of union got
corrupted because final value assigned to the variable has occupied the memory location and
this is the reason that the value of salary member is getting printed very well. Now let's look
into the same example once again where we will use one variable at a time which is the main
purpose of having union:

#include<iostream.h>

union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

Employee E;

cout << "\nEnter Employee Id : ";


cin >> E.Id;
cout << "Employee Id : " << E.Id;

cout << "\n\nEnter Employee Name : ";


cin >> E.Name;
cout << "Employee Name : " << E.Name;

cout << "\n\nEnter Employee Age : ";


cin >> E.Age;
cout << "Employee Age : " << E.Age;

cout << "\n\nEnter Employee Salary : ";


cin >> E.Salary;
cout << "Employee Salary : " << E.Salary;

Output :
Enter Employee Id : 1
Employee Id : 1

Enter Employee Name : Kumar


Employee Name : Kumar

Enter Employee Age : 29


Employee Age : 29

Enter Employee Salary : 45000


Employee Salary : 45000

Here, all the members are getting printed very well because one member is being used at a
time.

14.5 Example of comparing size of union and structure

#include<iostream.h>

struct Employee1

int Id;

char Name[25];

long Salary;

};
union Employee2

int Id;

char Name[25];

long Salary;

};

void main()

cout << "\nSize of Employee1 is : " << sizeof(Employee1);

cout << "\nSize of Employee2 is : " << sizeof(Employee2);

Output :

Size of Employee1 is : 31

Size of Employee2 is : 25

15 Structure in C++
Structure is commonly referred to as user-defined data type. Structure is similar to an array but
the only difference is that array is collection of similar data type on the other hand structure is
collection of different data type. A structure can contain any data type including array and
another structure as well. Each variable declared inside structure is called member of structure.
Declare Structuration

Declaration of structure must start with the keyword struct followed by the structure name and
structure's member variables are declared within braces.

15.1 Syntax for declaring structure

struct structure-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

15.2 Example for declaring structure

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

15.3 Accessing the structure members


We have to create an object of structure to access its members. Object is a variable of type
structure. Structure members are accessed using the dot operator(.) between structure's object
and structure's member name.
15.4 Syntax for creating object

structure-name obj;

15.5 Example for creating object & accessing structure members

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

Employee E; //Statement 1

cout << "\nEnter Employee Id : ";


cin >> E.Id;

cout << "\nEnter Employee Name : ";


cin >> E.Name;

cout << "\nEnter Employee Age : ";


cin >> E.Age;
cout << "\nEnter Employee Salary : ";
cin >> E.Salary;

cout << "\n\nEmployee Id : " << E.Id;


cout << "\nEmployee Name : " << E.Name;
cout << "\nEmployee Age : " << E.Age;
cout << "\nEmployee Salary : " << E.Salary;

Output :

Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000

Statement 1 is creating an object E of Employee type.

15.6 Initialization of structure


Like normal variable structures can be initialized at the time of declaration. Initialization of
structure is almost similar to initializing array. The structure object is followed by equal sign
and the list of values enclosed in braces and each value is separated with comma.
15.7 Example for declaring & initializing structure at same time

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{

Employee E = {2,"Suresh",35,35000};

cout << "\n\nEmployee Id : " << E.Id;


cout << "\nEmployee Name : " << E.Name;
cout << "\nEmployee Age : " << E.Age;
cout << "\nEmployee Salary : " << E.Salary;

Output :

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
15.8 Array of Structure
Structure is collection of different data type. An object of structure represents a single record in
memory, if we want more than one record of structure type, we have to create an array of
structure or object. As we know, an array is a collection of similar type, therefore an array can
be of structure type.

15.9 Syntax for declaring structure array

struct structure-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

structure-name obj [ size ];

15.10 Example for declaring structure array

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1

for(i=0;i<3;i++)
{

cout << "\nEnter details of " << i+1 << " Employee";

cout << "\n\tEnter Employee Id : ";


cin >> Emp[i].Id;

cout << "\n\tEnter Employee Name : ";


cin >> Emp[i].Name;

cout << "\n\tEnter Employee Age : ";


cin >> Emp[i].Age;

cout << "\n\tEnter Employee Salary : ";


cin >> Emp[i].Salary;
}

cout << "\nDetails of Employees";


for(i=0;i<3;i++)
cout << "\n"<< Emp[i].Id <<"\t"<< Emp[i].Name <<"\t"
<< Emp[i].Age <<"\t"<< Emp[i].Salary;

Output :

Enter details of 1 Employee


Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000

Enter details of 3 Employee


Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000

Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using array of
object. Statement 1 is creating an array of Employee Emp to store the records of 3 employees.

15.11 Array within Structure


As we know, structure is collection of different data type. Like normal data type, It can also
store an array as well.

15.12 Syntax for array within structure

struct structure-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
----------
----------
datatype varN;
};

structure-name obj;

15.13 Example for array within structure

#include<iostream.h>

struct Student
{
int Roll;
char Name[25];
int Marks[3]; //Statement 1 : array of marks
int Total;
float Avg;
};

void main()
{
int i;
Student S;

cout << "\n\nEnter Student Roll : ";


cin >> S.Roll;

cout << "\n\nEnter Student Name : ";


cin >> S.Name;

S.Total = 0;

for(i=0;i<3;i++)
{
cout << "\n\nEnter Marks " << i+1 << " : ";
cin >> S.Marks[i];

S.Total = S.Total + S.Marks[i];


}

S.Avg = S.Total / 3;

cout << "\nRoll : " << S.Roll;


cout << "\nName : " << S.Name;
cout << "\nTotal : " << S.Total;
cout << "\nAverage : " << S.Avg;
}

Output :

Enter Student Roll : 10


Enter Student Name : Kumar
Enter Marks 1 : 78
Enter Marks 2 : 89
Enter Marks 3 : 56

Roll : 10
Name : Kumar
Total : 223
Average : 74.00000

In the above example, we have created an array Marks[ ] inside structure representing 3 marks
of a single student. Marks[ ] is now a member of structure student and to access Marks[ ] we
have used dot operator(.) along with object S.

15.14 Nested Structure in C++


When a structure contains another structure, it is called nested structure. For example,we have
two structures named Address and Employee. To make Address nested to Employee, we have
to define Address structure before and outside Employee structure and create an object of
Address structure inside Employee structure.

15.15 Syntax for structure within structure or nested structure


struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
structure1 obj;
};

15.16 Example for structure within structure or nested structure

#include<iostream.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
Address Add;
};

void main()
{
int i;
Employee E;

cout << "\n\tEnter Employee Id : ";


cin >> E.Id;

cout << "\n\tEnter Employee Name : ";


cin >> E.Name;

cout << "\n\tEnter Employee Salary : ";


cin >> E.Salary;

cout << "\n\tEnter Employee House No : ";


cin >> E.Add.HouseNo;

cout << "\n\tEnter Employee City : ";


cin >> E.Add.City;

cout << "\n\tEnter Employee House No : ";


cin >> E.Add.PinCode;

cout << "\nDetails of Employees";


cout << "\n\tEmployee Id : " << E.Id;
cout << "\n\tEmployee Name : " << E.Name;
cout << "\n\tEmployee Salary : " << E.Salary;
cout << "\n\tEmployee House No : " << E.Add.HouseNo;
cout << "\n\tEmployee City : " << E.Add.City;
cout << "\n\tEmployee House No : " << E.Add.PinCode;

Output :

Enter Employee Id : 101


Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056

Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056

15.17 Structure and Function in C++


Using function we can pass structure as function argument and we can also return structure
from function.
15.18 Passing structure as function argument
Structure can be passed to function through its object therefore passing structure to function or
passing structure object to function is same thing because structure object represents the
structure. Like normal variable, structure variable(structure object) can be pass by value or by
references / addresses.

15.19 Passing Structure by Value


In this approach, the structure object is passed as function argument to the definition of
function, here object is representing the members of structure with their values.

15.20 Example for passing structure object by value

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void Display(struct Employee);


void main()
{
Employee Emp = {1,"Kumar",29,45000};

Display(Emp);

}
void Display(struct Employee E)
{
cout << "\n\nEmployee Id : " << E.Id);
cout << "\nEmployee Name : " << E.Name);
cout << "\nEmployee Age : " << E.Age);
cout << "\nEmployee Salary : " << E.Salary);
}

Output :

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000

15.21 Passing Structure by Reference


In this approach, the reference/address structure object is passed as function argument to the
definition of function.

15.22 Example for passing structure object by reference

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void Display(struct Employee*);


void main()
{
Employee Emp = {1,"Kumar",29,45000};

Display(&Emp);

void Display(struct Employee *E)


{
cout << "\n\nEmployee Id : " << E->Id;
cout << "\nEmployee Name : " << E->Name;
cout << "\nEmployee Age : " << E->Age;
cout << "\nEmployee Salary : " << E->Salary;
}

Output :

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
15.23 Function Returning Structure
Structure is user-defined data type, like built-in data types structure can be return from
function.

15.24 Example for passing structure object by reference

#include<iostream.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

Employee Input(); //Statement 1


void main()
{
Employee Emp;

Emp = Input();

cout << "\n\nEmployee Id : " << E.Id;


cout << "\nEmployee Name : " << E.Name;
cout << "\nEmployee Age : " << E.Age;
cout << "\nEmployee Salary : " << ESalary;

}
Employee Input()
{
Employee E;

cout << "\nEnter Employee Id : ";


cin >> E.Id;

cout << "\nEnter Employee Name : ";


cin >> E.Name;

cout << "\nEnter Employee Age : ";


cin >> E.Age;

cout << "\nEnter Employee Salary : ";


cin >> E.Salary;

return E; //Statement 2
}

Output :

Enter Employee Id : 10
Enter Employee Name : Ajay
Enter Employee Age : 25
Enter Employee Salary : 15000

Employee Id : 10
Employee Name : Ajay
Employee Age : 25
Employee Salary : 15000
In the above example, statement 1 is declaring Input() with return type Employee. As we know
structure is user-defined data type and structure name acts as our new user-defined data type,
therefore we use structure name as function return type.

Input() have local variable E of Employee type. After getting values from user statement 2
returns E to the calling function and display the values.

16 Bit manipulation

16.1 Bits manipulation


Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter
than a byte. C language is very efficient in manipulating bits.

Here are following operators to perform bits manipulation:

16.2 Bitwise Operators:


Bitwise operator works on bits and performs bit by bit operation.
Assume if B = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1000
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
Show Examples
There are following Bitwise operators supported by C language
The shift operators perform appropriate shift by operator on the right to the operator on the left.
The right operator must be positive. The vacated bits are filled with zero.

For example: x << 2 shifts the bits in x by 2 places to the left

if x = 00000010 (binary) or 2 (decimal)

then:

x >>= 2 => x = 00000000 or just 0 (decimal)


Also: if x = 00000010 (binary) or 2 (decimal)

then

x <<= 2 => x = 00001000 or 8 (decimal)

therefore a shift left is equivalent to a multiplication by 2. Similarly a shift right is equal to


division by 2. Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you
want fast multiplications or division by 2 use shifts.

To illustrate many points of bitwise operators let us write a function, Bit count, that counts bits
set to 1 in an 8 bit number (unsigned char) passed as an argument to the function.

int bitcount(unsigned char x)

int count;

for ( count=0; x != 0; x>>=1);

if ( x & 01)

count++;

return count;

This function illustrates many C program points:

 For loop not used for simple counting operation.


 x >>= 1 => x = x>> 1;
 for loop will repeatedly shift right x until x becomes 0
 use expression evaluation of x & 01 to control if
 x & 01 masks of 1st bit of x if this is 1 then count++
16.3 Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data
storage is at a premium. Typical examples:

 Packing several objects into a machine word. E.g. 1 bit flags can be compacted.

 Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit
integers.

C allows us do this in a structure definition by putting: bit length after the variable. For example:

struct packed_struct {

unsigned int f1:1;

unsigned int f2:1;

unsigned int f3:1;

unsigned int f4:1;

unsigned int type:4;

unsigned int my_int:9;

} pack;

Here the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit
my_int.

C automatically packs the above bit fields as compactly as possible, provided that the maximum
length of the field is less than or equal to the integer word length of the computer. If this is not
the case then some compilers may allow memory overlap for the fields whilst other would store
the next field in the next word.

16.4 (Important tactics)


Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks
for Competitive Programming
1. Compute XOR from 1 to n (direct method) :

// Direct XOR of all numbers from 1 to n


int computeXOR(int n)
{
    if (n % 4 == 0)
        return n;
    if (n % 4 == 1)
        return 1;
    if (n % 4 == 2)
        return n + 1;
    else
        return 0;
}
Input: 6
Output: 7
Refer Compute XOR from 1 to n for details.
2. We can quickly calculate the total number of combinations with numbers smaller than or
equal to with a number whose sum and XOR are equal. Instead of using looping (Brute
force method), we can directly find it by a mathematical trick i.e.
// Refer Equal Sum and XOR for details.
Answer = pow(2, count of zero bits)
3. How to know if a number is a power of 2?

//  Function to check if x is power of 2


bool isPowerOfTwo(int x)
{
     // First x in the below expression is
     // for  the case when x is 0
     return x && (!(x & (x - 1)));
}
Refer check if a number is power of two for details.
4. Find XOR of all subsets of a set. We can do it in O(1) time. The answer is always 0 if given
set has more than one elements. For set with single element, the answer is value of single
element. Refer XOR of the XOR’s of all subsets for details.
5. We can quickly find number of leading, trailing zeroes and number of 1’s in a binary code
of an integer in C++ using GCC. It can be done by using inbuilt function i.e.
Number of leading zeroes: builtin_clz(x)
Number of trailing zeroes : builtin_ctz(x)
Number of 1-bits: __builtin_popcount(x)
Refer GCC inbuilt functions for details.
6. Convert binary code directly into an integer in C++.
// Conversion into Binary code//
#include <iostream>
using namespace std;

int main()
{
    auto number = 0b011;
    cout << number;
    return 0;
}
Output: 3
7. The Quickest way to swap two numbers:
a ^= b;
b ^= a;
a ^= b;
Refer swap two numbers for details.
8. Simple approach to flip the bits of a number: It can be done by a simple way, just simply
subtract the number from the value obtained when all the bits are equal to 1 .
For example:
Number : Given Number
Value : A number with all bits set in given number.
Flipped number = Value – Number.

Example :
Number = 23,
Binary form: 10111;
After flipping digits number will be: 01000;
Value: 11111 = 31;
9. We can find the most significant set bit in O(1) time for a fixed size integer. For example
below cocde is for 32 bit integer.

int setBitNumber(int n)
{
    // Below steps set bits after
    // MSB (including MSB)

    // Suppose n is 273 (binary


    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n>>1;

    // This makes sure 4 bits


    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n>>2;

    n |= n>>4;
    n |= n>>8;
    n |= n>>16;

    // Increment n by 1 so that


    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;

    // Return original MSB after shifting.


    // n now becomes 100000000
    return (n >> 1);
}
Refer Find most significant set bit of a number for details.
10. We can quickly check if bits in a number are in alternate pattern (like 101010). We
compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce
a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if a number has
bits in alternate pattern for details.

You might also like