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

PF Notes - Ii

The document discusses control statements in programming, specifically focusing on sequence, decision, and repetition structures. It details various decision-making constructs in C++ such as if, if-else, nested if, and switch statements, as well as repetition structures including for, while, and do-while loops. Each structure is explained with syntax, flow charts, and examples to illustrate their usage in programming.

Uploaded by

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

PF Notes - Ii

The document discusses control statements in programming, specifically focusing on sequence, decision, and repetition structures. It details various decision-making constructs in C++ such as if, if-else, nested if, and switch statements, as well as repetition structures including for, while, and do-while loops. Each structure is explained with syntax, flow charts, and examples to illustrate their usage in programming.

Uploaded by

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

CONTROL STATEMENTS:

1) SEQUENCE STRUCTURE:
Up-till now, programs that we have covered follow sequence structure.

Sequence Structure: In Sequence Structure, programs are written in a sequence of steps


and there is not any type of branching in the program.

Second comes the decision structure which is discussed below.

2) DECISION STRUCTURE:
Decision Structure: Sometimes we need to execute a block of statements only when a
particular condition is met or not met. This is called decision making, as we are executing a
certain code after making a decision in the program logic.
For decision making in C++, we have different types of decision making structures /
selection structures / control statements (or control structures), which are as follows:
1. if statement
2. if-else statement
3. if-else-if statement
4. nested if statement
5. Switch statement
1) If Statement:
if statement is the most simple decision making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e. if a certain condition is
true then a block of statements is executed otherwise not.

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

if(condition)
{
//Statement(s) to execute if the
// condition is true
}
Here, condition after evaluation will be either true or false. If the value is true then it will
execute the block of statements below it otherwise not. The statement/s inside curly braces ‘{‘
and ‘}’ are called body of if-statement. If we do not provide the curly braces ‘{‘ and ‘}’ after
if(condition) then by default if statement will consider the first immediately below statement to
be inside its block.

Example:
if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.
FlowChart:
How if statement works?

Examples: In CODE FILE.

2) If-Else Statement:
If-Else Statement: The if-statement alone tells us that if a condition is true it will execute
a block of statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false. Here comes the C++ else-statement.
We can use the else-statement with if-statement to execute a block of code when the if-
statement condition is false.

Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart:
How if...else statement works?

Examples: In CODE FILE.

3) If…Else-If Statement:
If…Else-If Statement: if...else statement is used to execute a block of code among two
alternatives. However, if we need to make a choice between more than two alternatives, we use
if...else if...else statement.

Syntax:
General syntax is:
if(condition_1)
{
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2)
{
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3)
{
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else
{
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}

IMPORTANT POINTS:
1. First if-statement is necessary.
2. The use of else statement at last is optional (not necessary).
3. As soon as a particular condition is satisfied, its corresponding statements are
executed and the rest of the statements are bypassed/skipped.
4. If none of the conditions is satisfied, then the statements inside “else” gets
executed.
Flow Chart:

Working:
Another representation:

PROGRAMS: In CODE FILE


4) Nested-If Statement:
Nested-If Statement: Sometimes, we need to use an if statement inside another if statement.
This is known as nested if statement.

Think of it as multiple layers of if statements. There is a first, outer if statement, and


inside it is another, inner if statement. Its syntax is:
// outer if statement
if (condition1)
{
// statements

// inner if statement
if (condition2)
{
// statements
}
}

Notes:
 We can add else and else if statements to the inner if statement as required.
 The inner if statement can also be inserted inside the outer else or else if statements (if they
exist).
 We can nest multiple layers of if statements.
 As you can see, nested if...else makes your logic complicated. If possible, you should always try
to avoid nested if...else.

PROGRAMS: In CODE FILE.


5) Switch Statement:
Normally, if we have to choose one case among many choices, if…else-if statement is
used. The problem with if…else-if statement is that it becomes complex when we have many
conditions. The switch case is a clean and efficient method of handling such scenarios.
Switch statement: A switch statement allows a variable to be tested for equality against
a list of values/choices. Each value is called a case, and the variable being switched on is checked
for each case. The switch statement allows us to execute a block of code among many
alternatives/choices.

