Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

CPP All

notes on cpp programing

Uploaded by

Panashe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

CPP All

notes on cpp programing

Uploaded by

Panashe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

C++ First Program Hello World

In this tutorial, we are going to learn about the basic structure of a C++
program. Let's first write a simple C++ program to print "Hello World" string on
screen. This program is very useful to learn the basic syntax and semantics of
the C++ language. It become the traditional first program that many people
write while learning a new programming language.

C++ Program to print Hello World string


1#include <iostream>
2using namespace std;
3
4int main() {
5 // Printing "Hello World" string
6 cout << "Hello World";
7 return 0;
8}
Let us look various parts of the above program line by line:
• #include <iostream>
#include is a preprocessor directive to includes the header file in our
proram. C++ language contains various function library(header files)
which contain information that is either necessary or useful to your
program. In this program we are using one such header called iostream
which is required for input and output.
• using namespace std;
This line tells the compiler to use the std namespace. Namespaces are
used to avoid naming conflicts and to make it easier to reference
operations included in that namespace(here we are using std
namespace).
• int main() {
The next line is int main(){. Every C++ program must have a main()
function, and every C++ program can only have one main() function
where program execution begins. The int is what is called the return
value. The two curly brackets {} are used to group all statements
together.
• // Printing "Hello World" string
This line is a single-line comment of C++ language. Comments are
written for better readability of code, this line is ignored by compiler.
Single-line comments begin with // till end of the line. Everything on the
line after // is ignored by compiler.
• cout<<"Hello World";
This line prints "Hello World" string on the screen. The cout is an object
of standard output stream which is defined in iostream header. cout is
used for displaying data on the screen.
• return 0;
This statement is returning 0 to calling function, in this case operating
system. int main() declares that main must return an integer. Returning
0 means informing operating system that program successfully
completed, whereas returning 1 means error while running program.
Points to Remember
• C++ support both single line comment as well as multi line
comments.
• Every statement must end with a semicolon.
• We must include iostream header for any input and output
operation in our C++ program.
• Every C++ program must have only one main() function where
program execution starts.
• Main returns an integer to Operating system informing about it's
termination state. Whether program executed successfully or an error
has occurred.

How to Compile and Execute your C++ Program


1. Write
o Open a text editor and type the above mentioned "Hello
World" code.
o Save this file as HelloWorld.cpp.

2. Compile
o Open command prompt and go to your current working
directory where you saved your HelloWorld.cpp file.
o Compile your code by typing "g++ HelloWorld.cpp" in
command prompt. Your program will compile successfully, If your
program doesn't contain any syntax error.
o It will generate an a.out file.
3. Execute
o Now run your program by typing "a.out" in command
prompt.

4. Output
o You will see "Hello World" printed on your console.
C++ First Program Hello World
In this tutorial, we are going to learn about the basic structure of a C++
program. Let's first write a simple C++ program to print "Hello World" string on
screen. This program is very useful to learn the basic syntax and semantics of
the C++ language. It become the traditional first program that many people
write while learning a new programming language.

C++ Program to print Hello World string


1#include <iostream>
2using namespace std;
3
4int main() {
5 // Printing "Hello World" string
6 cout << "Hello World";
7 return 0;
8}
Let us look various parts of the above program line by line:
• #include <iostream>
#include is a preprocessor directive to includes the header file in our
proram. C++ language contains various function library(header files)
which contain information that is either necessary or useful to your
program. In this program we are using one such header called iostream
which is required for input and output.
• using namespace std;
This line tells the compiler to use the std namespace. Namespaces are
used to avoid naming conflicts and to make it easier to reference
operations included in that namespace(here we are using std
namespace).
• int main() {
The next line is int main(){. Every C++ program must have a main()
function, and every C++ program can only have one main() function
where program execution begins. The int is what is called the return
value. The two curly brackets {} are used to group all statements
together.
• // Printing "Hello World" string
This line is a single-line comment of C++ language. Comments are
written for better readability of code, this line is ignored by compiler.
Single-line comments begin with // till end of the line. Everything on the
line after // is ignored by compiler.
• cout<<"Hello World";
This line prints "Hello World" string on the screen. The cout is an object
of standard output stream which is defined in iostream header. cout is
used for displaying data on the screen.
• return 0;
This statement is returning 0 to calling function, in this case operating
system. int main() declares that main must return an integer. Returning
0 means informing operating system that program successfully
completed, whereas returning 1 means error while running program.
Points to Remember
• C++ support both single line comment as well as multi line
comments.
• Every statement must end with a semicolon.
• We must include iostream header for any input and output
operation in our C++ program.
• Every C++ program must have only one main() function where
program execution starts.
• Main returns an integer to Operating system informing about it's
termination state. Whether program executed successfully or an error
has occurred.

How to Compile and Execute your C++ Program


1. Write
o Open a text editor and type the above mentioned "Hello
World" code.
o Save this file as HelloWorld.cpp.

2. Compile
o Open command prompt and go to your current working
directory where you saved your HelloWorld.cpp file.
o Compile your code by typing "g++ HelloWorld.cpp" in
command prompt. Your program will compile successfully, If your
program doesn't contain any syntax error.
o It will generate an a.out file.

3. Execute
o Now run your program by typing "a.out" in command
prompt.

4. Output
o You will see "Hello World" printed on your console.
C++ Comments
Comments are added in C++ program for documentation purpose. Comments
are explanatory statements that we can in our code to make it easy to
understand for anyone reading this source code. We can add comments
anywhere and any number of times in our programs. Adding comments in
your code is highly recommended and is considered as a good programming
practice. Comment are ignored by C++ compilers.
C++ programming language supports two types of comments
• Single line comments.
• Multi line comments(inherited from C).

Single Line Comments in C++

• Single line comment starts with “//” symbol and till end of the line.
• Everything on the line after // is ignored by compiler.
For Example:
// My first C++ Program
cout << "Hello_World";
cout << "Hello_World"; // My first C++ Program

Multiple Line Comments in C++

• Multi line comments in C++ start with /* and end with */.
Everything between /* and */ is ignored by compiler.
• Nesting of multi-line comments is not allowed.
• Inside multi line comment // characters have no special meaning.
For Example:
/* This is my first C++ program
to print Hello World string on screen
*/
cout << "Hello World";
cout << "Hello World"; /* My first C++ Program */

Summary

• Comments are always ignored by C++ compiler.


• Comments are used for documentation and explanatory purpose.
• We can add comments anywhere and any number of times in our
programs.
• In C++, a comment can be single line or multi-line.
• Adding comments in program is a good programming practice.
C++ Basic Input and Output
In this tutorial we learn about basic input and output capabilities provided by
C++ programming language. For Input and output, C++ programming
language uses an abstraction called streams which are sequences of bytes. A
stream is an abstract entity where a program can either write or read
characters. It hides the hardware implementation and details from the C++
program.
In any input operation, data from mouse, keyboard, external disk etc to main
memory for program consumption whereas data flows from main memory to
output devices like screen, printer etc, in any output operation. In most
programming environments, standard input device by default is keyboard and
standard output device by default is screen. The C++ standard library defines
some stream objects for input and output.

Standard Input Stream (cin)


cin is a predefined object of class istream. cin object by default is attached to
the standard input device which is keybord in most programming
environments. cin along with extraction operator (>>) is used to take keyboard
input from user. Extraction operator is followed by a variable where the input
data is stored. cin is an input statement, hence programs waits for user to
enter input from keyboard and press enter. Input data flows directly from
keyboard to variable.
Here is an example of reading an integer value from user
int count;
cin >> count;

Here is an example of reading an integer value from user


int count, sum;
cin >> count >> sum;

Based on the data type of the variable after extraction operator(>>) cin
determine how it interprets the characters read from the input. If the variable is
of integer data type than it will expect integer input from user.
We can also take string input from user using cin and extraction operator. For
string input, it reads characters till first white space character(space, tab,
newline etc). With cin we can only read one word at a time, it does not support
reading an entire line having space characters. To read an entire space
seperated sentence we should use "getline" function.

Standard Output Stream (cout)


cout is a predefined object of class ostream. cout object by default is attached
to the standard output device which is screen in most programming
environments. cout along with insertion operator (<<) is used to display data
to user on screen. Insertion operator is followed by a variable or constant
which needs to be displayed to user. Input data flows directly from variable to
output stream.
Here is an example of printing an integer on screen
int count = 10;
cout << count;

We can print multiple values at a time by cascading insertion operator.


cout << count << 20 << "Hello";

We can use ‘\n‘ or endl to print the output on new line.


cout << 20 << endl << "Hello\n" << "World";

Output :
20
Hello
World

C++ Program for Basic Input Output using cin and cout
#include <iostream>
using namespace std;

int main( ) {
char name[50];
int age, salary, account_number;

cout << "Enter your name \n";


// reading string
cin >> name;
cout << "Enter your age \n";
// reading integer
cin >> age;
cout << "Enter your salary and account number\n";
// taking two input at a time
cin >> salary >> account_number;

cout << name << endl << age << endl <<
salary << endl << account_number;

return 0;
}
Output
Enter your name
Adam
Enter your age
22
Enter your salary and account number
2345 87654
Adam
22
2345
87654

In above program, we are taking input from user using cin and printing it on
screen using cout as explained above. We are taking input of different data
types like integer and string. We are also taking multiple inputs in a single cin
statement by using multiple extraction operator.
C++ Keywords and Identifiers
C++ Keywords
C++ keywords are the reserved words which are pre-defined in C++
programming language. We cannot use keywords as an identifier. Each
keyword has a pre-defined meaning for C++ compiler.
• Trying to use a keyword as an identifier will generate a
compilation error.
• All keywords are in lower case letters.
Here is the list of reserved keywords in C++.
asm else new thi

auto enum operator thro

bool explicit private tru

break export protected try

case extern public type

catch false register type

char floar reinterpret_cast typen

class for return uni

const friend short unsig

const_cast goto signed usin


continue if sizeof virtu

default inline static voi

delete int static_cast vola

do long struct wcha

double mutable switch whi

dynamic_cast namespace template

C++ Identifiers
In C++ programming language, the name of variables, functions, labels,
classes and user-defined entities are called Identifiers. Each element of a C++
program are given an identifier. A C++ identifier can be of any length, there is
no limit on the length of the identifiers in C++.
For Example:
int Interest;
int getSimpleInterest(int amount);

Interest is an identifier for a variable of integer data type and


getSimpleInterest is an identifier for a function. C++ identifiers are case
sensitive, which means 'value' and 'Value' will be treated as two different
identifiers.
Rules for Writing Identifiers
• An identifier cannot be same as a C keyword.
• The first character of an identifier must be either an alphabet or
underscore.
• An identifier can be composed of alphabets, digits, and
underscore only.
• Identifier name is case sensitive. "Home" and "home" is
recognised as two separate identifiers.
• Any special characters other than alphabets, digits, and
underscore (such as :, . ,blank space, / are not allowed).
Here are few examples of valid and invalid Identifiers.

Valid Identifiers Invalid Identifiers

hello 1hello

Hello Hel/lo

_hello hel lo

hello_world hello,,,world
C++ Data Types
In C++ programming language, data type specifies the type of data a variable
can store and how much memory is required to store this data. The data type
of a variable also defines the format in which a data of particular type should
be stored.

C++ Primitive Data Types


There are seven basic data types in C++ programming language.
• Boolean
• Character
• Integer
• Floating point
• Double floating point
• Void
• Wide character
All other user defined data types(like structure, classes etc) are derived from
these basic data types.

C++ Data Type Modifiers


C++ data type modifiers specifies the amount of memory space to be
allocated for a variable. Modifiers are prefixed with basic data types to modify
the amount of memory allocated for a variable.
For Example in a 16 bit system, the size of int data type is 2 bytes. If we add
long prefix in integer variable declaration(long int), it's size becomes 8 bytes.
There are four data type modifiers in C++ Programming Language:
• long
• short
• signed
• unsigned
The size of basic data types is system dependent. Size of an integer data type
in a 32 bit computer is 4 bytes whereas size of integer data type in 16 bit
computer is 2 bytes. We can use sizeof operator to know the exact size of any
data type.
The following table, shows the different basic data types, their size and value
range in a 32 bit operating system.

Data Types Memory Occupied in bytes Min-Max Range

char 1 bytes -128 to 127 or 0 to 255

unsigned char 1 bytes 0 to 255

signed char 1 bytes -128 to 127

wchar_t 2-4 bytes 1 wide character

short int 2 bytes -32768 to 32767

unsigned short int 2 bytes 0 to 65,535

signed short int 2 bytes -32768 to 32767

int 4 bytes -2147483648 to 2147483647

unsigned int 4 bytes 0 to 4294967295

signed int 4 bytes -2147483648 to 2147483647

long int 8 byte -2,147,483,648 to 2,147,483,647

signed long int 8 byte -2,147,483,648 to 2,147,483,647

unsigned long int 8 byte 0 to 4,294,967,295


Data Types Memory Occupied in bytes Min-Max Range

float 4 bytes +/- 3.4e +/- 38 (~7 digits)

double 8 bytes +/- 1.7e +/- 308 (~15 digits)

long double 8 bytes +/- 1.7e +/- 308 (~15 digits)

C++ Void Data Type


The void data type in C++ means no data. We cannot define variables of void
data types.

C++ Boolean Data Type


The boolean data type can only represent one of two states, true or false.
Keyword bool is used to declare variables of boolean type.
For Example:
bool isAvailable = true;

C++ Integer Data Type


Integer data type in C++ is used to store a value of numeric type. Memory size
of a variable of integer data type is dependent on Operating System, For
example size of an integer data type in a 32 bit computer is 4 bytes whereas
size of integer data type in 16 bit computer is 2 bytes.
Keyword int is used to declare variables of type integer. Range of integer(int)
data type in 16 Bit system is -32,768 to 32,767.
For Example:
int i = 2015;
Above statement declares a variable 'i' of integer data type and stores 2015 in
it's memory location.

C++ Character Data Type


Character data type is used to store a character. A variable of character data
type allocated only one byte of memory and can store only one character.
Keyword char is used to declare variables of type character. Range of
character(char) data type is -128 to 127.
For Example:
char c = 'A';

Above statement declares a variable 'c' of character data type and stores
character 'A' in it's memory location.

C++ Floating Point Data Type


Floating point data type in C++ can be sub-divided into two types on the basis
of precision and size.
• float : 4 bytes with six digits of precision.
• double : 8 bytes with ten digits of precisionfloat data type.
Floating point data type in C++ is used to store a value of decimal values.
Memory size of a variable of floating point data type is dependent on
Operating System, For example size of an floating point data type in a 16 bit
computer is 4 bytes. Keyword float is used to declare variables of floating
point type. Floating point data type provides up-to 6 digits of precision.
For Example:
float fl = 11.243567f;

Above statement declares a variable 'fl' of float data type and stores
11.243567f in it's memory location.
double data type
Floating point data type similar to float data type except it provides up-to ten
digit of precision and occupies eight bytes of memory.
For Example:
double d = 11676.2435676542;

Above statement declares a variable 'd' of double data type and stores
11676.2435676542 in it's memory location.

C++ Program to Show Size of Basic Data Types


1
2#include <iostream>
3using namespace std;
4
5int main(){
6 /*
* Size of Data type is dependent on Operating System
7
* I am running this program in a 32 bit OS
8 */
9 cout << "Size for char : " << sizeof(char) << endl;
10 cout << "Size for int : " << sizeof(int) << endl;
11 cout << "Size for float : " << sizeof(float) << endl;
12 cout << "Size for double : " << sizeof(double) << endl;
13
14 return 0;
15}

Output
Size for char : 1
Size for int : 4
Size for float : 4
Size for double : 8

As explained above, the size of a variable depends on the programming


environment. I ran above program in a 32 bit computer and produced above
output.
C++ Constants and Literals
Constants in C++ refers to immutable values that C++ program cannot
change during the course of execution. In C++, a constant can be of any basic
data types like boolean, character constants, integer constant, strings etc.
For Example : true, 'A', 754, 123.5, "Hello World".

Boolean literals in C++


C++ supports two boolean literals "true" and "false". true and false are part of
the C++ keywords.

Integer Constants in C++


Integer constants are whole numbers without any fractional part or
exponential part. It can either be positive or negative, If no sign precedes then
by default it is assumed to be positive. The range of integer constant depends
on programming environment. For Example, In a 16-bit system range of
integer literal is -32768 to 32767.
An integer constant can be a decimal, octal, or hexadecimal. A prefix specifies
the base of number system.

Prefix Description Base Exam

0x or 0X Hexadecimal Number 16 0x5C,

0 Octal Number 8 012C,

Nothing Decimal Number 10 25, 1

You can also specify the type of integer constant by using a suffix character. It
can be lowercase or uppercase and can be in any order.
• L, l : Long
• U, u : Unsigned
Examples of Integer Constants
• Unsigned Integer Constant : 100U, 565U
• Long Constant : 67L, -2398876L
• Unsigned Long Constant : 55UL, 77652UL
• Decimal Constants : 85, -54
• Octal Constants : 0213, 045
• Hexadecimal Constants : 0x4b, 0x2A

Character Constants in C++


Character constants are enclosed between a pair or single quote. C++,
supports two type of character constants, wide character literal and narrow
character literal. If a character literal starts with uppercase 'L' then it is a Wide
character (for Example : L'a') and must be stored in a variable of type wchar_t
otherwise it is a narrow character(for Example : 'a') and can be stored in
variable of type char. The ASCII value of character constants are stored
internally.
For Example : 'a', 'A', '1', '#' are character constants. C++ Backslash
Character Constants
There are some characters which are impossible to enter into a string from
keyboard like backspace, vertical tab, newline etc. C++ includes a set of
backslash character which have special meaning in C++ programming
language. The backslash character ('\') changes the interpretation of the
characters by C++ compiler.

Escape Sequence Description

\” Double quote(")

\' Single quote(')

\\ Backslash Character(\)
Escape Sequence Description

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\v Vertical tab

\a Alert or bell

\? Question mark

\0 Null character

C++ Program to print character constants


#include <iostream>
using namespace std;

int main() {
char c1 = 'E';
wchar_t wc = L'E';

cout << c1 << endl;


cout << wc << endl;
// Printing newline character
cout << '\n';
printf("Tech\nCrash\nCourse");

return(0);
}
Output
E
69

Tech
Crash
Course

C++ Floating-point Constants


A floating point constant has a integer part, a decimal point, a fractional part
and may contain an exponential part. Floating point literal may be positive or
negative but must have a decimal point. You can also represent floating point
literals in scientific notation.
For Example: 1234.5432, -100.001, 2.37E-3

C++ String Constants


p class="myParagraph"> A string constant in C++ is a set of characters
enclosed between a pair of double quotes. A string literal is actually a
character array. A string literal may contain any number of characters
including alphanumeric characters, escape characters, graphical characters
etc.
For Example

• "" : Null String.


• "A" : String literal having one characters.
• "XYZ12.iyu" : String literal with multiple characters.
• "XYZ jjuh\n" : String with spaces and escape characters.

Declaration of Constants in C++


We can define constants in C++ in two ways.
1. Using const keyword.
2. Using #define preprocessor directives.
We can use const keyword as a prefix of data type to declare a Constant.
Here is the syntax for using const keyword.
const data_type variable_name = Constant;
For Example
const float INTEREST_PERSENTAGE = 9;
#include Preprocessor Directive
We can use #define preprocessor directive to define a constant as per
following syntax.
#define Constant_Identifier Value
For Example:
#define INTEREST_PERSENTAGE 9
C++ Program to show use of #include preprocessor
#include <iostream>
#define PI 3.141

using namespace std;

int main() {
float radius;

cout << "Enter Radius of Circle\n";


cin >> radius;

cout << "Circumference of Circle : " << 2*PI*radius;

return 0;
}

Output
Enter Radius of Circle
5.0
Circumference of Circle : 31.41
C++ Operators
In C++, an operator is a symbol used to perform logical and mathematical
operations in a C++ program. An expression ia a statement containing
operators and variables. C++ operators connects constants and variables to
form expressions.
For Example:
3.141 x radius x radius;

• x is operator
• 3.141 is a constant
• radius is a variables
• "3.141 x radius x radius;" is an expression, performing one logical
task.
C++ programming language is rich in built in operators.

C++ Assignment Operators


Assignment Operator in C++ is used to assign a value to a variable. "=" is
called simple assignment operator in C++, it assigns values from right side
operands(R value) to left side operand (L value).
syntax of assignment operator
variable_name = expression;
For Example:
age = 25;
count = 500;

C++ also supports compound assignment operators. These operators are


combination of arithmetic and assignment operators. They first perform
arithmetic operation between left and right operand and then assign the result
to left operand.
• var+=10; is equivalent to var = var+10;
It first add 10 to var, and then assign result to var.
List of Shorthand Assignment Operators Supported in C++
Operator Example Equivalent Expression Description

+= A += B; A = A+B; It Adds A and B, then assign result to A

-= A -= B; A = A-B; It subtract B from A, then assign result t

/= A /= B; A = A/B; It divides A by B, then assign result to A

*= A *= B; A = A*B; It multiply A and B, then assign result to

%= A %= B; A = A%B; It takes modulus of A by B, then assign

&= A &= B; A = A&B; It does bitwise AND between A and B, t


result to A

|= A |= B; A = A|B; It does bitwise OR between A and B, the


result to A

^= A ^= B; A = A^B; It does bitwise XOR between A and B, t


result to A

>>= A >>= B; A = A>>B; It does bitwise right shift, then assign re

<<= A <<= B; A = A<<b;< td="" It does bitwise left shift, then assign resu
style="box-sizing:
border-box;"></b;<>

C++ Arithmetic Operators


Arithmetic operators in C++ are used to perform mathematical operations.
There are five fundamental arithmetic operators supported by C++ language,
which are addition(+), subtraction(-), division(/), multiplication(-), and
modulus(%) of two numbers.

Operator Description Syntax Exam

+ Adds two numbers a+b 15 + 5 = 20

- Subtracts two numbers a-b 15 - 5 = 10

* Multiplies two numbers a*b 15 * 5 = 75

/ Divides numerator by denominator a/b 15 / 5 = 3

% Returns remainder after an integer a%b 15 % 5 = 0


division

C++ Relational Operators


Relational Operators in C++ are used to compare two values. It specifies the
relation between two values like equal, greater than, less than etc. Relational
operators always returns boolean value (zero for false and non-zero value for
true).
For Example :
(X < Y) : It checks whether X is less than Y or not. It will return none-zero(true)
if X is less than Y otherwise zero(false).
Below is the list of Relational Operators Supported in C++
Relational Operator Example Description

> A>B Checks if A is greater than B

< A<B Checks if A is less than B


Relational Operator Example Description

>= A >= B Checks if A is greater than or equal to B

<= A <= B Checks if A is less than or equal to B

== A == B Checks if A is equal to B

!= A != B Checks if A is not equal to B

C++ Logical Operators


Logical Operators in C++ combines multiple boolean expressions. If we want
to combine multiple boolean statements, then we need logical Operators.
Logical Operators in C++ always produces boolean results, either TRUE(non-
zero value) or FALSE(zero value). There are 3 logical operators in C++
language AND(&&), OR(||) and NOT(!).
• AND : Returns true, If both operands are true otherwise false.
• OR : Returns false If both operands are false, otherwise true.
• NOT : Returns true if operand is false and Returns false if
operand is true.
Here is the truth table of Logical Operators
A B A && B A || B

TRUE FALSE FALSE TRUE F

TRUE TRUE TRUE TRUE F

FALSE TRUE FALSE TRUE T


A B A && B A || B

FALSE FALSE FALSE FALSE T

C++ Bitwise operators


C++ inherits the mid-level language features from C. It support many
operations which can be performed in assembly language like operations on
bits. Bitwise operators performs bit-by-bit operations on operands. There are
six bitwise operators supported by C++.

Bitwise Operator Syntax Description

| A|B Bitwise OR Operator

& A&B Bitwise AND Operator

~ ~A NOT Operator(One's Complement)

^ A^B Bitwise Exclusive OR Operator

>> A >> B Right Shift Operator

<< A << B Left Shift Operator

C++ Conditional Operator


C++ Conditional operators are also called as Ternary Operator. Conditional
Operator is a powerful Operator which can be used to implement if-then-else
type of logic.
Syntax of Ternary Operator
Conditional_Expression ? Expression_One : Expression_Two;
Ternary Operator will execute Expression_One if Conditional_Expression is
true, otherwise it execute Expression_Two.
For Example int X = 25;
int Y = (X > 20 ? 1 : 2);
As X > 20, So after above statement Y's value becomes 1.
C++ If Statement
The if statement in C++ programming language is used to execute a block of
code only if a condition is true. It is used to check the truthness of the
expression (In C++, all non-zero values are considered as true and zero is
considered as false).
Syntax of If Statement
if(boolean_expression) {
// code to be execute if the boolean_expression is true
}

• Condition written inside If statement parenthesis must be a


boolean expression.
• The if statement first evaluates the boolean expression inside
parenthesis.
• If the boolean_expression evaluated to true, then the block of
code inside the if statement is executed.
• If boolean_expression evaluated to false, then the block of code
inside the if statement is ignored and the next statement after if block is
executed.

C++ If statement Example Program


#include <iostream>
1
using namespace std;
2
3
int main(){
4
5
int score;
6
cout << "Enter your score : ";
7
cin >> score;
8
/* Using if statement to check whether
9
a student failed in examination or not*/
10
if(score < 30){
11
// if condition is true then print the following
12
13 cout << "You Failed :(\n";

14 }

15 // This line always gets printed

16 cout << "Your score : " << score;


17
18 return 0;
19}

Output
Enter your score : 45
Your score : 45
Enter your score : 25
You Failed :(
Your score : 25

Points to Remember about If Statement


• If statement allows the program to select an action based upon
the user's input or the result of an expression. It gives us flexibility to
change the logic of a program in different situations.
• The conditional_expression must be a boolean expression. It
must evaluate to true or false value(In C++, all non-zero values are
considered as true and zero is considered as false).
• We may use more than one condition inside if statement
For Example:
if(condition_one && condition_two) {
/* if code block */
}
• Opening and Closing Braces are optional, If the block of code of if
statement contains only one statement
For Example:
if(condition_expression)
statement1;
statement2;
In above example only statement1 will gets executed if
condition_expression is true. To execute more than one statements
after if statement evaluates to true, we have to use braces like the body
of a function.
C++ If Else Statement
The if else statement in C++ programming language execute if block
statements if condition is true and execute else block statements when
condition is false.
Syntax of if else statement
if(condition_expression) {
// statements to be execute if the condition_expression is true
} else {
// statements to be execute if the condition_expression is false
}
• Condition written inside If statement parenthesis must be a
boolean expression.
• Either if block or else block gets executed(not both) depending on
the outcome of conditional expression. Both if and else block of
statements can never execute at a time.
• If the condition_expression evaluated to true, then the if block of
code gets executed.
• If condition_expression evaluated to false, then the block of code
inside the if body is ignored and block of code inside the else body is
executed.
C++ If Else Statement Example Program
#include <iostream>
using namespace std;

int main() {
int score;
cout << "Enter your score : ";
cin >> score;
/* Using if else statement to decide whether
a student passed or failed in examination */
if(score < 35){
// if condition is true then print the following
cout << "You Failed :(\n";
} else {
// if condition is false then print the following
cout << "Congrats You Passed :)\n";
}
// This line always gets printed
cout << "Your score : " << score;
return 0;
}

Output
Enter your score : 25
You Failed :(
Your score : 25
Enter your score : 60
Congrats You Passed :)
Your score : 60

Points to Remember about If Else Statement

• If else statement allows the program to select one of the two


action based upon the user's input or the result of an expression. It
gives us flexibility to change the logic of a program in different
situations.
• The condition_expression must be a boolean expression. It must
evaluate to true or false value(In C++, all non-zero values are
considered as true and zero is considered as false).
• We may use more than one condition inside if else statement. We
can use relational and logical operators like >, <, ==, && etc to create
compound boolean expressions.
For Example:
if(condition_one && condition_two) {
/* if code block */
} else {
/* else code block */
}
• Opening and Closing Braces are optional, If the block of code of if
else statement contains only one statement.
For Example:
if(condition_one && condition_two)
statement1;
else
statement2
In above example only statement1 will gets executed if
condition_expression is true otherwise statement2.
C++ If Else Ladder Statement
• The if else ladder statement in C++ programming language is
used to check set of conditions in sequence.
• This is useful when we want to selectively executes one code
block(out of many) based on certain conditions.
• It allows us to check for multiple condition expressions and
execute different code blocks for more than two conditions.
• A condition expression is tested only when all previous if
conditions in if-else ladder is false.
• If any of the conditional expression evaluates to true, then it will
execute the corresponding code block and exits whole if-else ladder.

Syntax of if else ladder statement


if(condition_expression_One) {
statement1;// Statements executes when the
condition_expression_One is true
} else if (condition_expression_Two) {
statement2;// Statements executes when the
condition_expression_Two is true
} else if (condition_expression_Three) {
statement3;// Statements executes when the
condition_expression_Three is true
} else {
statement4;// Statements executes when none of the above conditions
evaluates to true
}
• First condition_expression_One is tested and if it is true then
following code block will execute and control comes out out of whole if
else ladder.
• If condition_expression_One is false then only
condition_expression_Two is tested. Control will keep on flowing
downward, If none of the conditional expression is true.
• The last else is the default block of code which will gets executed
if none of the conditional expression is true.
• If none of the conditional expressions evaluates to true then last
else block will executes.
C++ If Else Ladder Statement Example Program
#include <iostream>
using namespace std;

int main(){
int score;

cout << "Enter your score between 0-100\n";


cin >> score;
/* Using if else ladder statement to print
Grade of a Student */
if(score >= 90){
// Marks between 90-100
cout << "YOUR GRADE : A\n";
} else if (score >= 70 && score < 90){
// Marks between 70-89
cout << "YOUR GRADE : B\n";
} else if (score >= 50 && score < 70){
// Marks between 50-69
cout << "YOUR GRADE : C\n";
} else {
// Marks less than 50
// if none of the conditions is true
cout << "YOUR GRADE : Failed\n";
}

return 0;
}

Output
Enter your score between 0-100
72
YOUR GRADE : B
Enter your score between 0-100
10
YOUR GRADE : Failed

Points to Remember about If else ladder statement

• The condition_expression must be a boolean expression. It must


evaluate to true or false value(In C++, all non-zero values are
considered as true and zero is considered as false).
• An if block can have zero or more else if blocks. All else if blocks
must be before else block(if any).
• We may use more than one condition inside if else ladder
statement
For Example:
if(condition_one && condition_two) {
/* if code block */
} else if(condition_three) {
/* else code block */
}
• Default else block is optional in if-else ladder statement.
• Only of the else-if code block will execute. If none of the else if
conditions evaluates to true then default else code block executes.
• Opening and Closing Braces are optional, If the block of code of if
else statement contains only one statement.
For Example:
if(condition_expression)
statement1;
else if(condition_expression)
statement2;
In above example only statement1 will gets executed if
condition_expression is true.
C++ Switch Case Statement
A switch statement in C++ allows a variable or value of an expression to be
tested for equality against a list of possible case values and when match is
found, the block of code associated with that case is executed. It is similar to
if..else ladder statement, but the syntax of switch statement is more readable
and easy to understand.

Syntax of Switch Statement


switch(expression) {
case constant1 :
// statements to be executed when value of expression equals
constant1
break;
case constant2 :
// statements to be executed when value of expression equals
constant2
break;
case constant3 :
// statements to be executed when value of expression equals
constant3
break;
default :
// Default block will execute when none of the case matches }
Important Points about Switch Statement in C++
• Switch case performs only equality check of the value of
expression/variable against the list of case values.

• Case constants must be unique. We cannot write two case blocks


with same constants.
• The expression in switch case must evaluates to return an
integer, character or enumerated type.

• You can use any number of case statements within a switch.

• One switch statement can have maximum of one default label.


Default block can be placed anywhere in switch statement.

• The data type of the value of expression must be same as the


data type of case constants.

• The break statement is optional. The break statement at the end


of each case cause switch statement to exit. If break statement is not
used, all statements below that case statement are also executed until it
found a break statement.

• The default code block gets executed when none of the case
matches with expression. default case is optional and doesn't require a
break statement.

C++ Switch Statement Example Program


1#include <iostream>
2using namespace std;
3
4int main(){
5 int n;
6
7 cout << "Enter a number between 1 to 6\n";
8 cin >> n;
9
10 switch(n){
11 case 1 :
12 /* following code will execute when n == 1 */
13
cout << "ONE\n";
14
break;
15
case 2 :
16
/* following code will execute when n == 2 */
17
cout << "TWO\n";
18
break;
19
case 3 :
20
/* following code will execute when n == 3 */
21
cout << "THREE\n";
22
break;
23
case 4 :
24
case 5 :
25
26 case 6 :

27 /* following code will execute when n==4 or n==5 or n==6*/

28 cout << "FOUR, FIVE OR SIX\n";

29 break;
30 default :
31 /* following code will execute when n < 1 or n > 6 */
32 cout << "INVALID INPUT\n";
33 }
34
35 cout << "Always gets printed\n";
36
37 return 0;
}

Output

Enter a number between 1 to 6


3
THREE
Always gets printed
Enter a number between 1 to 6
6
FOUR, FIVE OR SIX
Always gets printed
Enter a number between 1 to 6
8
INVALID INPUT
Always gets printed

Advantages and Disadvantages of Switch Case in C++


Advantages of Switch Case
• The complexity of the program increases as the number of
constants to compare increases. Switch statement provides a way to
write easy to manage and readable code.
• Switch statement provides a default case handler when no case
matches.
• We can nest switch statements like if else statements.
• The syntax of switch case is easy to understand and more
readable.
Disadvantages of Switch Case
• Switch statements can only be used to perform equality
comparison, we cannot perform conditional checks using relational or
logical operators like >, <, >==, &&, || etc.
C++ For Loop
The for loop in C++ is used to execute execute some statements repetitively
until the given condition is true. The for loop is mainly used to perform
repetitive tasks.
Syntax of for Loop
for(initialization; condition; update) {
/* code to be executed */
}

For Example:
for(i = 1; i <= 10; i++){
cout << i;
}

Above for loop prints integers from 1 to 10;

For Loop Syntax Description


• Initialization : The Initialization statement allows us to declare
and initialize any loop variables. It is executed only once at the
beginning of the for loop.

• Condition : After initialization, condition expression is evaluated.


It is a boolean expression which decides whether to execute loop's body
or terminate for loop. if condition expression evaluates to true, the for
loop code block gets executed otherwise it will terminate for loop and
control goes to the next statement after the for loop.

• Update : After code block of for loop gets executed, control


comes back to update statements. It allow us to modify any loop
variable for next iteration of loop. This step is mainly used for updating
loop control variable.
• All three fields of a for loop are optional. They can be left empty,
but in all cases the semicolon signs between them are required.

Control Flow Diagram of for loop

How for loop works


• The Initialization statement will be executed first. We can declare
and initialize any number of loop control variables here.
• After the Initialization statement the condition expression is
evaluated. If the value of condition expression is true then code block of
for loop will be executed otherwise the loop will be terminated.
• After execution of the code block of for loop control goes to
update statements of the loop statement which modifies the loop control
variables.
• After modifying control variables in update statements, control
again goes to condition expression.
• For loop iteration continues unless condition expression becomes
false or for loop gets terminated using break statement.

C++ for Loop Example Program


#include <iostream>
using namespace std;

int main(){
int N, i, sum=0;

cout << "Enter a positive number\n";


cin >> N;
// Using for loop to find the sum
// of all integers from 1 to N
for(i=1; i <= N; i++){
sum+= i;
}

printf("Sum of all numbers from 1 to %d = %d", N, sum);

return 0;
}

Output
Enter a positive number
6
Sum of all numbers from 1 to 6 = 21
In above program, we first take a number N as input from user. Now, we have
to find sum of all numbers from 1 to N. We are using a for loop to iterate from
1 to N and add each number to variable sum.

For Loop Facts


• The condition_expression in for loop is a boolean expression. It
must evaluate to true or false value(In C++, all non-zero values are
considered as true and zero is considered as false).

• Initialization statement, Condition expression and Update


statement are all optional in for loop.

• You can use multiple initialization statements and update


statements inside for loop.
For Example:
for(i=0, j=50; i < 100; i++, j--)

• Opening and Closing braces are not required for single statement
inside for loop code block.
For Example:
for(i = 0; i < 100; i++)
sum+= i;

• We can also use infinite for loops like for(;;), which will never
terminate. You should add terminating condition using break statement
in order to terminate infinite for loop.
For Example:
for(;;){
if(.....){
break;
}
}
C++ While Loop
The while loop in C++ used for repetitive execution of the statements until the
given condition is true. Unlike for loop in C++, there is no initialization and
update statements in while loop.

Syntax of while Loop in C++


while(condition) {
// statements to be executed
}

While Loop Syntax Description

• condition : Condition expression is evaluated before code block


of while loop. It is a boolean expression which decides whether to go
inside the loop or terminate while loop. If condition expression evaluates
to true, the code block inside while loop gets executed otherwise it will
terminate while loop and control goes to the next statement after the
while loop.
• statement : While loop can contain any number of statements
including zero statements. while loop body should change the values
checked in the condition in some way, so as to force the condition to
become false at some point. Otherwise, the loop will never terminate.

Flow Diagram of while Loop Statement


While loop evaluate the condition expression. If the value of condition
expression is true then code block of while loop(statements inside {} braces)
will be executed otherwise the loop will be terminated. While loop iteration
continues unless condition expression becomes false or while look gets
terminated using break statement.

C++ While Loop Example Program


#include <iostream>
using namespace std;

int main(){

int N, i, sum=0;
cout << "Enter a positive number\n";
cin >> N;
/*
* Initializing loop control variable before while loop
*/
i = 1;
while(i <= N){
// Below statements will only execute if while loop
// condition evaluates to true
sum+= i;
//Incrementing loop control variable
i++;
}
cout << "Sum of Integers from 1 to %d = %d", N, sum;

return 0;
}

Output
Enter a positive number
5
Sum of Integers from 1 to 5 = 15
Enter a positive number
7
Sum of Integers from 1 to 7 = 28

In above program, we first take an integer N as input from user. We want to


find sum of all integer from 1 to N. Here, we are using while loop to traverse
all elements from i=1 to N. While loop will terminate when i becomes > N.

While Loop Interesting Facts


• The condition_expression in while loop is a boolean expression. It
must evaluate to true or false value(In C++, all non-zero values are
considered as true and zero is considered as false).

• Unlike for loop, initialization statements, condition expression and


update statements are on different line.

• Unlike do..while loop, the body of while might not executes even
once.
• Opening and Closing braces are not required for single statement
inside while loop code block.
For Example:
while(i < 100)
sum+= i;

• We can also use infinite while loops like while(1), which will never
terminate. You should add terminating condition using break statement
in order to terminate infinite while loop.
For Example:
while(1) {
if(.....){
break;
}
}
C++ do while Loop
The do while loop in C++ is similar to while loop with one important difference,
the code block of do..while loop is executed once before the condition is
checked. It checks its condition at the bottom of the loop, before allowing the
execution of loop body for second time. The block of code is before the
condition, so code will be executed at lease once.

Syntax of do while Loop


do {
statement(s);// statements to be executed
}while(condition);
do while Loop Syntax Description
• condition : The condition expression in do while loop is a boolean
expression. Condition expression is evaluated after code block of do-
while loop. It must evaluate to true or false value(In C++, all non-zero
values are considered as true and zero is considered as false).
• statement(s) : do while loop's body can contain zero or more
number of statements. Unlike for and while loop, all statements inside
do-while loop will gets executed atleast once.
• Unlike while loop, there is semicolon in the end of
while(condition); in do..while loop.

Flow diagram of do while Loop in C++


How do while loop works ?
• First do while loop execute the statements inside body of the loop.
• Then, the condition expression is tested. If the condition
expression evaluates to true then body of do..while loop is executed.
• If the condition expression evaluates to false then do..while loop is
terminated and control goes to the next statement after do..while loop.
NOTE : Do While loop can get terminated from loop body by executing break
statement.

C++ do..while Loop Example Program


#include <iostream>
using namespace std;

int main(){

int N, i, sum=0;
cout << "Enter a positive number\n";
cin >> N;
i = 1;
do {
// Below statements will execute atleast once
sum+= i;
//Incrementing loop control variable
i++;
} while(i <= N);
cout <<"Sum of Integers from 1 to " << N << " = " << sum;

return 0;
}

Output
Enter a positive number
5
Sum of Integers from 1 to 5 = 15
Enter a positive number
7
Sum of Integers from 1 to 7 = 28

Points to Remember about do while loop

• do…while loop is guaranteed to execute at least once.

• The condition expression in do while loop is a boolean


expression. It must evaluate to true or false value(In C++, all non-zero
values are considered as true and zero is considered as false).

• Unlike for loop, initialization statements, condition expression and


update statements are on different line.

• Opening and Closing braces are not required for single statement
inside do while loop code block.
For Example:
do
statement;
while(condition);

• We can also use infinite do while loops which will never terminate.
You should add terminating condition using break statement in order to
terminate infinite do while loop.
For Example:
do {
if(....){
break;
}
} while(1);
C++ goto Statement
The goto statement in C++ is used to transfer the control of program to some
other part of the program. A goto statement used as unconditional jump to
alter the normal sequence of execution of a program.

Syntax of a goto statement in C++


goto label;
...
...
label:
...

• label : A label is an identifier followed by a colon(:) which


identifies which marks the destination of the goto jump.
• goto label: : When goto label; executes it transfers the control of
program to the next statement label:.

C++ goto Statement Example Program


#include <iostream>
using namespace std;

int main(){

int N, counter, sum=0;


cout<< "Enter a positive number\n";
cin >> N;

for(counter=1; counter <= N; counter++){


sum+= counter;
/* If sum is greater than 50 goto
statement will move control out of loop */
if(sum > 50){
cout << "Sum is > 50, terminating loop\n";
// Using goto statement to terminate for loop
goto label1;
}
}
label1:
if(counter > N)
cout << "Sum of Integers from 1 to " << N <<" = "<< sum;

return 0;
}
Output
Enter a positive number
25
Sum is > 50, terminating loop
Enter a positive number
8
Sum of Integers from 1 to 8 = 36

In above program, we first take an integer N as input from user using cin. We
wan to find the sum of all numbers from 1 to N. We are using a for loop to
iterate from i to N and adding the value of each number to variable sum. If
becomes greater than 50 then we break for loop using a goto statement,
which transfers control to the next statement after for loop body.

Disadvantages of goto statement

• goto statement ignores nesting levels, and does not cause any
automatic stack unwinding.
• goto statement jumps must be limited to within same function.
Cross function jumps are not allowed.
• goto statement makes difficult to trace the control flow of program
and reduces the readability of the program.
• Use of goto statement is highly discouraged in modern
programming languages.

Uses of goto Statement


The only place where goto statement is useful is to exit from a nested loops.
For Example :
for(...) {
for(...){
for(...){
if(...){
goto label1;
}
}
}
}
label1:
statements;

In above example we cannot exit all three for loops at a time using break
statement because break only terminate the inner loop from where break is
executed.

Any program written in C++ language using goto statement can be re-written
using break and continue statements.
C++ break Statement
The break statement in C++ is used to terminate loops and switch statement
immediately when it appears. We sometimes want to terminate the loop
immediately without checking the condition expression of loop. Most of the
time, break statement is used with conditional statement inside body of the
loop.
Use of break statement, change the normal sequence of execution of
statements inside loop.

Syntax of break Statement


break;
Uses of break Statement
• We can use break statement inside any loop(for, while and do-
while). It terminates the loop immediately and program control resumes
at the next statement following the loop.
• We can use break statement to terminate a case in the switch
statement.
• It can be used to end an infinite loop.
• If we are using break statement inside nested loop, then it will
only terminate the inner loop from where break is executed.

C++ break Statement Example Program


#include <iostream>
using namespace std;

int main(){

int N, counter, sum=0;


cout<< "Enter a positive number\n";
cin >> N;

for(counter=1; counter <= N; counter++){


sum+= counter;
/* If sum is greater than 50 break
statement will terminate the loop */
if(sum > 50){
cout << "Sum is > 50, terminating loop\n";
// Using break statement to terminate for loop
break;
}
}
if(counter > N)
cout << "Sum of Integers from 1 to " << N <<" = "<< sum;

return 0;
}

Output
Enter a positive number
20
Sum is > 50, terminating loop
Enter a positive number
7
Sum of Integers from 1 to 7 = 28

Above program find sum of all integers from 1 to N, using for loop. It sum is
greater than 50, break statement will terminate for loop.
C++ break Statement
The break statement in C++ is used to terminate loops and switch statement
immediately when it appears. We sometimes want to terminate the loop
immediately without checking the condition expression of loop. Most of the
time, break statement is used with conditional statement inside body of the
loop.
Use of break statement, change the normal sequence of execution of
statements inside loop.

Syntax of break Statement


break;
Uses of break Statement
• We can use break statement inside any loop(for, while and do-
while). It terminates the loop immediately and program control resumes
at the next statement following the loop.
• We can use break statement to terminate a case in the switch
statement.
• It can be used to end an infinite loop.
• If we are using break statement inside nested loop, then it will
only terminate the inner loop from where break is executed.

C++ break Statement Example Program


#include <iostream>
using namespace std;

int main(){

int N, counter, sum=0;


cout<< "Enter a positive number\n";
cin >> N;

for(counter=1; counter <= N; counter++){


sum+= counter;
/* If sum is greater than 50 break
statement will terminate the loop */
if(sum > 50){
cout << "Sum is > 50, terminating loop\n";
// Using break statement to terminate for loop
break;
}
}
if(counter > N)
cout << "Sum of Integers from 1 to " << N <<" = "<< sum;

return 0;
}

Output
Enter a positive number
20
Sum is > 50, terminating loop
Enter a positive number
7
Sum of Integers from 1 to 7 = 28

Above program find sum of all integers from 1 to N, using for loop. It sum is
greater than 50, break statement will terminate for loop.
C++ continue Statement
The continue statement in C++ is used to skip some statements inside the
body of the loop and forces the next iteration of the loop. The continue
statement skips the rest of the statements of loop body in the current iteration.
Most of the time, continue statement is used with conditional statement inside
body of the loop. Use of continue statement, change the normal sequence of
execution of statements inside loop.
• Inside while and do..while loop, continue statement will take
control to the condition statement.
• Inside for loop, continue statement will take control to the update
statement(increment/decrement of loop control variable) then condition
will be checked.

Syntax of continue Statement


continue;

Flow Diagram of continue Statement


Uses of continue Statement
• We can use continue statement inside any loop(for, while and do-
while). It skips the remaining statements of loop's body and starts next
iteration.
• If we are using continue statement inside nested loop, then it will
only skip statements of inner loop from where continue is executed.

C++ continue Statement Example Program


#include <iostream>
using namespace std;

int main(){
int N, counter, sum=0;
cout << "Enter a positive number\n";
cin >> N;

for(counter=1; counter <= N; counter++){


//Using continue statement to skip all odd numbers
if(counter%2 == 1){
continue;
}
sum+= counter;
}
cout <<"Sum of all even numbers from 1 to " <<N<<" = "<< sum;

return 0;
}
Output
Enter a positive number
6
Sum of all even numbers from 1 to 6 = 12

In above program, we first take an integer N as input from user. We want to


find the sum of all even numbers between 1 to N. If counter is odd number
then continue statement will force next iteration without executing sum
statement. Here, continue statement is used to skip all odd numbers while
finding even numbers sum.
C++ Functions
Functions in C++ language are building blocks of a C++ program. A function is
a sequence of statements to perform a specific task and it can be called by
other functions. A function may take some input and perform a logical unit of
task and may return the response to calling function.
The function in C++ language is also known as subroutine, procedure or
method.
• A C++ program is a set of functions calling each other.
• We can use any number of functions in a C++ program.
• All C++ programs must contains at least one main() function.
• When a function exits, it return control to the calling function from
where it is called.
• There are two types of functions depending on whether a function
is created by programmer or is pre-defined in library.

Advantage of Functions in C++ Programming


• We can call a function any number of times in a program from any
place which avoid rewriting same code again and again at various
program.
• A large C++ program can divide into set of functions, where each
function owns the responsibility of performing one specific task.
Functions are written in order to make C++ program modular.
• We can add common utility functions in header files, So that It can
be reused by other programs.
• When a function exits, it return control to the calling function from
where it is called.
• Breaking a large C++ program into functions, makes it easy to
maintain, more readable and easy to understand.

How Functions work in C++ Programming


• First of all main() function of C++ program gets called by
Operating system.
• Execution of C++ program begins. Program's statements and
expressions getting executed in top to bottom sequence.
• When control reaches a function call lets say myFunction(int val);
it pauses the execution of current function and control goes inside the
called function myFunction.
• Once execution of code inside myFunction body finishes control
comes back to the calling function. It resumes the execution of calling
function at the next statement following the function call of myFunction.
• At the point of any function call, control keeps on jumping
between calling function and called function.
• C program terminates when execution of main function ends.

Function Declaration in C++


A function declaration in C++ tells the compiler about function name, function
parameters and return value of a function. The actual body of the function can
be defined separately. Like variable in C, we have to declare functions before
their first use in program.
Syntax of Function Declaration in C++
return_type function_name(type arg1, type arg2 .....);
• Function declaration is also known as function prototype.
• Function declaration in C++ always ends with a semicolon.
• By default the return type of a function is integer(int) data type.
• Name of parameters are not compulsory in function declaration
only their type is required. Hence following declaration is also valid. int
getSum(int, int);
• If function definition is written before main function then function
declaration is not required whereas, If function definition is written after
main function then we must write function declaration before main
function.

For Example
• Declaration of a function with no input parameters
void printName();

• Declaration of a function with one input parameter and integer


return type
int isPrimeNumber(int num);

• Declaration of a function with multiple input parameter and integer


return type.
int getProduct(int num1, int num2);

• Declaration of a function with no input parameters and integer


return type.
int getRandomNumber();

C++ Function Declaration Example Program


#include <iostream>
using namespace std;

// Function Declaration
int getSum(int a, int b);

int main(){
int a, b, sum;
cout << "Enter two numbers\n";
cin >> a >> b;
// Calling getSum function
sum = getSum(a, b);
cout << "SUM = " <<sum;

return 0;
}
// Function Defination
int getSum(int a, int b) {
return a+b;
}
Output
Enter two numbers
3 6
SUM = 9

In above program, we declared a function named "getSum" before main,


which takes two integer parameters. After main, we defined the function to
add two numbers and return sum.

Function Definition in C++


A function definition in C++ language consists of function name, function
parameters, return value and function's body.
Syntax of Function Definition
return_type function_name(type arg1, type arg2 .....) {
body of a function
return (expression);
}

• return_type : The return_type is the data type of the value


returned by the function. void data type is used when the function does
not return any value. By default the return type of a function is
integer(int).
• function_name : This is a C++ identifies representing the name
of the function. Every function must have a unique name in a C++
program. Name of a function is used to call a function.
• type arg1, type arg2 ..... : It is a comma-separated list of data
types and names of parameters passed by the calling function. The
parameter list contains data type, order, and number of the parameters
expected by a function at the time of calling it. Parameters field is
optional, we can skip it if a function don't require any data from calling
function.
• body of a function : The body of a function contains a set of
statements that will be executed when this function is called. It may
define it's own local variables and call other functions.
• return(expression) : This is used to send a value to calling
function before termination of function. If the return type of function is
void, you need not use this line. When control reaches return statement,
it halts the execution of function immediately and returns the value of
expression to calling function.

Points To Remember
• First line is called as Function Header and it should be identical to
function Declaration/Prototype except semicolon.
• Function's definition contains code to be executed when this
function is called.
• Name of arguments are compulsory here unlike function
declaration.

C++ Function Definition Example Program


#include <iostream>
using namespace std;

// Function Defination
int getAreaOfSquare(int side){
// local variable declaration
int area;
area = side*side;
// Return statement
return area;
}

int main(){
int side, area;

cout << "Enter side of square\n";


cin >> side;
// Calling getAreaOfSquare function
area = getAreaOfSquare(side);
cout << "Area of Square = " << area;

return 0;
}

Output
Enter side of square
5
Area of Square = 25
C++ Calling a Function and Return Statement
Calling a function in C++ programming language
After writing a function in C++, we should call this function to perform the task
defined inside function body. We cannot execute the code defined inside
function's body unless we call it from another function.
When a function X calls another function Y, program control is transferred to
function Y. Function Y performs specific task defined in function's body and
when function Y terminates either by return statement or when the last
statement of function body executes, program control returns back to the
calling function X.

Syntax to Call a Function


function_name(argument1 ,argument2 ,...);
We can call a C++ function just by passing the required parameters along with
function name. If function returns a value, then we can store returned value in
a variable of same data type.
For Example :
int sum = findSum(2, 3);

Above statement will call a function named findSum and pass 2 and 3 as a
parameter. It also stores the return value of findSum function in variable sum.

C++ Example Program to call a Function


#include <iostream>
using namespace std;

// Function Defination
int getAreaOfSquare(int side){
// local variable declaration
int area;
area = side*side;
// Return statement
return area;
}

int main(){
int side, area;

cout << "Enter side of square\n";


cin >> side;
// Calling getAreaOfSquare function
area = getAreaOfSquare(side);
cout << "Area of Square = " << area;

return 0;
}

Output
Enter radius of circle
4
Area of Circle = 50.256

In above program, we defined a function "getAreaOfSquare" which takes side


of a square as input parameter and return the area of the square. Inside main
function, we first take side of square as input from user using cin and then call
getAreaOfSquare function(by passing side of square) to get the area of
square.

C++ Return Statement


The return statement in C++ language terminates the execution of a function
and returns control to the calling function. A return statement can also return a
single value to the calling function. The return type of a function is defined in
function declaration before the name of the function. It is not necessary that
function will always return a value. If a function does not return a value, the
return type in the function declaration and definition is defined as void.
If no return statement is found in a function definition, then control
automatically goes to the calling function after the last statement of the
function body is executed.

Syntax of return Statement in C++


return expression;
Expression is optional. If present, is evaluated and then converted to the
return data type specified in function declaration.
C++ Passing Arguments to a Function
A function in C++ may needs data from calling function to perform it's task. It
accepts data as function arguments which is passed by calling function.
These variables to receive data from calling function are called the formal
parameters of the function. A function can be called by passing zero or more
parameters as per function declaration.
In C++, parameter(arguments) refers to data which is passed to function while
calling function. The formal parameters are similar to local variables inside the
function scope and are created when control enters into the function and gets
destroyed upon exit.
A Function in C++ can be called in two ways.
• Call by value
• Call by reference
First of all we should understand the meaning of actual and formal
parameters.
• Formal parameter : This is the argument which is used inside
body of function definition. It's is limited to the scope of function, it is
visible to statements in function's body only. It gets created when control
enters function and gets destroyed when control exits from function.
• Actual parameter : This is the argument which is used while
calling a function.
• A function can have many arguments of same or different data
types.
• The data type of the actual parameter must match with the data
type of formal parameter.
• The count of formal parameter and actual parameter must be
same.

Call by value
In call by value method a copy of actual arguments is passed into formal
arguments in the function definition. Any change in the formal parameters of
the function have no effect on the value of actual argument. Call by value is
the default method of passing parameters in C++. Different memories are
allocated for the formal and actual parameters.
C++ Program to Pass Arguments to Function as Call by Value
#include <iostream>
using namespace std;

void getDoubleValue(int F){


F = F*2;
cout << "F(Formal Parameter) = " << F;
}

int main(){
int A;
cout << "Enter a number\n";
cin >> A;
// Calling function using call by value
getDoubleValue(A);
/* Any change in the value of formal parameter(F)
will not effect the value of actual parameter(A) */
cout << "\nA(Actual Parameter) = " << A;

return 0;
}
Output
Enter a number
5
F(Formal Parameter) = 10
A(Actual Parameter) = 5

Above program shows that, their is no change in the value of A(Actual


parameter) even if the value of F(Formal parameter) changed inside function.

Call by reference
In call by reference method the address of the variable is passed to the formal
arguments of a function. Any change in the formal parameters of the function
will effect the value of actual argument. Same memory location is accessed by
the formal and actual parameters.
C++ Program to Pass Arguments to Function as Call by Reference
#include <iostream>
using namespace std;
void getIncrementValue(int *ptr){
*ptr = *ptr + 1;
cout << "F(Formal Parameter) = " << *ptr;
}

int main(){
int A;
cout << "Enter a number\n";
cin >> A;
// Calling function using call by reference
// by passing address of A
getIncrementValue(&A);
/* Any change in the value of formal parameter(F)
will effect the value of actual parameter(A) */
cout << "\nA(Actual Parameter) = " << A;

return 0;
}
Output
Enter a number
5
F(Formal Parameter) = 6
A(Actual Parameter) = 6

In above program, we passed the address of variable A to function


getIncrementValue, which incremented the value stored at location pointed by
pointer ptr. Here, any change in formal parameters of function will change the
value of actual parameter also because both are pointing to same memory
location.
C++ Programming Default Parameters
(Arguments)
C++ programming language provides flexibility to specify a default value for
function arguments. We have to specify the default value of the function
arguments during function declaration.
• It is not compulsory to specify default values for all arguments, but
if you provide default value for an argument X, then You must provide
default values for each argument after X otherwise program will not
compile.
• A function with three parameters may be called with only two
parameters. For this, the function declaration must include a default
value for third(last) parameter, which will be used by the function when
calling function passes fewer arguments.
For Example :
int getSum(int A, int B = 10){
return A + B;
}

Calling function can call getSum function by either passing one or two
parameters.

int sum = getSum(5); // Calling by passing only one argument.

Here, calling function is only passing value for formal parameter A(which is 5)
and parameter B will take default value which is 10. Hence, the value of sum
will be 15.

int sum = getSum(5, 6); // Calling by passing two argument.

Here, calling function is passing value for both parameters A and B. Both A
and B will contain the actual parameters passed by the calling. In this case
function will not use the default value for argument B. Hence, the value of sum
will be 11.

int sum = getSum(5, 6); // Calling by passing two argument.


Points To Remember
• If a value for that parameter is not passed when the function is
called, the default given specified for that parameter will be used.
• If a value of a parameter is passed will calling a function then the
default value is ignored and the passed value is used.

C++ Function Default Argument Example Program


#include <iostream>
using namespace std;

// Default value for B is 10


int getsum(int A, int B=10) {
return A + B;
}

int main () {
int sum;

// Passing values for both arguments,


// B will not take the default value
sum = getsum(5, 6);
cout << "Sum = " << sum << endl;

// Passing value only for one parameter(A)


// B will take the default of 10
sum = getsum(5);
cout << "Sum = " << sum << endl;

return 0;
}

Output
Sum = 11
Sum = 15

In above program, we defined a function called getSum with two input


parameters A and B. We have assigned default value of 10 to parameter B. In
main, we first call getSum function with two arguments as getsum(5, 6);. In
this case, formal parameters A and B takes 5 and 6 respectively. In second
call to getSum function, we pass only one argument getsum(5);. In this case,
formal parameter A becomes 5 and B takes default value which is 10.
C++ Storage Class
The Storage class in C++ defines the scope, life-time and where to store a
variable in C++ program. These specifiers precede the type that they modify.
There are four storage classes defined in C++ programming language
• auto
• static
• register
• extern

auto Storage Class


A variable which is declared inside a function or block is automatic variable by
default. We can declare automatic variables using auto keyword, but it is
rarely used because by default every local variable is automatic variable.
For Example :
int count;
auto int size;

Both count and size are automatic variable. C++ Local Variable(auto)
Example Program
#include <iostream>
using namespace std;

int main(){
// Automatic variable by default
int a = 5;
// Declaration of automatic variables using auto keyword
auto int b = 10;

cout << "Sum = " << a+b;

return 0;
}
Output
Sum = 15
static Storage Class
A local static variable is visible only inside their own function but unlike local
variables, they retain their values between function calls. We can declare
static variable by adding static keyword before data type in variable
declaration statement.
static data_type variable_name;
For Example :
static int count;

• Variables declared static are initialized to zero(or for pointers,


NULL) by default.
• Static keyword has different effect on local and global variables.
• For local static variables, compiler allocates a permanent storage
in heap like global variable, so that they can retain their values between
function calls. Unlike global variables, local static variables are visible
only within their function of declaration.
• For global static variables, compiler creates a global variable
which is only visible within the file of declaration.
• In C++, when static is used on a class data member, it causes
only one copy of that member to be shared by all objects of its class.

C++ Static Variable Example Program


In the following program, we declared a local and a static variable inside
getVal function. Output of this programs shows that static variable retains it's
value between successive function call whereas local variable vanishes when
control exits function block.
#include <iostream>
using namespace std;

int printVal(){
// Declaring a loval static variable
static int sVariable = 0;
// Declaring a local variable
int lVariable = 0;

// Incrementing both variables


sVariable++;
lVariable++;
// Static variable will retail it's value between successive function calls
cout << "StaticVariable = "<<sVariable<<" LocalVariable = "<<lVariable;
cout << endl;
}

int main(){
printVal();
printVal();
printVal();
printVal();

return 0;
}
Output
StaticVariable = 1 LocalVariable = 1
StaticVariable = 2 LocalVariable = 1
StaticVariable = 3 LocalVariable = 1
StaticVariable = 4 LocalVariable = 1

register Storage Class


Declaring a variable with register keyword is a hint to the compiler to store this
variable in a register of the computer's CPU instead of storing it in memory.
Storing any variable in CPU register, will reduce the time of performing any
operation on register variable. We can declare register variables using register
keyword.
For Example :
register int count;

• Declaring a variable as register is a request to the compiler to


store this variable in CPU register, compiler may or may not store this
variable in CPU register(there is no guarantee).
• Register variable was deprecated in C++11.
• The scope of register variables are same as automatic variables,
visible only within their function.
• Frequently accessed variables like loop counters are good
candidates for register variable.
• We can only declare local variables and formal parameters of a
function as register variables, global register variables are not allowed.
C++ Register Variable Example Program
#include <iostream>
using namespace std;

int main(){
// Declaration of a variables using register keyword
register int counter;
int sum=0;
// Variable counter is used frequently within for loop
for(counter = 1; counter <= 500; counter++){
sum+= counter;
}
cout << "Sum = " << sum;

return 0;
}
Output
Sum = 125250

extern Storage Class


External variables in C++ are variables which can be used across multiple
files. We you can declare an external variable by preceding a variable name
with extern specifier. The extern specifier only tells the compiler about the
name and data type of variable without allocating any storage for it. However,
if you initialize that variable, then it also allocates storage for the extern
variable. The extern modifier is most commonly used when there are two or
more files sharing the same global variables or functions.
• Variables declared extern are initialized to zero by default.
• The scope of the extern variable is global.
• The value of the external variable exists till program termination.
C++ Function Overloading
Function overloading in C++ allows us to write multiple functions having same
name, so long as they have different parameters; either because their number
of parameters are different or because any of their parameters are of a
different data type. You can not overload a function declarations that differ
only by return type.
For Example :
int getSum(int a, int b) {
return a+b;
}

This is a simple function which takes two integer arguments and returns the
sum of two integers. We can use this function to add two integers only. To add
two floating point numbers we can overload getSum function ad follows:

float getSum(float a, float b) {


return a+b;
}

Now, both above functions have same name "getSum" but their parameters
are of a different data type. We can further overload getSum function to add
three integers as follows :

int getSum(int a, int b, int c) {


return a+b+c;
}

All of the three overloaded functions are different from each other either in
their number of parameters or data types of parameters. We now have three
version of getSum function:
• int getSum(int a, int b); // To add two integers.
• float getSum(float a, float b); // To add two floating point numbers.
• int getSum(int a, int b, int c); // To add three integers.

Calling Overloaded function in C++


We can call an overloaded function like calling any other function in C++.
Which version of getSum function gets called by compiler depends on the
arguments passed when the function is called.If we call getSum with two
integer arguments, C++ compiler will know that we want to call getSum(int,
int). If we call getSum function with two floating point numbers, C++ compiler
will know we want to call getSum(float, float).

C++ Function Overloading Example Program


#include <iostream>
using namespace std;

int getSum(int a, int b) {


cout << "\nInside getSum " << a << " " << b;
return a+b;
}

float getSum(float a, float b) {


cout << "\nInside getSum " << a << " " << b;
return a+b;
}

int getSum(int a, int b, int c) {


cout << "\nInside getSum " << a << " " << b << " " << c;
return a+b+c;
}

int main(){
// calling getSum function with different arguments
getSum(3,5);
getSum((float)3.2, (float)5.7);
getSum(4, 7, 9);

return 0;
}

Output
Inside getSum 3 5
Inside getSum 3.2 5.7
Inside getSum 4 7 9
C++ Arrays
Array in C++ is a collection of fixed size data belongings to the same data
type. An array is a data structure provided in C++ which can store a number of
variables of same data type in sequence. These similar elements could be of
type int, float, double, char etc. All array elements are stored in the contiguous
memory locations.
For Example :
int score[100]; /* Integer array of size 100 */
char name[10]; /* character array of size 10 */

Suppose, you want to store marks of 100 students. You can store marks of all
students by creating 100 variable of int data type individually like
studentMarks1, studentMarks2, studentMarks3 .... studentMarks100. This is
very tedious, time consuming and difficult to maintain method of storing 100
marks.

C++ programming language provides support for array data structure, which
solves the problem of storing N similar data. We can declare an integer array
of length 100 to store marks of 100 students.

int studentMarks[100];

In the above array declaration, we declared an array of name "studentMarks"


which can store maximum of 100 integer data in contiguous memory
locations. We can access the individual elements of an array using their index.

• studentMarks[0] refers to the first element of array.


• studentMarks[1] refers to the second element of array.
• studentMarks[99] refers to the last element of array which is 100th
element.
Suppose, we have an integer array of size 7 whose name is score. The base
address or starting address of array score is 1000(base address is same as
address of first element score[0]) and the size of int be 2 bytes. Then, the
address of second element(score[1]) will be 1002, address of third
element(score[2]) will be 1004 and so on.
Points to Remember about Arrays in C++

• An array is a collection of variables of same data types.


• The size of array must be a constant integral value.
• Array is a random access data structure. you can access any
element of array in just one statement.
• All elements of array are stored in the contiguous memory
locations.
• * Individual elements in an array can be accessed by the name of
the array and an integer enclosed in square bracket called
subscript/index variable like employeeSalary[5].
• The first element in an array is at index 0, whereas the last
element is at index (size_of_array - 1)

Advantage of Arrays in C++


• Random Access : We can access any elements of array in O(1)
time complexity.
• Less amount of code : Using array we can aggregate N
variables of same data type in a single data structure. Otherwise we
have to declare N individual variables.
• Easy access of elements : We can access any element of array
using array name and index. We can access all elements serially by
iterating from index 0 to size-1 using a loop.
• Easy to implement algorithms : Certain algorithms can be easily
implemented using array like searching and sorting, finding maximum
and minimum elements.

How to declare an array in C++


Like any other variable in C++, we must declare an array before using it.
Below is the syntax of declaring an 1D array.
data_type array_name[array_size];
Advantage of Arrays in C++
• array_name : It is a valid C++ identifier.
• array_size : It is the maximum number of elements which can be
stored in array. It must be an integer constant greater than zero.
• data_type : It represents the data type of each elements to be
stored in array.
Examples of Array Declaration in C++
An Array of 10 Integers
int age[10];
An Array of 50 Characters.
char address[50];
Two Dimensional Array of Integers.
int maze[20][20];

How to initialize an array in C++ programming


Arrays in C++ programming language is not initialized automatically at the
time of declaration. By default, array elements contain garbage value. Like
any other variable in C++, we can initialize arrays at the time of declaration.
Array Initialization by Specifying Array Size
int marks[7] = {5,2,9,1,1,4,7};

Array Initialization Without Specifying Array Size


int marks[] = {5,2,9,1,1,4,7};

In above declaration, compiler counts the number Of elements inside curly


braces{} and determines the size of array score. Then, compiler will create an
array of size 7 and initialize it with value provided between curly braces{} as
discussed above.
C++ Accessing Array Elements
In C++, We can access array element using array name and subscript/index
written inside pair of square brackets [].
For Example :
Suppose we have an integer array of length 5 whose name is age.

int age[5] = {8,5,2,3,7};

Now we can access elements of array marks using subscript followed by array
name.
• age[0] = First element of array age = 8
• age[1] = Second element of array age = 5
• age[2] = Third element of array age = 2
• age[3] = Fourth element of array age = 3
• age[4] = Last element of array age = 7
Point To Remember
Remember array indexing starts from 0. Nth element in array is at index N-1.

C++ Accessing Array Elements Sample Program


#include <iostream>
using namespace std;

int main(){
int age[7] = {8,5,2,3,7,6,7};
int i;
// Printing array elements using loop
for(i = 0; i < 7; i++){
// Accessing array elements using i as index
cout << "Element at index " << i <<" is " << age[i];
cout << endl;
}

return 0;
}

Output
Element at index 0 is 8
Element at index 1 is 5
Element at index 2 is 2
Element at index 3 is 3
Element at index 4 is 7
Element at index 5 is 6
Element at index 6 is 7

In above program, we initialed an array named "age" of length seven. Using a


for loop, we are printing every array element from index 0 to 6.
C++ Multidimensional Arrays
C++ programming language supports multi dimensional Arrays.
Multidimensional arrays can be described as "arrays of arrays". For Example,
a two dimensional array:

int matrix[3][4];

can be imagined as a table of 12 elements arranged in 3 rows and 4 columns.


First dimension represents the number of row and second dimension
represent number of vertical columns.
• Multi dimensional arrays are array of arrays.
• Multi dimensional arrays have more than one subscript variables.
• Multi dimensional array is also called as matrix.
2D

Multidimensional Array Declaration


data_type array_name[size1][size2]...[sizeN];
Above statement will declare an array of N dimensions of name array_name,
where each element of array is of type data_type. The maximum number of
elements that can be stored in a multi dimensional array array_name is size1
X size2 X size3...sixeN.
For Example :
Declaration of two dimensional integer array
int maze[8][8];
Declaration of three dimensional character array
char rubix[50][60][30];

Multidimensional Array Initialization


Initialization of Two Dimensional Array
Two dimensional arrays can be initialized by specifying elements for each row
inside curly braces. The following declaration initializes a two dimensional
matrix of 4 rows and 3 columns.

int matrix[4][3] = {
{1, 2, 3}, /* Initialization of first row */
{4, 5, 6}, /* Initialization of second row */
{7, 8, 9}, /* Initialization of third row */
{10, 11, 12}, /* Initialization of fourth row */
};

Similarly, we can initialize any multi dimensional array.


A two dimensional matrix can be initialized without using any internal curly
braces as follows:

int matrix[4][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

In above declaration, compiler will assign first four values(1, 2, 3 and 4) to first
row of matrix and within a row it will populate elements from left to right. Then
next four elements to second row and so on.
Initialization of Three Dimensional Array
Similarly, we can initialize any multi dimensional array.
Similar to two dimensional array, we can also initialize 3 dimensional array as
follows :

int rubix[2][3][2] = {4, 6, 1, 0, 6, 12, 3, 10, 0, -4, 8, 9};

Two Dimensional Array in C++


Two dimensional arrays are most common type of multi dimensional array in
C++. A two dimensional array in C++ language is represented in the form 2D
matrix having rows and columns.
• A two dimensional matrix is an array of one dimensional arrays.
• Two dimensional array requires two subscript variables or
indexes.
• One subscript represents the row index while other represent
column index of an element in matrix.
• Elements of a two dimensional array are stored in contiguous
memory location. First all elements of first row are store then all
elements of second row and so on.

Any element in two dimensional matrix is uniquely identified by


array_name[row_Index][column_Index], where row_index and column_index
are the subscripts that uniquely specifies the position of an element in a 2D
matrix.
An element in second row and third column of an two dimensional matrix
whose name is board is accessed by board[1][2]. Like single dimensional
array, indexing starts from 0 instead of 1.
We can declare a two dimensional matrix of R rows and C columns as follows:

data_type array_name[R][C];

For Example :
A two dimensional integer matrix of 3 rows and 3 columns can be declared as

int score[3][3];

C++ Two Dimensional Array Example program


#include <iostream>
using namespace std;

int main(){
// Two dimentional array declaration
int matrix[20][20];
int rowCounter, colCounter, rows, cols, sum=0;

cout << "Enter size of a matrix\n";


cin >> rows >> cols;
// Populating elements inside matrix
cout << "Enter elements of a matrix\n";
for(rowCounter = 0; rowCounter < rows; rowCounter++){
for(colCounter = 0; colCounter < cols; colCounter++){
cin >> matrix[rowCounter][colCounter];
}
}
// Accessing all elements of matrix to calculate their sum
for(rowCounter = 0; rowCounter < rows; rowCounter++){
for(colCounter = 0; colCounter < cols; colCounter++){
sum += matrix[rowCounter][colCounter];
}
}

cout << "Sum of all elements = " << sum;

return 0;
}

Output
Enter size of a matrix
3 3
Enter elements of a matrix
1 2 3
3 4 5
6 7 8
Sum of all elements = 39

In above program, we first take number of rows and columns as input from
user. Then using two for loops we take matrix elements input from user and
store it in 2D array named matrix. To find the sum of each element of matrix
we traverse the matrix row wise using two for loop.
C++ Passing Array to a Function
In C++ programming, an array can be passed to a function as an argument.
We can pass an array of any dimension to a function as argument.
• Passing an array to a function uses pass by reference, which
means any change in array data inside function's body will reflect
globally.
• When an array is passed as an argument to a function, only the
name of an array is passed. Name of the array represent the address of
the first element of array.
For Example :
• int arrayName[10];

• getSum(arrayName) is equivalent to getSum(&arrayName[0]);

Passing Single Element of an Array to Function


We can pass one element of an array to a function like passing any other
basic data type variable.
C program to pass single element of an array to function
#include <iostream>
using namespace std;

int getSquare(int num){


return num*num;
}

int main(){
int array[5]={1, 2, 3, 4, 5};
int counter;
for(counter = 0; counter < 5; counter++){
// Passing individual array elements to function
cout << "Square of " << array[counter] << " is " << getSquare(array[counter]);
cout << endl;
}

return 0;
}

Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

Passing One-dimensional Array to a Function


We can pass a one dimensional array to a function by passing the base
address(address of first element of an array) of the array. We can either pass
the name of the array (which is equivalent to base address) or pass the
address of first element of array like &array[0]. Similarly, we can pass multi
dimensional array also as formal parameters.
Different ways of declaring function which takes an array as parameter
• Function argument as a pointer
• int testFunction(int *array){
• /* Function body */

• }

• By specifying size of an array in function parameters


• int testFunction(int array[10]){

• /* Function body */

• }

the formal argument int array[10] in function declaration converts to int*


array. This pointer points to the base address of array.
• By passing unbounded array in function parameters.
• int testFunction(int array[]){
• /* Function body */

• }

C++ Program to Pass One Dimensional Array as Parameter to


a Function
#include <iostream>
using namespace std;

// This function takes integer pointer as argument


void printArrayOne(int *array, int size){
int i;
for(i=0; i<size; i++){
cout << array[i] << " ";
}
cout << endl;
}

// This function takes sized array as argument


void printArrayTwo(int array[5], int size){
int i;
for(i=0; i<size; i++){
cout << array[i] << " ";
}
cout << endl;
}

// This function takes unbounded array as argument


void printArrayThree(int array[], int size){
int i;
for(i=0; i<size; i++){
cout << array[i] << " ";
}
cout << endl;
}

int main(){
int score[5]={1, 2, 3, 4, 5};
// Passing name of array
printArrayOne(score, 5);
printArrayTwo(score, 5);
// passing address of first array element
printArrayThree(&score[0], 5);
return 0;
}

Output
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Passing Multidimensional Array to a Function


Multidimensional array with dimension 2 or more can be passed in similar way
as one dimensional array.
#include <iostream>
using namespace std;

// This function takes sized array as argument


void printArray(int array[3][3], int rows, int cols){
int i, j;
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
cout << array[i][j] << " ";
}
cout << endl;
}
}

int main(){
int matrix[3][3]={{1, 2, 3},{4, 5, 6},{7, 8, 9}};
// Passing name of array
printArray(matrix, 3, 3);

return 0;
}

Output
1 2 3
4 5 6
7 8 9
C++ Returning Array from a Function
In C++, we can return a pointer to the base address(address of first element
of array) of array from a function like any basic data type. However, C++
programming language does not allow to return whole array from a function.

We should not return base pointer of a local array declared inside a function
because as soon as control returns from a function all local variables gets
destroyed. If we want to return a local array then we should declare it as a
static variable so that it retains it's value after function call.
Declaration of a Function Returning Integer Array
int* getScoreList();

Above function returns the base address of an integer array.

C++ Program for Returning Array from a Function


#include <iostream>
using namespace std;

// This function returns an array of N even numbers


int* getEvenNumbers(int N){
// Declaration of a static local integer array
static int evenNumberArray[100];
int i, even = 2;

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


evenNumberArray[i] = even;
even += 2;
}
// Returning base address of evenNumberArray array
return evenNumberArray;
}

int main(){
int *array, counter;
array = getEvenNumbers(10);
cout << "Even Numbers\n";
for(counter=0; counter<10; counter++){
cout << array[counter] << " ";
}

return 0;
}
Output
2 4 6 8 10 12 14 16 18 20

Similarly, you can return multi dimentional arrays from a function.


C++ Strings
In C++, a String is a sequence of characters. C++ supports two types of String
representations:
• C Strings (terminated by a null character('\0'))
• Objects of string class (C++ Library provides a string class)

C Strings
String in C programming language is a one-dimensional array of characters
which is terminated by a null character('\0'). A character array which is not null
terminated is not a valid C string. In a C string, each character occupies one
byte of memory including null character.

Null character marks the end of the string, it is the only way for the compiler to
know where this string is ending.
Examples of C Strings
• "A"
• "TechCrashCourse"
• "Tech Crash Course"
• ""
Memory representation of C string

Declaration of C Strings
Syntax of String Declaration
char string_name[SIZE_OF_STRING];

In the above declaration, string_name is a valid C identifier which can be used


later as a reference to this string. Remember, name of an array also specifies
the base address of an array.SIZE_OF_STRING is an integer value specifying
the maximum number of characters which can be stored in this string
including terminating null character. We must specify size of string while
declaration if we are not initializing it.
For Example:
char address[100];
char welcomeMessage[200];

Initialization of C Strings
Initialization of string using a character array
char name[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};

or
char name[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};

In the above declaration individual characters are written inside single


quotes('') separated by comma to form a list of characters which is wrapped in
a pair or curly braces. This list must include a null character as last character
of the list.

If we don't specify the size of String then length is calculated automatically by


the compiler.
Initialization of string using string literal
char name[16] = "TechCrashCourse";

or
char name[] = "TechCrashCourse";

In above declaration a string with identifier "name" is declared and initialized


to "TechCrashCourse". In this type of initialization, we don’t need to put
terminating null character at the end of string constant. C compiler will
automatically inserts a null character('\0'), after the last character of the string
literal.

C++ Program for String Initialization


#include <iostream>
using namespace std;

int main(){
char nameOne[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
char nameTwo[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
char nameThree[16] = "TechCrashCourse";
char nameFour[] = "TechCrashCourse";
char *nameFive = "TechCrashCourse";
char nameSix[16];

cout << nameOne << endl;


cout << nameTwo<< endl;
cout << nameThree << endl;
cout << nameFour << endl;
cout << nameFive << endl;

// Taking string input from user


cout << "Enter a string \n";
cin >> nameSix;
cout << "You Entered : " << nameSix;

return 0;
}
Output
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
Enter a string
C++
You Entered : C++
String Handling Standard Library Functions in C++
cstring header file contains a wide range of functions to manipulate null-
terminated C strings. Below are some commonly used string handling
functions of cstring header file.

Function Description

strlen() It returns the length of a string.

strcat() It appends one string at the end of another string.

strcpy() It copies characters from one string into another string.

strcmp() It compares two strings character by character.

strtok() It breaks a string into smaller tokens.

strchr() It searches for the first occurrence of a character in the string.

strstr() It searches for the first occurrence of a string in another string.

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

int main(){
char input[50];
char copyString[60];

cout << "Enter a string\n";


cin >> input;

// Printing length of string using strlen()


cout << "Length of string : " << strlen(input) << endl;

// copying input into copyString


strcpy(copyString, input);
cout << "Copied String : " << copyString << endl;

// comparing input and copyString string


if(strcmp(copyString, input)){
cout << "Both Strings are Not Equal\n";
} else {
cout << "Both Strings are Equal\n";
}

return 0;
}
Output
Enter a string: TechCrashCourse
Length of TechCrashCourse : 15
Copied String : TechCrashCourse
Both Strings are Equal

Points To Remember
• Null character marks the end of the C strings.
• C Strings are single dimensional array of characters ending with a
null character(‘\0’).
• The ASCII value of null character('\0') is 0.
• Each character of string is stored in consecutive memory location
and occupy 1 byte of memory.
• Strings constants are enclosed by double quotes and character
are enclosed by single quotes.
• If the size of a C string is N, it means this string contains N-1
characters from index 0 to N-2 and last character at index N-1 is a null
character.

String Class in C++


C++ provides a String class, you can also create a objects of string class for
holding strings. String class supports all the operations mentioned above,
additionally much more functionality.At this point may not understand about
classes and object, until you understand the Object Oriented Programming
Concepts(which is discussed later). Here is a sample C++ program using
string class.
#include <iostream>
#include <cstring>

using namespace std;

int main () {
// Declaring objects of string class
string strOne = "C++";
string strTwo = "Programming";
string strThree;
int length;

// Reading string from user


cout << "Enter a string\n";
getline(cin, strThree);

// Printing String
cout << strThree<< endl;;
// concatenating strOne and strTwo
strOne = strOne + strTwo;
cout << "Combined String : " << strOne << endl;

// Printing length of string


length = strOne.size();
cout << "Length of Combined String : " << length << endl;

return 0;
}
Output
Enter a string
TechCrashCourse
TechCrashCourse
Combined String : C++Programming
Length of Combined String : 14
C++ Pointers
A pointer in C++ allows us to directly access data stored at a particular
memory location. Pointers are one of the most powerful feature of C++
programming language. Once you master the use of pointers, you will use
them everywhere to make the code more efficient and faster. In C++, some
operations can be performed more efficiently using pointers like dynamic data
structures like linked list and trees,dynamic memory allocation, pass
arguments to a function as Call by Reference, access array elements etc.

What is a Pointer
A pointer in C++ is a variable which is used to store the address of another
variable.

A variable in C++ is the name given to a memory location, where a program


can store data. A program can manipulate the value stored using variable's
identifier. When we declare a variable in C++, compiler allocates sufficient
space in memory to store the value assigned to this variable. We can access
the value of this variable either by variable identifier or by directly accessing
the memory location using pointers.
Every memory location is given a unique address, once you know the address
of a memory location(variable), you'll then be able to go to that address and
manipulate the data stored in it. To get the address of any variable, we can
use &(Address of) operator and to retrieve the value stored at a memory
location we can use *(Value of Operator).
• If count is a variable then, &count gives the memory address of
count variable.
• If ptr is a pointer variable storing the address of a memory location
then *ptr gives the data stores at memory location pointed by ptr.

Advantages of Pointers

• We can dynamically allocate or deallocate space in memory at


run time by using pointers.
• We can pass arrays to a function as call by Reference.
• The use of pointers results into faster execution of program.
• Using pointers we can return multiple values from a function.
• Pointers in C++ are used to efficiently implement dynamic Data
Structures like Queues, Stacks, Linked Lists, Tress etc.
• Pointers are used to efficiently access array elements, as array
elements are stored in adjacent memory locations. If we have a pointer
pointing to a particular element of array, then we can get the address of
next element by simply incrementing the pointer.

Reference operator (&) and Deference operator (*)


The & is a unary operator in C++ which returns the memory address of a
variable. This is also known as address of operator.

The * is a unary operator which returns the value stored at a memory location
which is pointed by a pointer variable. It is known as "value of" operator. It is
also used for declaring pointer variable.
For Example :
int A = 100;
int *ptr = &A;
cout << *ptr;

In the first statement, we first declare an integer variable and initialize it with
value 100. In second statement, we are declaring a pointer to a variable of
type int and initializing it with address of A. The third statement prints the
value stored at the memory location pointed by ptr, which is 100.

Pointer Declaration
A pointer is a derived data type that is created from fundamental data types.
We use (*) for defining pointer variables. Here is the syntax of declaring a
pointer variable.

<data_type> *<identifier>;

For Example :
int *ptr;

Above pointer declaration specifies that, ptr is a pointer variable that will store
the memory address of an integer. We can also initialize a pointer as follows:

int age = 10;


int *ptr = &age;

Integer variable 'age' is the name to a memory location where value 10 is


stored. Let the memory address of age is "0x52436721". Then pointer variable
ptr will contain address of age which is "0x52436721"
#include <iostream>
using namespace std;

int main () {
int age = 10;
int *ptr = &age;

cout << "Value of count variable is " << age << endl;
cout << "Address of count variable: " << ptr << endl;
cout << "Value retrieved through pointer : " << *ptr;

return 0;
}

Output
Value of count variable is 10
Address of count variable: 0x22fe34
Value retrieved through pointer : 10

Size Of Pointer Variable


The size of a pointer variable depends on system architecture. A memory
address is considered as integer value. Size of a pointer is fixed, it doesn't
depend on the data type it is pointing to. We can use size of operator to get
the size of a pointer.
C++ Program to print the size of pointer
// C++ Program to print the size of pointer variables
#include <iostream>
using namespace std;

int main() {
int count = 10;
float sum = 20.5;
int *null_ptr = NULL;
int *int_ptr = &count;
float *float_ptr = &sum;

cout << "Size of NULL Pointer : " << sizeof(null_ptr) << " Bytes\n";
cout << "Size of Integer Variable : " << sizeof(count) << " Bytes\n";
cout << "Size of Integer Pointer : " << sizeof(int_ptr) << " Bytes\n";
cout << "Size of Float Variable : " << sizeof(sum) << " Bytes\n";
cout << "Size of Float Pointer : " << sizeof(float_ptr) << " Bytes\n";

return 0;
}

Output
Size of NULL Pointer : 8
Size of Integer Variable : 4
Size of Integer Pointer : 8
Size of Float Variable : 4
Size of Float Pointer : 8
C++ Pointer Arithmetic
In C++, arithmetic operations on pointer variable is similar to a numeric value.
As we know that, a pointer in C++ is a variable used to store the memory
address which is a numeric value. The arithmetic operations on pointer
variable changes the memory address pointed by pointer. Not all arithmetic
operations are valid for pointer variable, like multiplication and division. Here
is the list of valid pointer arithmetic operations.
• Incrementing a pointer.
• Decrementing a pointer.
• Adding a number to pointer.
• Subtracting a number form a pointer.
• Comparison on two pointers.
• Subtracting two pointers.
And, here is the list of invalid pointer arithmetic operations.
• Addition of two pointers.
• Division of two pointers.
• Multiplication of two pointers.

Adding a numbers to a Pointer


Addition of a number N to a pointer leads the pointer to a new memory
location after skipping (N x size of pointer data type) bytes.

ptr + N = ptr + (N * sizeof(pointer_data_type))

For example, Let ptr be an integer pointer, initially pointing to location 1000.
The size of integer data type is 4 bytes. Then ptr + 5 = 1000 + 4*5 = 1020.
Pointer ptr will now point at memory address 1020.

Subtracting Numbers from Pointers


Subtraction of a number N from a pointers is similar to adding a number
except in subtraction the new location will be before current location by (N x
size of pointer data type).
ptr - N = ptr - (N * sizeof(pointer_data_ype))

For example, Let ptr be a double pointer, initially pointing to location 1000.
The size of double data type is 6 bytes. Then ptr - 3 = 1000 - 6*3 = 982.
Pointer ptr will now point at memory address 982.

Subtraction of Two Pointers


The difference between two pointer returns indicates “How apart the two
Pointers are. It gives the total number of elements between two pointers. For
example, Let size of integer is 4 bytes. If an integer pointer 'ptr1' points at
memory location 10000 and integer pointer 'ptr' points at memory location
10008, the result of ptr2 - ptr1 is 2.

Incrementing a Pointer in C++


We use increment operator(++) to increment a pointer. The effect of
incrementing an integer and an integer pointer is different. Let ptr be an
integer pointer which points to the memory location 5000 and size of an
integer variable is 4 bytes. Now, when we increment pointer ptr

ptr++;

it will point to memory location 5004 because it will jump to the next integer
location which is 4 bytes next to the current location. Incrementing a pointer is
not same as incrementing an integer value. On incrementing, a pointer will
point to the memory location after skipping N bytes, where N is the size of the
data type(in this case it is 4).

ptr++ is equivalent to ptr + (sizeof(pointer_data_type)).


"Incrementing a pointer increases its value by the number of bytes of its data
type".
• An integer(4 bytes) pointer on increment jumps 4 bytes.
• A character(1 bytes) pointer on increment jumps 1 bytes.
Decrementing a Pointer in C++
We use decrement operator(--) to decrement a pointer. Decrementing a
pointer will decrease its value by the number of bytes of its data type. Let ptr
is originally pointing to memory location 5000. Hence, after

ptr--;

ptr will point to 4996.


ptr--; is equivalent to ptr - (sizeof(pointer_data_type)).
C++ Pointers and Arrays
Relationship between Array and Pointers
• The name of the array is a const pointer to the beginning of the
array. It contains the address of first array element.

int score[100];

the score is equal to &score[0].


• A pointer that points to the beginning of array can access any
element of array using pointer arithmetic.

• int score[100];
• int *ptr = score;

Now we can access fourth element of array as *(ptr + 3) or ptr[3].


Internally, any array element access using index is implemented using
pointer.
• A pointers variable can also store address of individual array
elements like address of single variables.

• int score[100];

• int *ptr = &score[4];


• On incrementing a pointer who is pointing to an array element, it
will start pointing to next array element.

• int score[100];

• int *ptr = score;

Currently, ptr is pointing to first element of array but when we increment


it

ptr = ptr + 1;

It will start pointing to 1st element of array. Incrementing a pointer


increases its value by the number of bytes of its data type.
1. On incrementing, a pointer pointing to an integer(4 bytes)
array jumps 4 bytes.
2. On incrementing, a pointer pointing to a character(1 bytes)
array jumps 1 bytes.

C++ Program to print array elements using array index and


pointers
#include <iostream>
using namespace std;

int main () {
int score[6] = {1, 2, 3, 4, 5, 6};
int i, *ptr;

// printing array elements using array index


for(i = 0; i < 6; i++){
cout << score[i] << " ";
}
cout << endl;

// Initializing pointer
ptr = score;
// printing array elements using pointer
for(i = 0; i < 6; i++){
cout << *(ptr) << " ";
// Incrementing pointer
ptr++;
}
return 0;
}

Output
1 2 3 4 5 6
1 2 3 4 5 6

In above program, we first initialize a pointer with base address of an integer


array. On incrementing this pointer inside for loop, it keeps on pointing to next
array element.
• Pointers and Arrays are interchangeable in many cases but their
one difference. Name of an array is a constant pointer, which always
points to first element of array. We can use array name in pointer
arithmetics as long as we are not changing it's value.
int score[100];
• (score + 1) is a valid expression because here we are not
changing value of score whereas *(score++) is invalid.

You might also like