Documente Academic
Documente Profesional
Documente Cultură
LAB MANUAL
Revised Date
February 2015
Revision History
Revised Date
Revised By
Revised Topics
1. Lab Manual # 1 is added to
introduce the software
Code::Blocks instead of
Sadaf Inam
September, 2014
Sadaf Inam
February, 2014
Sadaf Inam
2|Page
C ER TI FICA TE O F AP PROVA L
It is certified that the lab manual titled Computer Programming, in scope and in quality, covers
the objectives and topics defined in the course outline.
Remarks by Mentor:
---------------------------------------------Nabeel Shehzad
Assistant Professor
Department of Electrical Engineering
The University of Lahore
Remarks by HOD:
3|Page
Contents
Lab 01 Part 01: ......................................................................................................................................... 6
Introduction to Programming Using Code::Blocks .............................................................................. 6
Lab 01 Part 02: ....................................................................................................................................... 17
Selection Control Structure (if, if/else) ................................................................................................... 17
Lab 02:........................................................................................................................................................ 23
Selection Control Structure(Switch Statement) .................................................................................. 23
Lab 03:........................................................................................................................................................ 29
Repetition Control Structure (Counter - Controlled For and While Loop) ...................................... 29
Lab 04:........................................................................................................................................................ 36
Arrays ..................................................................................................................................................... 36
Declaring Arrays: ...................................................................................................................................... 36
Initializing Arrays:....................................................................................................................................... 37
Accessing Array Elements:........................................................................................................................ 37
Lab 05:........................................................................................................................................................ 44
Strings..................................................................................................................................................... 44
The C-Style Character String: .................................................................................................................... 44
Lab 06:........................................................................................................................................................ 51
2D arrays ................................................................................................................................................ 51
Two-Dimensional Arrays: .......................................................................................................................... 51
Initializing Two-Dimensional Arrays: ........................................................................................................... 52
Accessing Two-Dimensional Array Elements: ............................................................................................ 52
Lab 07:........................................................................................................................................................ 58
Functions (Value Returning Functions)............................................................................................... 58
Defining a Function: .................................................................................................................................. 59
Example: .................................................................................................................................................. 59
Lab 08:........................................................................................................................................................ 63
Functions (Void Functions) .................................................................................................................. 63
Function Declarations:............................................................................................................................... 63
Calling a Function:..................................................................................................................................... 64
Function Arguments:................................................................................................................................. 65
Default Values for Parameters: .................................................................................................................. 66
4|Page
Lab 09:........................................................................................................................................................ 72
Functions ( ............................................................................................................................................. 72
Example 1: Passing One-dimensional Array to a Function .................................................. 72
Passing Multidimensional Array to a Function ......................................................................... 73
Example 2: Passing Multidimensional Array to a Function ................................................... 73
Lab10: ......................................................................................................................................................... 78
Recursion ............................................................................................................................................... 78
Lab 11:........................................................................................................................................................ 83
Pointers ................................................................................................................................................... 83
Address-of operator (&) ...................................................................................................................... 84
Dereference operator (*) .................................................................................................................... 85
Declaring pointers ............................................................................................................................... 87
Lab 13:........................................................................................................................................................ 92
Lab 14:...................................................................................................................................................... 103
Structures ............................................................................................................................................. 103
How to define a structure in C++ programming? ................................................................... 103
How to define a structure variable? ........................................................................................... 104
How to access members of a structure? .................................................................................. 104
Example 1: C++ Structure ............................................................................................................. 104
Lab 15:...................................................................................................................................................... 109
Files ...................................................................................................................................................... 109
OpeningaFile:............................................................................................................................................ 110
ClosingaFile.............................................................................................................................................. 112
WritingtoaFile:............................................................................................................................................ 113
ReadingfromaFile:...................................................................................................................................... 113
Read&WriteExample:................................................................................................................................. 113
Lab 16:...................................................................................................................................................... 120
Files ...................................................................................................................................................... 120
5|Page
Most of you would already be familiar with code::blocks, this part is for you to study at
home. Move to the programs part.
Prerequisites:
No prerequisite is required.
Resources:
Personal Computer installed with latest version of Code::Blocks.
A program is called the set of instructions given to perform a specific task. Every C++ program
has a function called main. Thus, if a C++ program has only one function, it must be the function
main. Any program you want to implement must be written in main( ). In a C++ program,
statements are executed in a sequential manner. So it is also called a sequential programming.
6|Page
C++ program must include some Preprocessor directives for the successful completion of the
program. Without these directives a program cannot run. Preprocessor directives are processed
by a program called a Preprocessor.
Preprocessor directives are commands supplied to the preprocessor that cause the preprocessor to
modify the text of a C++ program before it is compiled. All preprocessor commands begin with
#. There are no semicolons at the end of preprocessor commands because they are not C++
statements. To use a header file in a C++ program, use the preprocessor directive include.
For example, the following statement includes the header file iostream in a C++ program:
#include <iostream>
Preprocessor directives to include header files are placed as the first line of a program so that the
identifiers declared in those header files can be used throughout the program.
7|Page
8|Page
9|Page
4. Applictaion Settings:
After specifying the appliaction type, select the language. Two options will appear C and C++.
You must select C++.
10 | P a g e
11 | P a g e
6. Compiler Selection:
From the next window, compiler sholud be selected. As we are working with C++, so the
compiler will be GNU GCC compiler. Check the buttons of Create Debug configuration and
Create Release configuration. The paths of these debug and release will automatically adjust.
12 | P a g e
After pressing the Finish button, a new window will appear like below:
13 | P a g e
14 | P a g e
After writing the code of the program, check the correctness of the program by displaying the
output. For this purpose, you will select the Build button from the menu bar and then select
Build and Run. Short key for this is F9.
15 | P a g e
9. Output Window:
If your program is free from any syntax error, then the compiler will show you the output in the
separate window.
Lab Outcomes:
At the end of this lab, students will have complete understanding to use the software
Code::Blocks. Students will be able to write, compile and run the program using Code::Blocks.
16 | P a g e
Prerequisites:
Resources:
Personal computer installed with the latest version of Code::Blocks.
}
Ifis a Keyword (Reserve word).Condition can be any expression that will evaluate to true or
false. The Statement-block is executed if condition is true.
Else part is combined with theif part. Else part is written without any condition. If the condition
in the ifpart is false the itselsepart will execute. Syntax of if/else structure is:
if ( Condition )
{
Statement 1;
Statement 2;
.
Statement N;
}
else
{
Statement 1;
Statement 2;
.
Statement N;
}
Nested Structure:
Nested if/else structure is the structure containing if/else inside some if/else. General syntax of
nested if/else structure is:
if ( condition )
{
if ( condition )
statement-block;
else
statement-block;
}
else
{
if ( condition )
statement-block;
else
statement-block;
}
Inner if will execute if the outer if is executed otherwise the else part will execute. In the nested
else structure if the inner if is false then its else part will execute.
18 | P a g e
Lab Assignments:
1. Write a program that takes input of a number from user then checks and prints whether it is
even or odd.
Example1:
Example2:
Enter a number: 49
Enter a number: 22
2. Write a program that takes input of a number from user then checks and prints whether it is
negative or positive.
Example1:
Example2:
Enter a number: 12
Enter a number: -8
3. Write a program that takes input of two numbers from user then checks and prints which is
greater of them.
Example1:
Example1:
Example2:
greater
is greater
4. Write a program that takes input of number from user then prints whether the number is
divisible by 7 or not.
Example1:
Example2:
Enter a number: 49
Enter a number: 22
Number is divisible by 7
19 | P a g e
5. Write a program that takes input of a five-digit number from user then determines whether it
is a Numerical Palindrome. A Numerical Palindrome is a number that is the same forward
and backward, such as 43134.
Example1:
Example2:
Numerical Palindrome
6. Write a program that takes input of a number from user then prints whether the number is
divisible by 6 or by 8.
Example1:
Example2:
Example3:
Enter a number: 6
Enter a number: 8
Enter a number: 5
It is divisible by 2 and 3
It is divisible by 2 only
It is not divisible by 2
both.
and 3 both.
7. Write a program that takes input of a character type variable then do the following
conversion. If the entered character is:
i.
ii.
Example2:
Example3:
Output: B
Output: ?
Output: #
8. Write a program that reads 5 values and then determines and outputs whether the sequence
entered is sorted in ascending order, descending order, or is unordered.
Example1:
Example2:
Example3:
Enter 5 numbers:
Enter 5 numbers:
Enter 5 numbers:
32
Output:
17
99
15 11 9 1
Output:
1 72
Output:
order
order
manner
9. A program that prompts the user to input x, y coordinates of a point in a Cartesian plane. The
program should then output a message indicating whether point is origin, is located on x or y
axis or appears in a particular quadrant.
Example1:
Example2:
Example3:
Output:
point
is
in
quadrant
10. Write a program that takes input of two integer type variables from user then prints whether
first number is a multiple of second, or second number is a multiple of first number, or both
are not multiples of each other.
Example1:
Example2:
Example3:
Output:
Output:
Output:
Both are not multiple of each Second number is a multiple First number is a multiple of
other
of first number
second number
Lab Outcomes:
At the end of this lab, the students will have complete understanding of nested selection control
structure. Students will have a good command to perform the programs of nested if and nested
if/else structure.
21 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
Lab 02:
Selection Control Structure(Switch Statement)
Objectives:
Prerequisites:
Resources:
Personal computer installed with the latest version of Code::Blocks.
23 | P a g e
case value2:
statements
break;
case valueN:
statements
break;
default:
statements
}
In C++, switch, case, break, and default are reserved words. In a switch structure, first the
expression is evaluated. The value of the expression is then used to perform the actions specified
in the statements that follow the reserved word case.
Although it need not be, the expression is usually an identifier. Whether it is an identifier or an
expression, the value can be only integral. The expression is sometimes called the selector. Its
value determines which statement is selected for execution. A particular case value should
appear only once. One or more statements may follow a case label, so you do not need to use
braces to turn multiple statements into a single compound statement. The break statement may or
may not appear after each statement.
The switch statement executes according to the following rules:
a. When the value of the expression is matched against a case value (also called a label), the
statements execute until either a break statement is found or the end of the switch
structure is reached.
b. If the value of the expression does not match any of the case values, the statements
following the default label execute. If the switch structure has no default label and if the
value of the expression does not match any of the case values, the entire switch statement
isskipped.
c. A break statement causes an immediate exit from the switch structure.
24 | P a g e
Lab Assignment:
1. Write a program that takes input of a number as week day (1-7) then prints week day
accordingly.
Example1:
Example2:
Output: Saturday
2. Write a program that takes input of a number then prints whether is it even or odd.
Example1:
Example2:
Enter a number: 6
Enter a number: 9
Output: Even
Output: Odd
3. Write a program that takes input of a number then prints whether is it negative or positive.
Example1:
Example2:
Enter a number: 16
Output: positive
Output: Negative
4. Write a program that takes input of a number as month (1-12) then prints month accordingly
Example1:
Example2:
Output: September
5. Write a program that takes input of an alphabet then prints whether it is a vowel or
consonant.
Example1:
Example2:
Enter an alphabet: k
Enter an alphabet: A
Output: Consonant
Output: Vowel
25 | P a g e
6. Write a program that takes two integer type variables and an arithmetic operator (+, - , *, /,
%) as input then performs arithmetic operations on input numbers accordingly.
Example1:
Example2:
Example3:
Enter Operator: +
Enter Operator: *
Output: 9
Output: 10
7. Write a program that takes input of an alphabet then prints whether it is a capital alphabet or
not.
Example1:
Example2:
Example3:
Enter an alphabet: M
Enter an alphabet: a
Enter an alphabet: 9
8. Write a program that takes input of an alphabet then prints whether it is a small alphabet or
not.
Example1:
Example2:
Example3:
Enter an alphabet: m
Enter an alphabet: B
Enter an alphabet: 9
9. Write a program that takes input of a capital alphabet then prints it in small alphabet.
Example1:
Example2:
Example3:
Enter an alphabet: A
Enter an alphabet: h
Enter an alphabet: 0
Output: a
10. Write a program that takes input of a small alphabet then prints it in capital alphabet.
Example1:
Example2:
Example3:
Enter an alphabet: b
Enter an alphabet: H
Enter an alphabet: 19
Output: B
26 | P a g e
Lab Outcomes:
At the end of this lab, students will have a complete knowledge of the switch structure. Students
can make the programs related to the selection using the switch structure in the program.
27 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
Lab 03:
Repetition Control Structure (Counter Controlled For and While Loop)
Objectives:
Prerequisites:
Must be able to explain which of the loops are valid and which are invalid with
reason.
Resources:
Personal computer installed with the latest version of Code::Blocks.
29 | P a g e
There are two control structures used often: the for loop and the while loop. In C++, for and
while are reserved words. General syntax of for loop is:
for (initialization; condition; modification)
{
Statement 1;
Statement 2;
.
.
Statement N;
}
General syntax for while loop is:
while (condition)
{
Statement 1;
Statement 2;
.
.
Statement N;
}
In the counter-controlled loop, a variable is initialized as the counter of the loop. That variable is
evaluated according to some condition. If the given condition holds true then the loop will
execute. After executing the loop statements, loop counter variable is modified and that new
modified value is evaluated again according to the given condition. Again the whole process is
repeated until the given condition becomes false. After the condition becomes false, the loop will
terminate and do not execute further.
Lab Assignments:
1. Write a program to print the sum of odd numbers from 35 50.
2. Write a program to print the squares and cubes of all the numbers from 1 5.
3. Write a program to print the cubes of the numbers in the range given by the user. User will
enter the starting number and ending number and then your program will calculate the cubes
of those numbers.
30 | P a g e
Example1:
Example2:
Output:
Output:
16
64
25
125
36
216
1
4
4. Write a program that that takes input 8 numbers from user in a single variable using loop.
Then display sum of all the even numbers.
Example1:
Example2:
Enter 8 Numbers: 2 4 6 0 1 3 1 5
Enter 8 Numbers: 1 4 2 0 1 8 1 5
Output:
Output:
5. Write a program that takes input 8 numbers from user in a single variable using loop. Then
the program will print the total number of even elements and the number of odd elements.
Example1:
Example2:
Enter 8 Numbers: 2 4 6 0 1 3 1 5
Enter 8 Numbers: 1 4 2 0 1 8 1 5
Output:
Output:
6. Write a program that takes input 6 numbers from user in a single variable using loop. Then
prints how many of them were in the range of 35 to 50 and how many were out of this range.
Example1:
Example2:
Enter 6 Numbers: 24 61 50 11 37 41
Enter 6 Numbers: 44 61 50 11 37 41
Output:
Output:
7. Write a program to print the table of a number entered by the user from 1 5.
31 | P a g e
Example1:
Example2:
Enter a Number: 4
Enter a Number: 6
Output:
Output:
4 * 1= 4
6 * 1= 6
4 * 2= 8
6 * 2 = 12
4 * 3 = 12
4 * 4 = 16
6 * 4 = 24
4 * 5 = 20
6 * 5 = 30
* 3 = 18
8. Write a program to take input of a number from user and find its factorial by increment
method.
Example1:
Example2:
Enter a Number: 5
Enter a Number: 3
Output:
Output:
Factorial = 120
Factorial = 6
9. Write a program to take input of a number from user and check that the given number is
prime number or not.
Example1:
Example2:
Enter a Number: 5
Enter a Number: 60
Output:
Output:
Prime Number
Not Prime
10. Write a program that takes input of a number and its power from user. Calculate the number
rose to the power given by user.
Example1:
Example2:
Enter a Number: 5
Enter a Number: 2
Enter power: 3
Enter power: 5
Output:
Output:
32 | P a g e
5 power 3 = 125
2 power 5 = 32
11. Write a program to take input of a 4 digit number from user and calculate the sum of its
digits.
Example1:
Example2:
Output:
Output:
Lab Outcomes:
After performing this lab, the students will be able to:
1
12
123
2. Write a program to print the following patterns on the screen. Take input of row number
and the character, that is to be printed, from user.
$$$$$$
$$$$$
$$$$
%%%%%%%%%%
%
33 | P a g e
$$$
$$
$
%
%
%%%%%%%%%%
4
6
8
10
6
8
10
12
8
10
12
14
10
12
14
16
*
***
*****
*******
*********
H I J K L M
I J K LM
J K LM
K L M
L M
M
10 0 0 0
01000
00100
00010
00001
*
**
***
****
*****
1 3 5 7 9 13
1 3 5 7 9
1 3 5 7
1 3 5
1 3
1
34 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
Lab 04:
Arrays
Objectives:
To understand arrays
Prerequisites:
Study chapter 9, Arrays and Strings from book, C++ Programming: From problem
analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
Declaring Arrays:
To declare an array in C++, the programmer specifies the type of the elements and the number of
elements required by an array as follows:
36 | P a g e
This is called a single-dimension array. The arraySize must be an integer constant greater than
zero and type can be any valid C++ data type. For example, to declare a 10-element array called
balance of type double, use this statement:
double balance[10];
Initializing Arrays:
You can initialize C++ array elements either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index
will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is
also called base index. Following is the pictorial representaion of the same array we discussed
above:
37 | P a g e
The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example, which will use all the above-mentioned three concepts viz. declaration,
assignment and accessing arrays:
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
return 0;
}
This program makes use of setw() function to format the output. When the above code is compiled
and executed, it produces the following result:
Element
Value
100
38 | P a g e
101
102
103
104
105
106
107
108
109
Lab Assignments:
Program#1:
Write a program that declares an array abc of 10 elements of type int. Initialize each element of
array with cube of the index variable. Then display all values in the array using loop.
Output:
Values in array are 0 1 8 27 64 125 216 343 512 891
Program#2:
Write a program that declares an integer array of size 10 and reads values from user in it. Then
find out how many elements are even and how many are odd.
Output:
Enter values in array: 4 2 12 65 71 34 18 98 30 12
Even numbers are: 7
Odd Numbers are: 3
Program#3:
Write a program that declares an integer array of size 10 and reads values from user in it. Then
replace its negative elements with same positive values.
Output:
Enter values in array A:
14 -21 12 - 65 -87 34 -58 0 30 12
After replacement values are: 14 21 12
65 87 34 58 0 30 12
Program#4:
39 | P a g e
Write a program that declares an integer array of size 10 and reads values from user in it.
Calculate the average of 10 values stored in array and print all those values which are greater
than the calculated average
Output:
Values in array are 10 51 82 27 45 25 92 15 12 65
Average is= 39.9
Values greater than average are: 51 82 45 92 65
Program#5:
You have two arrays A and B, each of 10 integers. Then check whether every element of array A
is equal to its corresponding element in array B. in other words, the program must check if A[0],
is equal to B[0], A[1], is equal to B[1] and so forth. Print whether both arrays are equal or not.
Output:
Enter values in 1st array: 21 4
Enter values in 2nd array: 21 4
Both Arrays are equal
54
54
61
61
78
78
29 30 31 6 52
29 30 31 6 52
Program#6:
Write a program to copy the contents of one array into another array in reverse order.
Output:
Enter values in array A: 21 4 54 61
78 29 30 31 6 52
Values in array B are: 52 6 31 30
29 78 61 54 4 21
Program#7:
Write a program that inputs an integer array A of size 6 and an array B of size 7. Declare another
array of size 13 and store all values of A and B in array C.
Output:
Enter values in array A: 1 4 15 61 72 19
Enter values in array B: 8 14 54 31 18 29 34
Values stored in C are: 1 4 15 61 72 19 8 14 54 31 18 29 34
Program#8:
Write a program that takes an integer array of size 10 from user then checks and prints whether it
is in ascending order, descending order or unordered.
Output
Enter numbers in the array 97 45 37 35 28 24 20 14 10 8
Array is in Descending Order
40 | P a g e
Program#9:
Write a program that takes an integer array of size 10 from user then prints the smallest and
largest element of the array.
Output
Enter numbers in the array 47 45 37 96 28 24 82 14 70 38
Smallest element in the array is 14
Largest element in the array is 96
Program#10:
Write a program that takes an integer array of size 10 from user then shifts its all elements to the
left and its first element on the last location. (Circular shift left)
Output
Enter numbers in the array: 47 45 37 96 28 24 82 14 70 38
After shifting left array is : 45 37 96 28 24 82 14 70 38 47
Lab Outcomes:
After performing this lab, the students will be able to:
Program#2:
Write a program that takes an integer array of size 10 from user and an integer n as input then
shifts the whole array n number of times to the left.
Output
Enter numbers in the array: 47 45 37 96 28 24 82 14 70 38
How many times you want to shift? 3
After shifting right array is : 96 28 24 82 14 70 38 0 0 0
41 | P a g e
Program#3:
Write a program that takes an integer array of size 8 from user. Make sure entries in the array is
only multiples of 5 if user enters other value that is not a multiple of 5 then it should be entered
again. After storing values print final array.
Output
Enter values in Array 10 12 55 50 70 19 18 10 20 80 11 13 65
Stored values in Array are 10 55 50 70 10 20 80 65
Program#4:
Write a program that takes an integer array of size 8 from user and the draw a chart for each of
its input value. (Histogram)
Output
Enter numbers in the array: 7 5 0 9 12 4 18 7 13 5
7 *******
5 *****
0
12 ************
4 ****
18 ******************
7 *******
13 *************
5 *****
42 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
43 | P a g e
Lab 05:
Strings
Objectives:
Prerequisites:
Study chapter 9, Arrays and Strings from book, C++ Programming: From problem
analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
44 | P a g e
If you follow the rule of array initialization, then you can write the above statement as follows:
char greeting[] = "Hello";
Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string:
#include <iostream>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
45 | P a g e
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than
0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
int main ()
{
char str1[10] = "Hello";
46 | P a g e
len ;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Lab Assignments:
Program#1:
Write a program that takes a string as input from user then converts its capital letters into small
letters and small letters into capital letters.
Output
Enter a string
Learn from Yesterday, Live for Today, Hope for Tomorrow
lEARN FROM yESTERDAY, lIVE FOR tODAY, hOPE FOR tOMORROW
47 | P a g e
Program#2:
Write a program that takes a string as input from user then prints whether it is palindrome or not.
(Palindrome is a type of word play in which a word, phrase, or sentence reads the same
backward or forward)
Output
Enter a string
no evil shahs live on
The given string is a Palindrome string
Program#3:
Write a program that takes a string as input from user then capitalize its each word.
Output
Enter a string
We must accept finite disappointment, but never lose infinite hope
We Must Accept Finite Disappointment, But Never Lose Infinite Hope
Program#4:
Write a program that inputs a string, a sub-string and location (where user wants to add
substring) and then inserts the substring to the location provided by the user.
Output
Enter a string:
Pleases this application and give me gratuity
Enter Substring: read
Location : 7
After inserting substring final output is
Pleases read this application and give me gratuity
Program#5:
Write a program that takes two strings as input from user then prints whether both strings are
equal or not without using built-in function of strcmp().
Output
Enter first string:
He that lives upon hope will die fasting
Enter second string:
He that lives upon hope will die fasting
The given strings are equal
Program#6:
48 | P a g e
Write a program that takes a string and a character from user as input then remove that character
from the string and print the final string.
Output
Enter the string:
He that lives upon hope will die fasting
Enter the character you want to remove: i
Final string after removing i is:
He that lves upon hope wll de fastng
Program#7:
Write a program that takes a string as input then replaces all words of is by was.
Output
Enter the string:
This blue pen is for the kid, which is wearing blue shirt and is looking healthy.
Final string after replacement is:
This blue pen was for the kid, which was wearing blue shirt and was looking healthy.
Lab Outcomes:
After performing this lab, the students will be able to:
49 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
50 | P a g e
Lab 06:
2D arrays
Objectives:
Prerequisites:
Study chapter 9, Arrays and Strings from book, C++ Programming: From problem
analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
Two-Dimensional Arrays:
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 x,y, you would write something as follows:
51 | P a g e
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName 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 a, which contains three rows and four columns can be shown as
below:
Thus, every element in array a is identified by an element name of the forma[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.
/*
{4, 5, 6, 7} ,
/*
/*
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
52 | P a g e
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above digram.
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
return 0;
}
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
53 | P a g e
As explained above, you can have arrays with any number of dimensions, although it is likely that
most of the arrays you create will be of one or two dimensions.
Lab Assignments:
Program#1:
A program that takes a 6*6 matrix, then stores the sum of row number and column number for
each element. Output would be as follows.
1
2
3
4 5 6
1
2
3
4
5
6
7
2
3
4
5
6
7
8
3
4
5
6
7
8
9
4
5
6
7
8
9 10
5
6
7
8
9 10 11
6
7
8
9 10 11 12
Program#2:
A program that generates the following output using a 2-D array. (Use nested loops to store
values in array)
2
4
6
8
10
12
4
6
8
10
12
14
6
8
10
12
14
16
8
10
12
14
16
18
10
12
14
16
18
20
12
14
16
18
20
22
Program#3:
A program that reads two 2-d arrays as 3*3 matrices then calculates and stores their product into
another 2-d array of size 3*3.
Array A
3
1
12
5
9
10
6
2
7
Array B
4
2
3
6
3
8
7
5
6
81
82
28
49
64
89
158
176
54 | P a g e
Program#4:
A program that reads a 2-d array as 3*3 matrix then checks whether the matrix is symmetric or
not. A matrix is symmetric if mat [ i ] [ j ] = mat [ j ] [ i ] for all i and j except when i = j.
3
1
12
1
9
10
12
10
7
Matrix is symmetric
Program#5:
A program that reads a 2-d array as 3*3 matrix then calculates and prints its Determinant.
|A| = a11 (a22 a33 a23 a32) (a12 (a21 a33 a23 a31) +a13 (a21 a32 a22 a31)
Program#6:
A program that fills the right-to-left diagonal of a square matrix with 0s, the lower right triangle
with -1s, and the upper left triangle with +1s. The output of the program, assuming a 6*6 matrix,
is as follows.
+1
+1
+1
+1
+1
0
+1
+1
+1
+1
0
-1
+1 +1 +1
+1 +1 0
+1 0 -1
0 -1 -1
-1 -1 -1
-1 -1 -1
0
-1
-1
-1
-1
-1
Program#7:
A program that creates a 2-d Array matrix, representing the Pascal triangle. In a Pascal triangle ,
each element is the sum of the element directly above it and the element to the left of the element
directly above it (if any). A Pascal triangle of size 7 is as follows.
1
1
1
1
1
1
1
1
2
3
4
5
6
1
3
6
10
15
1
4
10
20
1
5
15
1
6
Program#8:
A program that takes an array of 8 strings to store names in it then display only those names that
starts with letter A.
55 | P a g e
Lab Outcomes:
After performing this lab, the students will be able to:
56 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
57 | P a g e
Lab 07:
Functions (Value Returning Functions)
Objectives:
To understand how you divide your problem into sub problems and calling functions in
other functions as well as in main()
Prerequisites:
Study chapter 6, Functions from book, C++ Programming: From problem analysis
to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
58 | P a g e
A function is knows as with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of
a function:
Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Function Body: The function body contains a collection of statements that define what the
function does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum between the two:
// function returning the max between two numbers
59 | P a g e
return result;
}
Lab Assignments:
Program#1:
Write a function that takes two values as parameter. It returns sum of x and y if x is greater than
y, otherwise it returns x minus two times y.
Program#2:
Write a function Dconversion() that converts a 4-bit binary integer into decimal equivalent.
Function takes one parameter of binary number and returns decimal number.
Hint: The decimal equivalent of binary 1101 is 1*1+0*2+1*4+1*8 or 1+0+4+8=13
Program#3:
Write a program that by defining a function even_odd(), to test whether a given integer is even or
odd. Pass an integer value as an argument to a function. The function returns 1 if number is Even
and 0 otherwise. Print corresponding messages in main() function.
Program#4:
Write a value returning function, isVowel(), which returns the value 1 if a given character is a
vowel and otherwise returns 0.
Program#5:
Write a function lcm() that takes two parameters as input then returns their least common
multiple to the main.
60 | P a g e
Program#6:
Write a function reverse() that takes an integer input as argument and returns its reverse. For
example if input number is 12345 then function would return 54321.
Program#7:
Write a function gcd() that takes two parameters as input then returns their greatest common
divisor to the main.
Program#8:
Write a function perfect() that takes input of an integer variable then returns 1 if it is perfect, 0
otherwise. (A number is perfect if sum of factors including 1 but not the number itself is equal to
the number)
Program#9:
Two positive integers are friendly if each one is equal to the sum of the divisors (including one
and excluding the number itself) of each other. Write a function to find weather given numbers
are friendly or not.
Example, 220 and 284 are friendly. 1+2+4+5+10+11+20+22+44+55+110=284
1+2+4+71+142=220
Lab Outcomes:
After performing this lab, the students will be able to:
Apply the syntaxes of functions with some value being returned from the function.
61 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
62 | P a g e
Lab 08:
Functions (Void Functions)
Objectives:
Prerequisites:
Study chapter 7, Functions from book, C++ Programming: From problem analysis
to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not importan in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);
63 | P a g e
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling the
function.
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its functionending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and
if function returns a value, then you can store returned value. For example:
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
64 | P a g e
return result;
}
I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result:
Max value is : 200
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parametersof the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type
Call by value
Description
65 | P a g e
Call by pointer
Call by reference
By default, C++ uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example while
calling max() function used the same method.
result = a + b;
return (result);
}
66 | P a g e
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120
Lab Assignments:
Program#1:
Write a function with name equl() that takes two integer parameters by reference. It then sets
both values with the smallest value between them. Print both values in main before and after
calling the function
Output
Enter first number 67
Enter second number 17
Before function call values are 67 , 17
Before function call values are 17 , 17
67 | P a g e
Program#2:
Write a function that takes two integer parameters as input and prints all tables between these
two numbers.
Output
Enter first number 3
Enter second number 5
3*1=3
3*2=6
.
.
.
.
5*8=40
5*9=45
5*10=50
Program#3:
Write a function that takes two integer parameters from user and prints all prime numbers
between them.
Output
Enter first number 10
Enter second number 40
All prime numbers between 10 and 40 are
11,13,17,19,23,29,31,37
Program#4:
Write a function that takes three integer parameters as reference and swaps their values. Also
write main program that prints the values before and after function call. (You cant declare a
fourth variable in the program)
Output
Enter first number 10
Enter second number 40
Enter third number 89
Before function call x=10, y=40, z=89
After function call x=89, y=10, z=40
68 | P a g e
Program#5:
Write a function triangle() that takes an integer input as argument and prints its triangle. For
example if user enters 6 the function should print the following triangle shape. (triangle would
always start with letter Z).
Output
Enter a number: 6
ZYXWVU
ZYXWV
ZYXW
ZYX
ZY
Z
Program#6:
Write a function triangle() that takes an integer input as argument and prints its triangle. For
example if user enters 9 the function should print the following triangle shape. (Make sure that
the input integer is odd if user enters an even number the input should be entered again)
Output
Enter a number: 16
Plese enter an odd number: 9
97531
7531
531
31
1
Program#7:
Write a program that takes 8 inputs from user in main using loop. Each time an input is given it
is passed to a function Slarge(). Slarge function takes one input as parameter and keeps record of
largest number and second largest number entered till now. (Hint: use global variables to keep
record of largest and second largest numbers)
Output
Enter numbers: 16
5
2
11
90
16
73
65
69 | P a g e
Lab Outcomes:
After performing this lab, the students will be able to:
Design programs and having understanding difference between void and value
returning functions
70 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
71 | P a g e
Lab 09:
Functions (Passing Arrays to Functions)
Objectives:
Prerequisites:
Study chapter 6 & 7, Functions from book, C++ Programming: From problem
analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
72 | P a g e
}
}
Output
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
When an array is passed as an argument to a function, only the name of an array is used as
argument.
display(marks);
Also notice the difference while passing array as an argument rather than variable.
void display(int m[5]);
The argument used marks in the above code represents the memory address of first
element of array marks[5] . And the formal argument int m[5] in function declaration
decays to int* m; . That's why, although the function is manipulated in the user -defined
function with different array name m[5] , the original array is manipulated. The C++
programming language handles passing array to a function in this way to save memory and
time.
Note: You need to have understanding of pointers to understand passing array t o a
function. Learn more: Call by reference
73 | P a g e
#include <iostream>
using namespace std;
void display(int n[3][2]);
int main() {
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}
void display(int n[3][2]) {
cout<<"Displaying Values: "<<endl;
for(int i = 0; i < 3; ++ i) {
for(int j = 0; j < 2; ++j) {
cout<<n[i][j]<<" ";
}
}
}
Output
Displaying Values:
3 4 9 5 7 1
Multidimensional array with dimension more than 2 can be passed in similar way as two
dimensional array.
Lab Assignments:
Program#1:
Write a program that inputs two integer arrays from user of size 8 then passes these two array
and another array of same size to the function small(). The function small() then compares the
input integr array values and stores the smallest of them in third array. For example it first
compares a[0] and b[0] the smallest value between them is stored in c[0].
Output
Enter numbers in array A: 6 12 87 19 19 10 20 91
Enter numbers in array B: 7 8 15 52 11 4 40 100
After function call array C is:6 8 15 19 11 4 20 91
Program#2:
Write a program that inputs a string of size 100 and an integer from user then passes both to a
74 | P a g e
function as arguments. The function then extract given number of characters from the string.
Output
Enter a string
The best way to find yourself is to lose yourself in the service of others
Enter an integer:17
Extracted string is:
service of others
Program#3:
Write a function that takes an integer array and its size as arguments and then shift the negative
numbers to the left and positive numbers to the right.
Output
Enter numbers in the array:
3 -5 1 3 7 0 -15 3 -7 -8
The array after function call is: -5 -15 -7 -8 3 1 3 7 0 3
Program#4:
Write a program that takes a string as argument and a character from user then passes both of
them to a function as arguments. If the character passed to the function is g then it replaces all
of the g with G and G with g.
Output
Enter a string
There are two tragedies in life. One is to lose your heart's desire. The other is to gain it.
Enter a character to replace: T
there are Two Tragedies in life. One is to lose your hearT's desire. the oTher is To gain iT.
Program#5:
Write a function that takes an integer array as an argument and its size also. The function then
prints the smallest even element and smallest odd element of the arry
Output
Enter 10 numbers in the array:
5 22 7 15 3 8 12 19 17 31
Smallest even number is 8
Smallest odd number is 3
Program#6:
Write a program that takes a 2-D character array and stores 6 names in it ( an array of strings of
6*80 size) then pass that array to a function named swap(). The swap() function will swap first
name with last name and print the array of strings.
Output
Enter 6 names:
Abdul Manan
Ali Hamza
Bilal Ahmad
75 | P a g e
M. Salman
Zahid Khan
Rehan Ali
After function call names are
Rehan Ali
Ali Hamza
Bilal Ahmad
M. Salman
Zahid Khan
Abdul Manan
Program#7:
Write a function that takes an array A of 3*3 size as an argument and calculates matrix B such
that each element in matrix B is equal to sum of neighbors of the corresponding elements in the
matrix A. consider sample given below:
1
2
3
11
19
13
4
5
6
23
40
27
7
8
9
17 31
19
Note that
Therefore
Similarly,
Therefore
Lab Outcomes:
After performing this lab, the students will be able to:
Must be able to explain passing one dimensional as well as two dimensional arrays to
the function
76 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
77 | P a g e
Lab10:
Recursion
Objectives:
Prerequisites:
Study chapter 14, Recursion from book, C++ Programming: From problem
analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
myFunction(--counter);
return;
}
}
This recursion is not infinite, assuming the function is passed a positive integer value. What will the
output be?
Consider this function:
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout<<"hello"<<counter<<endl;
myFunction(--counter);
cout<<counter<<endl;
return;
}
}
If the function is called with the value 4, what will the output be? Explain.
The above recursion is essentially a loop like a for loop or a while loop. When do we prefer recursion to
an iterative loop? We use recursion when we can see that our problem can be reduced to a simpler
problem that can be solved after further reduction.
Every recursion should have the following characteristics.
1. A simple base case which we have a solution for and a return value. Sometimes there are more
than one base cases.
2. A way of getting our problem closer to the base case. I.e. a way to chop out part of the problem
to get a somewhat simpler problem.
3. A recursive call which passes the simpler problem back into the function.
Lab Assignments:
Program#1:
Write a program that uses a recursive function to compute factorial of a number.
79 | P a g e
Program#2:
Write a program that takes two numbers from user as first and second of the Fibonacci Series
and then takes the number of the term that user wants to find in the series. You have to write a
recursive function to perform this task.
Program#3:
Write a recursive program that takes two numbers from user and calculates quotient using
recursive function without using / operator.
Program#4:
Write a recursive function that finds out whether a number is even or odd. You cant use %
operator. If you subtract 2 repeatedly from a number then finally the number will be reduced to 0
or 1, that would be base case for recursive call.
Program#5:
Write a recursive function power that takes as parameter two integers x and y such that x is
nonzero and returns xy. You can use the following recursive definition to calculate xy. If y>=0,
Power(x,y)={
(
) h
Program#6:
Write a program that takes an integer array and passes it to a recursive function. The function
then returns the largest number among array elements.
Program#7:
The expression of computing C (n,r), the number of combinations of n items taken r at a time is
C(n,r) = n! / r! (n-r)!.. Write a recursive function to calculate the C. moreover
C (n,0) = C(n,n) = 1.
It is also known that C(n,r) = C(n 1 , r - 1) + C(n-1 , r)
if 0<k<n
Program#8:
80 | P a g e
Write recursive GCD function, that finds greatest common divisor of two integers. Mathematical
Rule is given below.
gcd (x,y) =
gcd(y, x%y)
if y=0
if y0
Program#9:
Write a recursive function, that takes a string as argument and prints whether it is palindrome or
not.
Lab Outcomes:
After performing this lab, the students will be able to:
Apply the syntaxes of Calling a function inside the same function finitly.
81 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
82 | P a g e
Lab 11:
Pointers
Objectives:
Prerequisites:
Study chapter 14, Arrays and Strings from book, C++ Programming: From
problem analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
addresses where its variables are stored. Fortunately, that task is left to the environment where the
program is run - generally, an operating system that decides the particular memory locations on
runtime. However, it may be useful for a program to be able to obtain the address of a variable during
runtime in order to access data cells that are at a certain position relative to it.
This would assign the address of variable myvar to foo; by preceding the name of the
variable myvar with the address-of operator (&), we are no longer assigning the content of the variable
itself to foo, but its address.
The actual address of a variable in memory cannot be known before runtime, but let's assume, in order
to help clarify some concepts, that myvar is placed during runtime in the memory address 1776.
In this case, consider the following code fragment:
1 myvar = 25;
2 foo = &myvar;
3 bar = myvar;
The values contained in each variable after the execution of this are shown in the following diagram:
First, we have assigned the value 25 to myvar (a variable whose address in memory we assumed to
be 1776).
The second statement assigns foo the address of myvar, which we have assumed to be 1776.
84 | P a g e
Finally, the third statement, assigns the value contained in myvar to bar. This is a standard assignment
operation, as already done many times in earlier chapters.
The main difference between the second and third statements is the appearance of the address-of
operator (&).
The variable that stores the address of another variable (like foo in the previous example) is what in C++
is called apointer. Pointers are a very powerful feature of the language that has many uses in lower level
programming. A bit later, we will see how to declare and use pointers.
This could be read as: "baz equal to value pointed to by foo", and the statement would actually assign
the value 25 tobaz, since foo is 1776, and the value pointed to by 1776 (following the example above)
would be 25.
It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an
asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25.
Notice the difference of including or not including the dereference operator (I have added an
explanatory comment of how each of these two expressions could be read):
85 | P a g e
1 baz = foo;
2 baz = *foo;
& is the address-of operator, and can be read simply as "address of"
* is the dereference operator, and can be read as "value pointed to by"
Thus, they have sort of opposite meanings: An address obtained with & can be dereferenced with *.
Earlier, we performed the following two assignment operations:
1 myvar = 25;
2 foo = &myvar;
Right after these two statements, all of the following expressions would give true as result:
1
2
3
4
myvar == 25
&myvar == 1776
foo == 1776
*foo == 25
The first expression is quite clear, considering that the assignment operation performed
on myvar was myvar=25. The second one uses the address-of operator (&), which returns the address
of myvar, which we assumed it to have a value of1776. The third one is somewhat obvious, since the
second expression was true and the assignment operation performed on foo was foo=&myvar. The
fourth expression uses the dereference operator (*) that can be read as "value pointed to by", and the
value pointed to by foo is indeed 25.
So, after all that, you may also infer that for as long as the address pointed by foo remains unchanged,
the following expression will also be true:
*foo == myvar
86 | P a g e
Declaring pointers
Due to the ability of a pointer to directly refer to the value that it points to, a pointer has different
properties when it points to a char than when it points to an int or a float. Once dereferenced, the
type needs to be known. And for that, the declaration of a pointer needs to include the data type the
pointer is going to point to.
The declaration of pointers follows this syntax:
type * name;
where type is the data type pointed to by the pointer. This type is not the type of the pointer itself, but
the type of the data the pointer points to. For example:
1 int * number;
2 char * character;
3 double * decimals;
These are three declarations of pointers. Each one is intended to point to a different data type, but, in
fact, all of them are pointers and all of them are likely going to occupy the same amount of space in
memory (the size in memory of a pointer depends on the platform where the program runs).
Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the
same type: the first one points to an int, the second one to a char, and the last one to adouble.
Therefore, although these three example variables are all of them pointers, they actually have different
types:int*, char*, and double* respectively, depending on the type they point to.
Note that the asterisk (*) used when declaring a pointer only means that it is a pointer (it is part of its
type compound specifier), and should not be confused with the dereference operator seen a bit earlier,
but which is also written with an asterisk (*). They are simply two different things represented with the
same sign.
Let's see an example on pointers:
1
2
3
4
5
6
7
8
9
10
11
// my first pointer
#include <iostream>
using namespace std;
firstvalue is 10
secondvalue is 20
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
87 | P a g e
12
mypointer = &secondvalue;
13
*mypointer = 20;
14
cout << "firstvalue is " << firstvalue << '\n';
15
cout << "secondvalue is " << secondvalue <<
16 '\n';
17
return 0;
}
Lab Assignments:
Note: In all the following programs the variable values should not be used directly. Use
pointer notation to manipulate and printing the values.
Program#1:
Write a program that inputs two floating point numbers from user using pointer notation. Add
two times first value into second value. Add second value three times into first value. Then
display the final values stored in variables.
Output
Enter first number: 13.25
Enter second number: 8.61
After calculation
First number is: 30.47
Second number is: 48.36
Program#2:
Write a program that inputs two integers and then swaps the values and the program finally
displays the value using pointers.
Enter first number: 13
Enter second number: 61
After swapping
First number is: 61
Second number is: 13
Program#3:
Write a program that inputs two characters from user and change their cases. If both characters
are small alphabets then convert them into capital alphabets, if both are capital alphabets then
convert them in small alphabets, if anyone of them is small and other is capital then change their
cases.
Output
88 | P a g e
Enter an alphabet: h
Enter an alphabet: Y
After changing case output is H and y
Program#4:
Write a program that inputs three numbers from user and then prints the medium value among the
three inputs.
Output
Enter first number: 67
Enter second number: 17
Enter third number: 34
The number with medium value is 34
Program#5:
Write a program to input a number from keyboard until user enters a zero. Every time a number
is entered the program should display whether the number is greater than, less than, or equal to
the previous number.
Output
Enter a number: 26
Enter a number: 17
17 is smaller than 26
Enter a number: 32
32 is greater than 17
Enter a number: 32
32 is equal to 32
Enter a number: 0
Program#6:
Write a program that inputs five integers from user and prints their sum. The numbers should be
in the range of 20 to 50 if user enters a number out of this range then it should be entered again.
Output
Enter a number: 30
Enter a number: 17
17 is out of range please enter again
Enter a number: 22
Enter a number: 45
Enter a number: 59
59 is out of range please enter again
Enter a number: 41
89 | P a g e
Sum of 5 numbers=138
Lab Outcomes:
After performing this lab, the students will be able to:
90 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
91 | P a g e
Lab 12:
Passing Pointers to Functions
Objectives:
Prerequisites:
Study chapter, Pointers from book, C++ Programming: From problem analysis to
problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
int main ()
{
92 | P a g e
getSeconds( &sec );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Number of seconds :1294450468
The function which can accept a pointer, can also accept an array as shown in the following
example:
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
93 | P a g e
double avg;
return 0;
}
i, sum = 0;
double avg;
return avg;
}
When the above code is compiled together and executed, it produces the following result:
Average value is: 214.4
Lab Assignments:
Note: In all the following programs the variable values should not be used directly. Use
pointer notation to manipulate and printing the values.
94 | P a g e
Program#1:
Write a program that inputs an integer value from user using pointer notation. Pass that value to a
function named Check that receives value in a pointer. The function then checks if the number is
even it returns a pointer that stores square of the number, and returns cube otherwise. Display the
result in main.
Output
Enter a number: 13
Final result is: 2197
Program#2:
Write a program that inputs two integer values from user using pointer notation. Pass these
values to a function using pointers. The function then returns a pointer stored first second if
first value is greater than second and returns first + second otherwise. Display the result in main.
Output
Enter first number: 13
Enter second number: 35
Final result is: 48
Program#3:
Write a program that inputs a string from user in main. Pass that string to a function using
pointer. The function then reverses the string using pointer notation and a single repetition
statement. Also display final string in main.
Output
Enter a string
Arrays are called constant pointers
Reverse of string is
sretniop tnatsnoc dellac era syarrA
Program#4:
Write a program that inputs two integer arrays of size 8 from user using pointer notation. Pass
these arrays to a function using pointers. The function then returns 1 to main if both arrays are
reverse of each other and returns 0 otherwise. Display message in main accordingly.
Output
Enter values in first array: 7 5 19 28 16 10 18 39
Enter values in second array: 39 18 10 16 28 19 5 7
Both arrays are reverse of each other
95 | P a g e
Program#5:
Write a program that inputs a character array of size 10 from user. Pass that array to a function
using pointer that checks whether the characters in array are entered in ascending order that is the
first letter is smaller than the next one and so on. The function returns 0 to main if array is in
ascending order, returns 1 if array is in descending order and 2 otherwise. Print appropriate
messages in main.
Output
Enter characters in array: b e h i k m n q s y
Array is in Ascending order
Program#6:
Write a program that inputs a string from user in main. Pass that string to a function using
pointer. The function then removes all the vowels from string. Also display final string in main.
Output
Enter a string:
Only two things are infinite, the universe and human stupidity
After removing vowels string is
nly tw thngs r nfnt, th nvrs nd hmn stpdty
Program#7:
Write a program that takes six numbers from user and stores their addresses in an array of
pointer then finds and prints the smallest number using only pointer notation.
Output
Enter first number: 30
Enter second number: 17
Enter third number: 22
Enter fourth number: 45
Enter fifth number: 41
Enter sixth number: 61
Smallest number is 17
Lab Outcome:
96 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
97 | P a g e
Lab 13:
Dynamic Memory Allocation
Objectives:
Prerequisites:
Study chapter 14, Pointers from book, C++ Programming: From problem analysis
to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
98 | P a g e
Dynamic memory is allocated using operator new. new is followed by a data type specifier and,
if a sequence of more than one element is required, the number of these within brackets []. It
returns a pointer to the beginning of the new block of memory allocated. Its syntax is:
pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The
second one is used to allocate a block (an array) of elements of type type,
where number_of_elements is an integer value representing the amount of these. For example:
1 int * foo;
2
foo = new int [5];
In this case, the system dynamically allocates space for five elements of type int and returns a
pointer to the first element of the sequence, which is assigned to foo (a pointer).
Therefore, foo now points to a valid block of memory with space for five elements of type int.
Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with
the expression foo[0] or the expression *foo (both are equivalent). The second element can be
accessed either with foo[1] or *(foo+1), and so on...
Lab Assignments:
Program#1:
Write a program that inputs two floating point dynamic values. It then sets value to zero if a
number is greater than 50.
Output
Enter first value:19.32
Enter second value:63.5
First value is 19.32 and second value is 0
99 | P a g e
Program#2:
Write a program that takes two one-D integer arrays and inputs their size from user.Then pass
both the arrays and their size to a function. The function would then return the largest number
among both the array elements and print it in main.
Output
Enter size of array1:6
Enter values in array1: 4 12 41 32 16 91
Enter size of array2:8
Enter values in array2: 63 56 11 18 0 42 61 55
Largest element is 91
Program#3:
Write a program that inputs three dynamic integer values from user then pass these to a function
gcd(). The function then returns the greatest common divisor of these numbers. Print the result in
main.
Output
Enter first number:20
Enter second number:45
Enter third number:30
The greatest common divisor of 20, 45 and 30 is5
Program#4:
Write a programthat takes two dynamic integer arrays storing only binary digits in it. Your
program should sum both the arrays and store result in a third array in binary form. (Binary
addition).
Output
Enter binary digits in array1: 1 0 1 1 1 0 1
Enter binary digits in array2: 1 0 1 0 1 1 1
Sum of binary digits is :
1 0 1 1 0 1 0 0
Program#5:
Write a program that computesproduct of two matrices. Dimension of matrices must be taken
from the user. Your program must display the result in the matrix form if multiplication of
matrices is possible otherwise your program should display an error message.
Output
Enter rows for matrix1: 2
Enter columns for matrix1:2
Enter values in matrix1:
3 5
9 8
Enter rows for matrix2: 3
100 | P a g e
Program#6:
Write a program that takes input of a dynamic variable repeatedly from user until user enters 5
odd numbers. Ignoring even numbers, your program should calculate sum of these odd numbers.
Output
Enter 5 0dd numbers:
6
11
7
13
14
21
33
Sum of odd numbers is: 85
Program#7:
Write a programthat takes one dynamic integer array storing only binary digits in it. Your
program should then print 2s complement of this binary series.
Output
Enter binary digits in array: 1 0 1 1 1 1 0
2s complement ofbinary is: 0 1 0 0 0 1 0
Lab Outcomes:
After performing this lab, the students will be able to:
101 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
102 | P a g e
Lab 14:
Structures
Objectives:
Prerequisites:
Study chapter, Structure User Defined Datatype from book, C++ Programming:
From problem analysis to problem design by D.S. Malik
Resources:
Personal computer installed with the latest version of Code::Blocks.
103 | P a g e
float salary;
};
Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated. The structure definition is only the
blueprint for the creating of variables. You can imagine it as a datatype. When you define an
integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure definition
only specifies that, what property a structure variable holds when it is defined.
104 | P a g e
float salary;
};
int main() {
person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout
cout
cout
cout
return 0;
}
Output
Enter Full name: Magdalena Dankova
Enter age: 27
Enter salary: 1024.4
Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4
Here a structure person is declared which has three members. Inside main() function, a
structure variable p1 is defined. Then, the user is asked to enter information and data entered
by user is displayed.
Lab Assignments:
Program#1:
105 | P a g e
Creates a user defined structure type Time with three integer members hours, minutes and
seconds. The program defines a single Time structure type variable dinner_time. It uses the dot
operator to initialize the structures members with values given by user. Also write the print
function which takes a time type variable. It prints its time in hh:mm:ss format. Also and call a
function next40 which changes the given time type variable by adding 40 minutes to it and then
print it.
Program#2:
Create a user defined structure type Rectangle with these integer members, length and width. The
program defines a rectangle r1 and initializes the members according to user input. Then write a
function area which will take a rectangle type variableand calculate the area of that rectangle
call a function print in main which prints the given rectangle and also prints the area by calling
area function.
Program#3:
Write a function called increment that accepts a date structure with three fields each field is an
integer, one for the month, one for the day in the month, and one for the year. The function
increments the date by one day and returns the new date. If the date is the last day in the month,
the month field must also be changed. If the month is December, the value of the year field must
also be changed when the day is 31. A year is a leap year if it is evenly divisible by 4 but not by
100 or it is divisible by 400.
Program#4:
Write a function called futureDate. The function is to use two parameters. The first parameter is
a structure containing todays date. The second parameter is an integer showing the number of
days after today. The function returns a structure showing the next date, which may be in a future
year.
Program#5:
A point in a plane can be represented by its two coordinates, x and y. therefore, we can represent
a point in a plane by a structure having two fields, as shown below.
struct POINT
{
int x;
int y;
};
106 | P a g e
Write a function that accepts the structure representing a point and returns an integer(1, 2, 3, or
4) that indicates in which quadrant the point is located, as shown below.
2
3
1
4
I
II
III
IV
x
positive
negative
negative
positive
Y
positive
positive
negative
negative
Quartile coordinates
Program#6:
A straight line is an object connecting two points. Therefore, a line can be represented by a
nested structure having two structures of type POINT, as defined in the above problem.
struct LINE
{
POINT beg;
POINT end;
};
Program#7:
Write a function that accepts two parameters of type POINT and returns a structure of type LINE
representing the line connecting the two points.
Program#8:
Write a function that accepts a structure of type LINE and returns an integer (1, 2, 3), where 1
means vertical, 2 means horizontal, and 3 means oblique. A vertical line is a linewhose x
coordinates are the same. A horizontal line is the line whose y coordinates are the same. An
oblique line is a line that is not vertical or horizontal.
Lab Outcomes:
After performing this lab, the students will be able to:
107 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
108 | P a g e
Lab 15:
Files
Objectives:
Prerequisites:
Resources:
Personal computer installed with the latest version of Code::Blocks.
This tutorial will teach you how to read and write from a file. This requires another standard
C++ library called fstream, which defines three new data types:
Data Type
Description
109 | P a g e
ofstream
This data type represents the output file stream and is used to
create files and to write information to files.
ifstream
This data type represents the input file stream and is used to read
information from files.
fstream
This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can create
files, write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
OpeningaFile:
A file must be opened before you can read from it or write to it. Either
theofstream or fstream object may be used to open a file for writing and ifstream object is used
to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects.
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
Mode Flag
Description
ios::app
ios::ate
Open a file for output and move the read/write control to the end of the file.
ios::in
ios::out
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
111 | P a g e
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case it already exists, following will
be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );
ClosingaFile
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
112 | P a g e
WritingtoaFile:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
ReadingfromaFile:
You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream orfstream object instead of the cin object.
Read&WriteExample:
Following is the C++ program which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the program reads information from
the file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
113 | P a g e
char data[100];
115 | P a g e
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input and
output:
$./a.out
116 | P a g e
Above examples make use of additional functions from cin object, like getline() function to read
the line from outside and ignore() function to ignore the extra characters left by previous read
statement.
Lab Assignments:
Program#1:
Write a program that creates a new file and stores some text in it after writing text in the file it
also outputs file contents.
Program#2:
Write a program that opens an existing file in append mode and stores some new text in it after
writing text in the file it also outputs file contents.
Program#3:
Write a program that reads a file and then counts small and capital alphabets in it
117 | P a g e
Program#4:
Write a program that reads a file and then counts total number of words in it
Program#5:
Write a program that reads a file and count total number of spaces, char and digits comes.
Program#6:
Write a program that reads a file contents and copies them into another file.
Program#7:
Write a program that reads a file and then count how many time word the comes in the file.
Lab Outcomes:
After performing this lab, the students will be able to:
118 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
119 | P a g e
Lab 16:
Files
Objectives:
Prerequisites:
Resources:
Personal computer installed with the latest version of Code::Blocks.
Lab Assignments:
Program#1:
Write a program that reads a file and checks if there is any space, it replace that space with TAB
space.
Program#2:
Write a program to copy one file to another. While doing so replace all lowercase characters to
their equivalent uppercase characters.
Program#3:
Write a program that prints itself on the screen. It means program will read its own file and will
print data on screen.
Program#4:
Write a program that reads a file and verify that numbers of right and left braces are equal e.g.
{,}
Program#5:
Write a program to duplicate the fourth line in the file. Assume that the opened file does have
more than four lines.
Program#6:
121 | P a g e
Write a program that opens a C++ file and creates its copy by eliminating all the comments. Note
that the comments are of two types: Single line or multi line comments.
Program#7:
Write a program that opens a cpp file and finds how many integer variables are declared in it.
Program#8:
Write a program that calculates total number of characters in each line of the file.
Lab Outcomes:
After performing this lab, the students will be able to:
122 | P a g e
Each student is required to perform the lab and submit the following Performa along with the lab
report.
1 = Unsatisfactory
2 = Fair 3= Satisfactory
4 = Very good
Questions
5= Excellent
Rating
(1 to 5)
Remarks
123 | P a g e