PF Notes - Ii
PF Notes - Ii
1) SEQUENCE STRUCTURE:
Up-till now, programs that we have covered follow sequence structure.
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;
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?
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:
// 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.
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)
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
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:
In the above program, the condition is always true which will then run the code for infinite
times.
Example-2:
Example-3:
IMPORTANT POINTS:
1. We can omit either all or any of initialization, condition / test expression and increment
/ decrement expression from a for loop.
int i = 1;
Note: Here the control variable should be initialized before test condition to execute in the for
loop.
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.
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.
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.
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);
Example-2:
PROGRAMS: In CODE FILE.
If the condition of a loop is always true, the loop runs for infinite times (until the
memory is full). For example,
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”.
#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.
#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;
}
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.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// 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.
continue;
Flow Chart:
1
2
3
4
6
7
8
9
10
Output:
1
3
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
return 0;
}
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
#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:
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.
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.
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.
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;
#include <iostream>
using namespace std;
int main()
{
int 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()
{
return 0;
}
Example 1: Displaying Array Elements
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
return 0;
}
Output
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have
printed numbers[i].
int main() {
int numbers[5];
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.
int main() {
double sum = 0;
double count = 0;
double average;
return 0;
}
Output
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];
Another Example:
Below is a 2-D array named a [rows] [cols], with rows = 3 and cols = 4.
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} };
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
int main() {
int numbers[2][3];
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.
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:
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}
}
};
#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}
}
};
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
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.
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).
Like arrays, it is not necessary to use all the space allocated for the string. For example:
#include <iostream>
using namespace std;
int main()
{
char str[100];
return 0;
}
Output
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
Output
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.
#include <iostream>
using namespace std;
int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);
Output
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)
#include <cstring>
These are:
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.
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.
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.