Syntax:
Let's have a look at its syntax.
switch (expression or constant)
{
case value1:
statement(s);
break; //optional
case value2:
statement(s);
break; //optional
case value3:
statement(s);
break; //optional
.
.
.
/* you can give any number of cases */
default: //optional
statement(s);
}
NOTES:
1. The expression provided in the switch should result in a constant value otherwise it would
not be valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)

// Variable expression are allowed provided


// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c+10)
2. Duplicate case values are not allowed.
3. The default statement is optional. A switch statement can have an optional default case,
which must appear at the end of the switch. The default case can be used for performing a
task when none of the cases is true. No break is needed in the default case. Even if the switch
case statement do not have a default statement, it would run without any problem.
4. The break statement is used inside the switch to terminate a statement sequence. When a
break statement is reached, the switch terminates, and the flow of control jumps to the next
line after the switch statement.
5. The break statement is optional. Not every case needs a break statement. If omitted,
execution will continue on into the next case. The flow of control will fall through to
subsequent cases until a break is reached.
6. Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes
program more complex and less readable.
7. You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
8. The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
Flow Chart:
PROGRAMS: In CODE FILE.
3) REPETITION STRUCTURES:
Repetition Structure: Repetition Structure allows us to repeat one or more
statement/s. In Programming Languages, Repetition Structures are called as Loops.
Loops: Loops in programming come into use when we need to repeatedly execute a
block of statements. The block of statements executes repeatedly until a particular
condition is satisfied. We can achieve much more efficiency and sophistication in our
programs by making effective use of loops.
TYPES OF LOOPS IN C++:
On the Basis Of Test Condition: There are mainly two types of loops:

1. Entry Controlled loops: In this type of loops the test condition is tested before entering
the loop body. For Loop and While Loop are entry controlled loops. They are also called
as pre-test Loops.

2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the
end of loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. do – while loop is exit controlled loop. It is also
called as post-test Loop.
In Total: There are 3 types of loops in C++.
 for loop
 while loop
 do...while loop

(i) FOR LOOP:


For Loop: A for loop is a repetition control structure which allows us to execute a block
of code in a specific number of times. The loop enables us to perform ’n’ number of steps
together in one line.
Syntax:
Below is the syntax of for Loop.
for (initialization; condition ; increment/decrement)
{
//statement(s);
}

PARTS OF A FOR LOOP:


The for loop has 3 parts.

1. Initialization: Initialization (Initialization Expression) happens first when we enter for


loop for the first time and it happens only once, which means that the initialization part
of for loop only executes once. In this expression we have to initialize the loop control
variable to some value. For example: int i=1;
2. Condition: the condition (test expression), second step after initialization is evaluated
on each loop iteration. If the condition is true, the body of for loop is executed and we
proceed to increment/decrement (update expression). If it is false, the body of the loop
does not execute and flow of control jumps to the next statement just after the for loop.
For example: i <= 10;
Iteration: One complete round of a loop is called iteration.
3. Increment/decrement: After completion of Initialization and Condition steps the
increment/decrement expression updates the loop control variable. For example:
i++; OR i--;
4. After first iteration, the condition expression is evaluated and steps 2 and 3 are repeated
again as long as the condition expression is true.

Control flow of for loop

Another Control Flow Diagram:


Flow Chart:

Example-1:
Example-2:
C++ Infinite for loop:

If the condition expression in a for loop is always true, it runs forever (until memory/RAM is
full), such a loop is called Infinite Loop. For example,
Example-1:

// infinite for loop


for(int i = 1 ; i > 0 ; i++)
{
// block of code
}

In the above program, the condition is always true which will then run the code for infinite
times.
Example-2:

// infinite for loop


for(; 1 ; )
{
// block of code
}

Example-3:

// infinite for loop


for(int i = 1 ; i > 0 ; )
{
// block of code
}
There are many other examples of infinite loop.

IMPORTANT POINTS:
1. We can omit either all or any of initialization, condition / test expression and increment
/ decrement expression from a for loop.

Example-1 (Omitting Initialization Expression Only):

int i = 1;

for( ; i > 0 ; i++)


{
// block of code
}

Note: Here the control variable should be initialized before test condition to execute in the for
loop.

Example-2 (Omitting Increment/Decrement Expression Only):

for(int i = 1 ; i > 0 ; )
{
// block of code
i++;
}

Note: Here Increment/Decrement Expression should be the last statement in the for loop body.

Example-3 (Omitting Both initialization and increment/decrement statement):

int i = 1;

for( ; i > 0 ; )
{
// block of code
i++;
}

Note: Here the control variable should be initialized before test condition to execute in the for
loop and the Increment/Decrement Expression should be the last statement in the for loop
body.

Example-4 (Omitting all expressions):

int i = 1;

for( ; ; )
{
If (i ==0)
{
break;
}
// block of code
i++;
}

Note: Here the control variable should be initialized, the test condition must be in the body
of loop and the Increment/Decrement Expression should be the last statement in the for loop
body.
2. A for loop is usually used when the number of iterations is already known.

PROGRAMS: In CODE FILE.


(ii) WHILE LOOP:
During the study of ‘for’ loop in C or C++, we have seen that the number of iterations is
known beforehand, i.e. the number of times the loop body is needed to be executed is known to
us.

While Loop: The while loop in C/C++ is used in situations where we do not know the exact
number of iterations of loop beforehand. The loop execution is terminated on the basis of the
test condition.

Syntax:
Below is the syntax of while Loop.
initialization_expression

while (condition/s)
{
//statement(s);
update_expression;
}
How does a While loop execute?
1. Control falls into the while loop.
2. The flow jumps to Condition
3. Condition is tested.
a. If Condition yields true, the flow goes into the Body.
b. If Condition yields false, the flow goes outside the loop
4. The statements inside the body of the loop get executed.
5. Updation takes place.
6. Control flows back to Step 2.
Control Flow Diagram:
Parts Of a While Loop:
1. Test Expression: In this expression we have to test the condition. If the condition evaluates
to true then we will execute the body of the loop and go to update expression. Otherwise,
we will exit from the while loop.
Example:
i <= 10
2. Update Expression: After executing the loop body, this expression increments /
decrements the loop variable by some value.
Example:
i++;
See this link for a gif representation: https://www.sitesbay.com/cprogramming/c-while-loop
Flow Chart:
PROGRAMS: In CODE FILE.
(iii) Do-While LOOP:
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
Do-While Loop: A do...while loop is similar to a while loop, except that a do...while loop
is guaranteed to execute at least one time.
If the number of iterations is not fixed and we want to execute the loop statements at
least one time irrespective of the condition, do-while loop is useful in such cases.
Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);

Note: Notice the semi-colon (“;”) in the end of loop.


Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.

How does a do-While loop execute?

1. Control falls into the do-while loop.


2. The statements inside the body of the loop get executed.
3. Updation takes place.
4. The flow jumps to Condition
5. Condition is tested.
a. If Condition yields true, goto Step 6.
b. If Condition yields false, the flow goes outside the loop
6. Flow goes back to Step 2.
Control Flow Diagram:

Parts of a do-while Loop:


The various parts of the do-while loop are:
1. Test Expression: In this expression we have to test the condition. If the condition evaluates
to true then we will execute the body of the loop and go to update expression.
Otherwise, we will exit from the while loop.
Example:
i <= 10
2. Update Expression: After executing the loop body, this expression increments/decrements
the loop variable by some value.
Example:
i++;
Flow Chart:
Example-1:

Example-2:
PROGRAMS: In CODE FILE.

Infinite while and do-while loops:

If the condition of a loop is always true, the loop runs for infinite times (until the
memory is full). For example,

// infinite while loop


while(true) {
// body of the loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop

int count = 1;

do {
// body of loop
}
while(count == 1);

In the above programs, the condition is always true. Hence, the loop body will run for
infinite times.
IMPORTANT POINTS:
1) If condition contains only a positive or a negative number, it will execute infinitely, but if
we use 0 or false, it will never execute.
See the example below:
This loop will never execute.
#include <iostream>
using namespace std;

int main ()
{
for (int i = 0 ; 0 ; i++)
{
cout << i << endl;
}

return 0;
}
2) If we use assignment statement in an if/else-if statement, the statement will always
execute because, after the execution of an assignment statement, a true value is returned.
#include <iostream>
using namespace std;

int main ()
{
int n = 10;

if (n = 5)
{
cout << "Number is 5.\n";
}
else
{
cout << "Number is not 5.\n";
}

return 0;
}
Output:

Number is 5.
See the output. Although n = 10, but the condition if(n=5) is executed because, this is an
assignment statement and it will always execute, because it returns true.

NESTED LOOPS:
A loop can be used inside another loop in C++. They are also called “loop inside loop”.

Syntax for Nested For loop:


for(initialize; condition; increment)
{
for (initialize; condition; increment)
{
statement(s);
}
statement(s);
}

Syntax for Nested While loop:


while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

Syntax for Nested Do-While loop:


do
{
statement(s);
do
{
statement(s);
}while( condition );
statement(s);
}while( condition );

Note: Any loop can be nested inside any loop.


Flow Chart Of Nested For Loop:
Flow Chart Of Nested While Loop:

Flow Chart Of Nested Do-While Loop:

PROGRAMS: In CODE FILE.


C++ BREAK STATEMENT:
The break statement has the following two usages in C++ −
 When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax of a break statement in C++ is −
break;
Flow Chart:

Working of C++ break Statement

Example 1: break with for loop


// program to print the value of i

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}

return 0;
}

Output

1
2

In the above program, the for loop is used to print the value of i in each iteration. Here, notice
the code:

if (i == 3) {
break;
}

This means, when i is equal to 3, the break statement terminates the loop. Hence, the output
doesn't include values greater than or equal to 3.
Note: The break statement is usually used with decision-making statements.

Example 2: break with while loop


// program to find the sum of positive numbers
// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;

// break condition
if (number < 0) {
break;
}

// add all positive numbers


sum += number;
}

// display the sum


cout << "The sum is " << sum << endl;
return 0;

Output

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.

In the above program, the user enters a number. The while loop is used to print the
total sum of numbers entered by the user. Here, notice the code,

If (number < 0) {
break;
}

This means, when the user enters a negative number, the break statement terminates
the loop and codes outside the loop are executed.
The while loop continues until the user enters a negative number.

break with Nested loop


When break is used with nested loops, break terminates the inner loop. For example,
// using break statement inside
// nested for loop

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}

return 0;
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In the above program, the break statement is executed when i == 2. It terminates the
inner loop, and the control flow of the program moves to the outer loop.
Hence, the value of i = 2 is never displayed in the output.

THE CONTINUE STATEMENT:


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

Syntax of continue statement

continue;
Flow Chart:

C++ Continue Statement Example:


#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
}
}
Output:

1
2
3
4
6
7
8
9
10

Example: Use of continue in For Loop:


#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++)
{
if(i==2)
{
continue;
}
cout << i << " \n";
}
}

Output:

1
3

Example: Use of continue in While loop:


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

return 0;
}
Output:

Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0

Example of continue in do-While loop:


#include <iostream>
using namespace std;
int main()
{
int j=4;
do
{
if (j==7)
{
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j<10);

return 0;
}
Output:

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

Example of continue with nested loops:


C++ Continue Statement continues inner loop only if you use continue statement
inside the inner loop.

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
cout<<i<<" "<<j<<"\n";
}
}
}

Output:

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
ARRAYS:
Array: An array is a collection of elements/items of same data type stored in consecutive
(contiguous) memory locations. We can say that an array is a collection of variables of the same
data-type.
Arrays can store elements of primitive data types such as int, float, char, double etc., as
well as derived data types such as structures and classes etc.
Syntax:
The following is the syntax of declaring arrays:

datatype array_name [ array_size ];


This is called a single-dimension / one-dimensional / 1-D array. The array-size must be
an integer constant greater than zero.

Declaring Arrays: There are various ways of declaring arrays.


1. Array declaration by specifying its size:
Example: 1. int array[10];
2. int size = 10;
int array[size];
Both the above two examples will declare arrays of size = 10. So, the above two
arrays will take (size*data-type) Bytes = (10*4) Bytes = 40 Bytes. So, total-array-size =
40 Bytes.
2. Array Declaration By Initializing Elements:
Example: int array[ ] = {1, 2, 3, 4, 5};
In this case, compiler will automatically find out the size of the array, by (count-
of-elements*data-type) Bytes. In the example, count-of-elements = 5, so, total-array-
size = (5*4) Bytes = 20 Bytes.
3. Array declaration by specifying size and initializing elements:
Example: 1. int array[4] = {1, 2, 3, 4};
2. int size = 5;
int array[size] = {1, 2, 3, 4, 5};
4. Count-of-elements < array-size:
Example: 1. int array[6] = {1, 2, 3, 4};
2. int size = 7;
int array[size] = {1, 2, 3, 4, 5};
In example-1, we gave size = 6, but initialized only four elements, while in
example-2, we gave size = 7, but initialized only five elements. In both the cases, the
compiler will automatically initialize remaining elements to be zero.
A Complete Diagram:
Let’s have a look at the diagram above. We have initialized an array of 5 elements. They
are shown in pink boxes. The blue boxes shown are the indices of the array. The indices of an
array start from 0 (zero).
1st element = 0th index
2nd element = 1st index
3rd element = 2nd index
... … …
N element = (N-1)th index
th
(generally)
The one shown in yellow boxes are the addresses of the elements of the array in RAM
(Memory).
Let’s say that first element (with value = 34) is at address/ Byte # 1000 in RAM. As the
array is of int data-type, this element will take 4 bytes i.e., 1000-1003. The second element (with
value = 21) can be found at address = (1000+4) = 1004th Byte, and so on.
General Diagram,

Note:
1. The size of array is also called length of the array.
2. The lowest address corresponds to the lowest element and the highest address
corresponds the highest element.
3. The element at zero index is the lowest element and the element at n-1th index is the
highest element.

Other ways are:

Why do we need arrays?


Let’ understand it with an example. Suppose that I want to find the average marks of PF
Subject of your class, having 22 students.
I will have to go through the following steps:
1. I will create 22 int variables to save marks of 22 students.
int marks1, marks2, …, marks22;
2. Then I will add these 22 marks variables.
int sum = marks1 + marks2 + … + marks22;
3. Then I will calculate average as.
float avg = sum / 22;

So, for calculating the average marks of PF Subject of 22 students, I will have to create
and work with 22 variables.

Question = What if I want to calculate average of marks of maths subject of all students
th
of 10 class Lahore Board? Let’s say the students are 2 lacs.
Answer = Create 2 lac variables for marks.

Is it easier? Answer = Absolutely not.


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

SOME IMPORTANT CONCEPTS ABOUT ARRAYS:

1. Accessing Array Elements:

In C++, each element in an array is associated with a number. The number is known as
an array index. We can access elements of an array by using those indices.

// syntax to access array elements


array[index];

Example:
Let’s say we have the following array:
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

So, we can access each individual element as shown above. Diagrammatically,


2. A No Index Out of bound Checking:
There is no index out of bounds checking in C++, for example, the following program
compiles fine but may produce unexpected output when run.
Example:
// This C++ program compiles fine
// as index out of bound
// is not checked in C++.

#include <iostream>
using namespace std;

int main()
{
int arr[2];

cout << arr[3] << endl;


cout << arr[-2] << " ";

return 0;
}
Output:

2008101287
4195777
In C++, it is not compiler error to initialize an array with more elements than the specified
size. For example, the below program compiles fine and shows just Warning.
Example:
#include <iostream>
Using namespace std;
int main()
{

// Array declaration by initializing it with more


// elements than specified size.
int arr[2] = { 10, 20, 30, 40, 50 };

return 0;
}
Example 1: Displaying Array Elements
#include <iostream>
using namespace std;

int main() {
int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}

Output

The numbers are: 7 5 6 12 35

Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have
printed numbers[i].

Example 2: Take Inputs from User and Store Them in an Array


#include <iostream>
using namespace std;

int main() {
int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;
}

Output

Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15

Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we
took an input from the user and stored it in numbers[i]. Then, we used another for loop to print
all the array elements.

Example 3: Display Sum and Average of Array Elements Using


for Loop
#include <iostream>
using namespace std;

int main() {

// initialize an array without specifying size


double numbers[6] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;

cout << "The numbers are: ";

// print array elements use of for loop


for (int i = 0 ; i < 6 ; i++)
{
cout << numbers[i] << " ";
// calculate the sum
sum += numbers[i];

// count the no. of array elements


++count;
}
// print the sum
cout << "\nTheir Sum = " << sum << endl;
// find the average
average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}

Output

The numbers are: 7 5 6 12 35 27


Their Sum = 92
Their Average = 15.3333

Using sizeof() operator with arrays:


The sizeof() operator gives the size of the array in Bytes.
Example:
int arr[5] = {10,20,30,40,50}; // valid
here, Size = 5;
Sizeof(arr) = 20 Bytes // size * 4 Bytes = 5 * 4 = 20 Bytes

TYPES OF ARRAYS IN C++:


There are two types of Arrays in C++:

 Single/One Dimensional Array / 1-D Array.


 Multi-Dimensional Arrays.

MULTI-DIMENSIONAL ARRAYS:
C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];
Multidimensional arrays are also known as array of arrays.

1) TWO-DIMENSIONAL ARRAY:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size rows, cols, you would write something as follows –
Syntax:
data-type array-name [ rows ][ cols ];
Where type can be any valid C++ data type and array-name will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns.
A 2-dimensional array x, which contains three rows and three columns can be shown as
below –
int x [3] [3];

Thus, every element in array x is identified by an element name of the form x[ i ][ j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify each
element in x.

Another Example:
Below is a 2-D array named a [rows] [cols], with rows = 3 and cols = 4.

int a [3] [4]; // Declaration statement

INITIALIZING TWO-DIMENSIONAL ARRAY/2-D ARRAY:

We can initialize the array in many ways:

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

Method 2:

This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3] = { {10, 11, 12} ,
{20, 21, 22} };

Accessing Array Elements:


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array.
Example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array.
Another Example:

arr[0][0] – first element


arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element

Example: Two dimensional array in C++


#include <iostream>
using namespace std;

int main(){
int arr[2][3] = { {11, 22, 33},
{44, 55, 66} };
for(int i=0; i<2;i++)
{
for(int j=0; j<3; j++)
{
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66

Example 2: Taking Input for Two Dimensional Array


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] <<
endl;
}
}

return 0;
}

Output

Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6

Here, we have used a nested for loop to take the input of the 2d array. Once all the input has
been taken, we have used another nested for loop to print the array members.

PROGRAMS: In CODE FILE


2) THREE- DIMENSIONAL ARRAY:
The second type of multi–dimensional arrays is three-dimensional array/ 3-D Array.
Below is the syntax of a general 3-D array.

Syntax:
data-type array-name [ n ][ rows ][ cols ];

where,
rows = no. of rows in 3-D array
cols = no. of columns in 3-D array
n = no. of 2-D arrays of size rows x cols.
Example:

Consider the 3-D Array diagram above. The following is the array declaration for the above 3-D
Array:
int arr [3] [3] [3];
here,
rows = 3
cols = 3
n = no. of 2-D Arrays of size 3x3 = 3 (2-DArrays)
Another Diagram:

Initializing 3-D Arrays:


We can initialize the array in many ways:

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

Method 2:

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

int arr[2][3][2] = {
{ {1, -1},
{2, -2},
{3, -3}
},

{ {4, -4},
{5, -5},
{6, -6}
}
};

Example 1: Three Dimensional Array


// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream>
using namespace std;

int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};

// Displaying the values with proper index.


for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
cout << "test[" << i << "][" << j << "][" << k << "] = "
<< test[i][j][k] << endl;
}
}
}

return 0;
}
Output

test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

Visit this link: https://youtu.be/bbkdiUbou74?t=269 (Three-Dimensional Arrays)

NOTES:
1. Total number of elements (n) that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
A two dimensional array:
int arr[2][3];
This array has total 2*3 = 6 elements.

A three dimensional array:


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

2. Multi-dimensional arrays are stored in RAM as 1-D Arrays.


For Example:

The above array will be stored in RAM as the following 1-D Array.
C++ STRINGS:

String is a collection of characters. There are two types of strings commonly used in C++
programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

C-strings:
In C programming, the collection of characters is stored in the form of arrays, this is also
supported in C++ programming. Hence it's called C-strings.

C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).

How to define a C-string?


char str[] = "C++";

In the above code, str is a string and it holds 4 characters.


Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.
Alternative ways of defining a string
char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String to read a word


C++ program to display a string entered by user.

#include <iostream>
using namespace std;

int main()
{
char str[100];

cout << "Enter a string: ";


cin >> str;
cout << "You entered: " << str << endl;

cout << "\nEnter another string: ";


cin >> str;
cout << "You entered: "<<str<<endl;

return 0;
}

Output

Enter a string: C++


You entered: C++

Enter another string: Programming is fun.


You entered: Programming

Notice that, in the second example only "Programming" is displayed instead of


"Programming is fun".
This is because the extraction operator >> works as scanf() in C and considers a space
(" ") as a terminating character.
Example 2: C++ String to read a line of text
C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;

int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);

cout << "You entered: " << str << endl;


return 0;
}

Output

Enter a string: Programming is fun.


You entered: Programming is fun.

To read the text containing blank space, cin.get() function can be used. This function
takes two arguments.
First argument is the name of the string (address of first element of string) and second
argument is the maximum size of the array.

In the above program, str is the name of the string and 100 is the maximum size of the
array.
String Object:
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per
your requirement.

Example 3: C++ string using string data type

#include <iostream>
using namespace std;

int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);

cout << "You entered: " << str << endl;


cout << "Length of string : " << str.length() << endl;
return 0;
}

Output

Enter a string: Programming is fun.


You entered: Programming is fun.

Length of string : 19

In this program, a string str is declared. Then the string is asked from the user.
Instead of using cin>> or cin.get() function, you can get the entered line of text
using getline().
getline() function takes the input stream as the first parameter which is cin and str as
the location of the line to be stored.
Mixing cin >> and cin.get (cin.ignore() function)

SOME USEFUL STRING FUNCTIONS:


The old c-string file has some very important functions that work with char strings i.e.
(char array[size]; ) etc.
These functions all require the cstring header file to be included, as shown here:

#include <cstring>
These are:

The strlen Function:


For instance, the following code segment uses the strlen function to determine the
length of the string stored in the name array:
char name[] = "Thomas Edison";
int length;
length = strlen(name);
strlen() returns the length of the string, which is the number of characters up to, but not
including, the null terminator. As a result, the variable length will have the number 13 stored in
it.
length = strlen("Thomas Edison"); // length = 13

The strcat Function:


The strcat function accepts two pointers to C-strings as its arguments. The function
concatenates, or appends one string to another. The following code shows an example of its use:

const int SIZE = 13;


char string1[SIZE] = "Hello ";
char string2[] = "World!";
cout << string1 << endl;
cout << string2 << endl;
strcat(string1, string2);
cout << string1 << endl;
These statements will cause the following output:
Hello
World!
Hello World!
The strcat function copies the contents of string2 to the end of string1. In this example,
string1 contains the string “Hello ” before the call to strcat. After the call, it contains the string
“Hello World!”. Figure 10-2 shows the contents of both arrays before and after the function call.

Notice the last character in string1 (before the null terminator) is a space. The strcat
function doesn’t insert a space, so it’s the programmer’s responsibility to make sure one is
already there, if needed. It’s also the programmer’s responsibility to make sure the array
holding string1 is large enough to hold string1 plus string2 plus a null terminator.
Here is a program segment that uses the sizeof() operator to test an array’s size before
strcat is called:
if (sizeof(string1) >= (strlen(string1) + strlen(string2) + 1))
strcat(string1, string2);
else
cout << "String1 is not large enough for both strings.\n";

WARNING! If the array holding the first string isn’t large enough to hold both strings,
strcat() will overflow the boundaries of the array.

The strcpy Function:


The strcpy function can be used to copy one string to another. Here is an example of its
use:
const int SIZE = 13;
char name[SIZE];
strcpy(name, "Albert Einstein");
The strcpy function’s two arguments are C-string addresses. The contents of the second
argument are copied to the memory location specified by the first argument, including the null
terminator. (The first argument usually references an array.) In this example, the strcpy function
will copy the string “Albert Einstein” to the name array.
If anything is already stored in the location referenced by the first argument, it is
overwritten, as shown in the following program segment:
const int SIZE = 10;
char string1[SIZE] = "Hello", string2[SIZE] = "World!";
cout << string1 << endl;
cout << string2 << endl;
strcpy(string1, string2);
cout << string1 << endl;
cout << string2 << endl;
Here is the output:
Hello
World!
World!
World!
WARNING! Being true to C++’s nature, strcpy performs no bounds checking. The array
specified by the first argument will be overflowed if it isn’t large enough to hold the string
specified by the second argument.

The strncat and strncpy Functions:


The strncat functions works like strcat, except it takes a third argument specifying the
maximum number of characters from the second string to append to the first. Here is an example
call to strncat:
strncat(string1, string2, 10);

When this statement executes, strncat will append no more than 10 characters from
string2 to string1.

The strncpy function allows you to copy a specified number of characters from a string to
a destination. Calling strncpy is similar to calling strcpy, except you pass a third argument
specifying the maximum number of characters from the second string to copy to the first. Here
is an example call to strncpy:
strncpy(string1, string2, 5);

When this statement executes, strncpy will copy no more than five characters from
string2 to string1. However, if the specified number of characters is less than or equal to the
length of string2, a null terminator is not appended to string1. If the specified number of
characters is greater than the length of string2, then string1 is padded with null terminators, up
to the specified number of characters.

The strstr Function:


The strstr function searches for a string inside of a string. For instance, it could be used
to search for the string “seven” inside the larger string “Four score and seven years ago.” The
function’s first argument is the string to be searched, and the second argument is the string to
look for. If the function finds the second string inside the first, it returns the address of the
occurrence of the second string within the first string. Otherwise it returns nullptr (the address
0).
Here is an example:
char arr[] = "Four score and seven years ago";
char str[] = strstr(arr, "seven"); // search for "seven"
cout << arr << endl;
cout << strPtr << endl;

In this code, strstr will locate the string “seven” inside the string “Four score and seven
years ago.” It will return the address of the first character in “seven” which will be stored in the
pointer variable strPtr. If run as part of a complete program, this segment will display the
following:
Four score and seven years ago
seven years ago

Because C-strings are stored in char arrays, you cannot use the relational operators to
compare two C-strings. To compare C-strings, you should use the library function strcmp.
This function takes two C-strings as arguments and returns an integer that indicates how
the two strings compare to each other. Here is the function:
int strcmp(char string1[], char string2[]);
The function takes two C-strings as parameters (actually, pointers to C-strings) and
returns an integer result. The value of the result is set accordingly:
• The result is zero if the two strings are equal on a character-by-character basis
• The result is negative if string1 comes before string2 in alphabetical order
• The result is positive if string1 comes after string2 in alphabetical order

Here is an example of the use of strcmp to determine if two strings are equal:
if (strcmp(string1, string2) == 0)
cout << "The strings are equal.\n";
else
cout << "The strings are not equal.\n";
The strcmp function is case sensitive when it compares strings. If the user enters “Dog”
and “dog” as two strings, it will report they are not the same.

Using ! with strcmp:


Some programmers prefer to use the logical NOT operator with strcmp when testing
strings for equality. Because 0 is considered logically false, the ! operator converts that value to
true.
The expression !strcmp(string1, string2) returns true when both strings are the same,
and false when they are different. The two following statements perform the same operation:
if (strcmp(firstString, secondString) == 0)
if (!strcmp(firstString, secondString))

You might also like