Sie sind auf Seite 1von 123

COMPUTER PROGRAMMING (CS1112)

LAB MANUAL

Revised Date
February 2015

DEPARTMENT OF ELECTRICAL ENGINEERING


THE UNIVERSITY OF LAHORE
1|Page

Revision History

Revised Date

Revised By

Revised Topics
1. Lab Manual # 1 is added to
introduce the software
Code::Blocks instead of

February 05, 2015

Sadaf Inam

Turbo along with revision of


previous concepts.
2. Theory is added with
Manuals to assist student in
understanding concepts

September, 2014

Sadaf Inam

3. Overall the format of every


manual is changed and
conceptual programs are
added at the end of each lab
Code::Blocks installation
and project creation manual
was added.

February, 2014

Sadaf Inam

Some programs were added


from book.

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:

------------------------------------------------Dr. Asrar ul Haq Sheikh


Professor
Department of Electrical Engineering
The University of Lahore

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

Lab 01 Part 01:


Introduction to Programming Using
Code::Blocks
Objectives:
To understand

The use of Code::Blocks

How to write a program in C++ using Code::Blocks?

How to compile and run a C++ program in Code::Blocks?

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.

Introduction and Theory:


Code::Blocks is a free and open source, platform which supports multiple compliers including
GCC, Clang and visual C++. Currently, Code::Blocks is oriented towards C, C++ and
FORTRAN. Code::block is being developed for Windows, Linux and Mac OS X.

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

General syntax is:


main ( )
{
Statement 1;
Statement 2;
.
.
Statement1 N;
}

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.

The general syntax to include a header file in a C++ program is:


#include <headerFileName>

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

Create a C++ project in Code::Blocks:


1. Start Page:

2. Create a new Project:


For creating a new project, select the File button from menu bar then select Project.

8|Page

3. Select the required Application type:


After selcting the new project, a window will appear asking about the application in which you
want to create the program. From these options, you have to select the Console Application.

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

5. Naming the Project:


Next step is to save your project by a name. you must specify a project name and the path of the
folder where the project must be saved.

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

7. Write a program in C++:


To write a program in C++, you will select main.cpp from the left side under sources. After you
click main.cpp, now the code window will open and you can write any program in this window.

14 | P a g e

8. Check the output of the program:

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

Lab 01 Part 02:


Selection Control Structure (if, if/else)
Objectives:

To revise the important contents of Introduction to Computing, Sequential and Selection.

To revise simple conditions structure

To understand the Nested Condition structure

Prerequisites:

Study chapter 4, Control Structures I (Selection) from book, C++ Programming:


From problem analysis to problem design by D.S. Malik

Must have completed understating of Relational operators.

Must have completed understating of Logical operators.

Must have complete understating of evaluating an expression to True / False.

Resources:
Personal computer installed with the latest version of Code::Blocks.

Introduction and Theory:


Theif statement is the Decision Making Control Structure. It is used to execute a set of one or
more instructions if a specific condition is true.General syntax of if structure is:
if ( Condition )
{
Statement 1;
Statement 2;
Statement 3;
.
Statement N;
17 | P a g e

}
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

Output: Odd Number

Output: Even Number

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

Output: Positive Number

Output: Negative Number

3. Write a program that takes input of two numbers from user then checks and prints which is
greater of them.
Example1:

Example1:

Example2:

Enter first number: 12

Enter first number: 3

Enter first number: 8

Enter second number: 10

Enter second number: 10

Enter second number: 8

Output: First Number is

Output: Second Number

Output: Both are equal

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

Number is not 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:

Enter a number: 53235

Enter a number: 26126

Numerical Palindrome

Not a 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.

Capital alphabet then convert it into lower alphabet.

ii.

Small alphabet then convert it into capital alphabet.

iii. Digit then convert it into #


iv. Special symbol then do not convert it. Print it as it is.
Example1:

Example2:

Example3:

Enter the character: b

Enter the character: ?

Enter the character: 9

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:

Numbers are in ascending Numbers are in descending Numbers are in unordered


20 | P a g e

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:

Enter the value of x: 5

Enter the value of x: -3

Enter the value of x: 0

Enter the value of y: 0

Enter the value of y: 4

Enter the value of y: 0

Output: point is on X-axis

Output:

point

is

in

2nd Output: point is on origin

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:

Enter first number: 9

Enter first number: 6

Enter first number: 9

Enter second Number: 4

Enter second Number: 3

Enter second Number: 81

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------22 | P a g e

Lab 02:
Selection Control Structure(Switch Statement)

Objectives:

To understand the selection using the switch statement

To understand the execution of cases under switch

To understand the concept of break in switch structure

Prerequisites:

Study chapter 4, Control Structures I (Selection) , from C++ Programming: From


problem analysis to problem design by D.S. Malik
Must have complete understanding of selection using the if/else structure.

Resources:
Personal computer installed with the latest version of Code::Blocks.

Introduction and Theory:


Switch structure is the selection control structure. It does not require the evaluation of the logical
expression like if/else structure. General syntax of switch structure is:
switch ( expression)
{
case value1:
statements
break;

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:

Enter a number from 1 7: 6

Enter a number from 1 7: 10

Output: Saturday

Output: Invalid Input

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

Enter a number: -19

Output: positive

Output: Negative

4. Write a program that takes input of a number as month (1-12) then prints month accordingly
Example1:

Example2:

Enter a number from 1 12: 9

Enter a number from 1 12: 23

Output: September

Output: Invalid Input

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 first number: 6

Enter first number: 5

Enter first number: 8

Enter Second number: 3

Enter Second number: 2

Enter Second number: 2

Enter Operator: +

Enter Operator: *

Enter Operator: >

Output: 9

Output: 10

Output: Invalid Operator

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

Output: Upper case Letter

Output: Not Capital Letter Output: Not Capital Letter

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

Output: Lower case Letter

Output: Not small Letter

Output: Not Small Letter

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

Output: Invalid input

Output: Invalid input

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

Output: Invalid input

Output: Invalid input

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------28 | P a g e

Lab 03:
Repetition Control Structure (Counter Controlled For and While Loop)

Objectives:

To understand repetition using for and while loop

To understand the counter controlled for and while loop

Prerequisites:

Study chapter 4, Control Structures II (Repetition) from book, C++ Programming:


From problem analysis to problem design by D.S. Malik

Must be able to explain which of the loops are valid and which are invalid with
reason.

Must have complete understating of selection control structure.

Resources:
Personal computer installed with the latest version of Code::Blocks.

Introduction and Theory:


Loop structures can be used to do repetitive calculations. Though human beings can do
calculation or processing or repetitive nature by hand, it is much slower and tedious for the
human being. Good and solid logic of loop structures can be used to solve such problems in a
very efficient way.

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:

Enter starting Number: 4

Enter starting Number: 1

Enter ending Number: 6

Enter ending Number: 2

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:

Sum of even Numbers = 12

Sum of even Numbers = 14

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:

Total even Numbers = 4

Total even Numbers = 3

Total odd Numbers = 4

Total Odd Numbers = 5

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:

Numbers between range 35 50 : 3

Numbers between range 35 50 : 4

Numbers out of range = 3

Numbers out of range = 2

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:

Enter a 4 digit Number: 5401

Enter a 4 digit Number: 6225

Output:

Output:

Sum of the digits = 10

Sum of the digits = 15

Lab Outcomes:
After performing this lab, the students will be able to:

Explain the basics of for and while loops

Apply the syntaxes of for and while loop structure.

Design programs using for and whileloop structure.

Solve hard problems of repetitive nature usingforand do-while loop structure.

Post Lab Tasks:


1. Write a program to print the following pattern on the screen. Take input of number of
rows from user.
*
**
***
****
*****
******

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

$$$
$$
$

%
%
%%%%%%%%%%

3. Write the programs to print the following patterns.


2
4
6
8

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------35 | P a g e

Lab 04:
Arrays
Objectives:

To understand arrays

To understand Declaration, Initialization, and Accessing elements of 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.

Introduction and Theory:


C++ provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

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

type arrayName [ arraySize ];

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:

Accessing Array Elements:


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:
double salary = balance[9];

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

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

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:

Explain the basics of arrays

Apply the syntaxes of array initialization, declaration.

Design programs using arrays and loops plus conditions.

Post Lab Tasks:


Program#1:
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 Right)
Output
Enter numbers in the array: 47 45 37 96 28 24 82 14 70 38
After shifting right array is : 38 47 45 37 96 28 24 82 14 70

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

9. To what extent did you learn on the material in the


lab?
10. Are you able to apply knowledge gained in the lab to
similar problems?
11. Are you able to analyze and interpret programs given
in the lab?

12. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

13. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
14. Were you able to function as a group in the lab?

15. Were you able to interpret effectively the procedures


and questions asked in the lab?
16. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

43 | P a g e

Lab 05:
Strings
Objectives:

To understand idea of Strings

To understand Declaration, Initialization, and Accessing strings

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.

Introduction and Theory:


C++ provides following two types of string representations:

The C-style character string.

The string class type introduced with Standard C++.

C-Style Character String:


The C-style character string originated within the C language and continues to be supported within
C++. This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello."

44 | P a g e

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows:
char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

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>

using namespace std;

int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

45 | P a g e

Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings:


S.N.

Function & Purpose

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.

Following example makes use of few of the above-mentioned functions:


#include <iostream>
#include <cstring>

using namespace std;

int main ()
{
char str1[10] = "Hello";

46 | P a g e

char str2[10] = "World";


char str3[10];
int

len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

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:

Explain the basics of strings

Apply the syntaxes of string initialization, declaration.

Design programs using strings and loops plus conditions.

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

17. To what extent did you learn on the material in the


lab?
18. Are you able to apply knowledge gained in the lab to
similar problems?
19. Are you able to analyze and interpret programs given
in the lab?

20. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

21. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
22. Were you able to function as a group in the lab?

23. Were you able to interpret effectively the procedures


and questions asked in the lab?
24. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

50 | P a g e

Lab 06:
2D arrays
Objectives:

To understand idea of multi dimensional arrays

To understand Declaration, Initialization, and Accessing 2d arrays

To get familiar with matrix operations

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.

Introduction and Theory:


C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];

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.

Initializing Two-Dimensional Arrays:


Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following
is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} ,

/*

initializers for row indexed by 0 */

{4, 5, 6, 7} ,

/*

initializers for row indexed by 1 */

{8, 9, 10, 11}

/*

initializers for row indexed by 2 */

};

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};

Accessing Two-Dimensional Array Elements:


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example:
int val = a[2][3];

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}};

// output each array element's value


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

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

Product of Array A and B is


30

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:

Explain the basics of multi dimensional arrays

Apply the operations of matrices.

Design programs using 2d arrays and nested loops.

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

25. To what extent did you learn on the material in the


lab?
26. Are you able to apply knowledge gained in the lab to
similar problems?
27. Are you able to analyze and interpret programs given
in the lab?

28. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

29. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
30. Were you able to function as a group in the lab?

31. Were you able to interpret effectively the procedures


and questions asked in the lab?
32. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

57 | P a g e

Lab 07:
Functions (Value Returning Functions)
Objectives:

To understand idea of functions

To understand Modular approach

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.

Introduction and Theory:


A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one memory
location to another location and many more functions.

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.

Parameters: A parameter is like a placeholder. When a function is invoked, you pass a


value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

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

int max(int num1, int num2)


{
// local variable declaration
int result;

59 | P a g e

if (num1 > num2)


result = num1;
else
result = num2;

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:

Explain the basics of functions

Apply the syntaxes of functions with some value being returned from the function.

Design programs using modular approach.

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

33. To what extent did you learn on the material in the


lab?
34. Are you able to apply knowledge gained in the lab to
similar problems?
35. Are you able to analyze and interpret programs given
in the lab?

36. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

37. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
38. Were you able to function as a group in the lab?

39. Were you able to interpret effectively the procedures


and questions asked in the lab?
40. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

62 | P a g e

Lab 08:
Functions (Void Functions)
Objectives:

To understand idea of void function

To understand defining, declaring and calling void functions

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.

Introduction and Theory:


Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );

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;

// calling a function to get max value.


ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;
}

64 | P a g e

// function returning the max between two numbers


int max(int num1, int num2)
{
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

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

This method copies the actual value of an argument


into the formal parameter of the function. In this case,
changes made to the parameter inside the function
have no effect on the argument.

65 | P a g e

Call by pointer

Call by reference

This method copies the address of an argument into


the formal parameter. Inside the function, the address
is used to access the actual argument used in the
call. This means that changes made to the parameter
affect the argument.

This method copies the reference of an argument into


the formal parameter. Inside the function, the
reference is used to access the actual argument used
in the call. This means that changes made to the
parameter affect the argument.

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.

Default Values for Parameters:


When you define a function, you can specify a default value for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the
function definition. If a value for that parameter is not passed when the function is called, the default
given value is used, but if a value is specified, this default value is ignored and the passed value is
used instead. Consider the following example:
#include <iostream>
using namespace std;

int sum(int a, int b=20)


{
int result;

result = a + b;

return (result);
}

66 | P a g e

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

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

Largest number is 90 and second largest is 73

Lab Outcomes:
After performing this lab, the students will be able to:

Explain the usage of void functions

Using total Modular approach in your program.

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

71 | P a g e

Lab 09:
Functions (Passing Arrays to Functions)
Objectives:

To understand idea of functions and arrays

To understand concept of arrays and functions combinely

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.

Introduction and Theory:


Arrays can be passed to a function as an argument. Consider this example to pass one dimensional array to a function:

Example 1: Passing One-dimensional Array to a Function


C++ Program to display marks of 5 students by passing one -dimensional array to a
function.
#include <iostream>
using namespace std;
void display(int marks[5]);
int main() {
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
void display(int m[5]) {
cout<<"Displaying marks: "<<endl;
for (int i = 0; i <5; ++i) {
cout<<"Student "<<i+1<<": "<<m[i]<<endl;

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

Passing Multidimensional Array to a Function


Multidimensional array can be passed in similar way as one -dimensional array. Consider
this example to pass two dimensional array to a function:

Example 2: Passing Multidimensional Array to a Function


C++ Program to display the elements of two dimensional array by passing it to a
function.

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

neighbours of A[0][0] are 2, 4, and 5


B[0][0] = 2 +4 + 5 =11
neighbours of A[1][1] are 1, 2, 3, 4, 6, 7, 8, 9
B[1][1] = 1 +2 + 3+ 4+ 6+ 7+ 8+ 9 = 40

Lab Outcomes:
After performing this lab, the students will be able to:

Explain the usage of arrays as parameters to functions

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

77 | P a g e

Lab10:
Recursion
Objectives:

To understand idea of function call in itself

To understand the beauty of Recursively calling functions

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.

Introduction and Theory:


Recursion
Simply put, recursion is when a function calls itself. That is, in the course of the function definition there
is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing
its tail. It can never catch it. So too it seems our function will never finish. This might be true is some
cases, but in practice we can check to see if a certain condition is true and in that case exit (return from)
our function. The case in which we end our recursion is called a base case . Additionally, just as in a loop,
we must change some value and incremently advance closer to our base case.
Consider this function.
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout <<counter<<endl;
78 | P a g e

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:

Explain the basics of Recursion

Apply the syntaxes of Calling a function inside the same function finitly.

Design programs using recursion

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

41. To what extent did you learn on the material in the


lab?
42. Are you able to apply knowledge gained in the lab to
similar problems?
43. Are you able to analyze and interpret programs given
in the lab?

44. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

45. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
46. Were you able to function as a group in the lab?

47. Were you able to interpret effectively the procedures


and questions asked in the lab?
48. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

82 | P a g e

Lab 11:
Pointers
Objectives:

To understand idea of Pointers

To understand Declaration, Initialization, and Memory Allocation through pointers

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.

Introduction and Theory:


In earlier chapters, variables have been explained as locations in the computer's memory which can be
accessed by their identifier (their name). This way, the program does not need to care about the
physical address of the data in memory; it simply uses the identifier whenever it needs to refer to the
variable.
For a C++ program, the memory of a computer is like a succession of memory cells, each one byte in
size, and each with a unique address. These single-byte memory cells are ordered in a way that allows
data representations larger than one byte to occupy memory cells that have consecutive addresses.
This way, each cell can be easily located in the memory by means of its unique address. For example, the
memory cell with the address 1776 always follows immediately after the cell with address 1775 and
precedes the one with 1777, and is exactly one thousand cells after 776 and exactly one thousand cells
before 2776.
When a variable is declared, the memory needed to store its value is assigned a specific location in
memory (its memory address). Generally, C++ programs do not actively decide the exact memory
83 | P a g e

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.

Address-of operator (&)


The address of a variable can be obtained by preceding the name of a variable with an ampersand sign
(&), known asaddress-of operator. For example:
foo = &myvar;

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.

Dereference operator (*)


As just seen, a variable which stores the address of another variable is called a pointer. Pointers are said
to "point to" the variable whose address they store.
An interesting property of pointers is that they can be used to access the variable they point to directly.
This is done by preceding the pointer name with the dereference operator (*). The operator itself can be
read as "value pointed to by".
Therefore, following with the values of the previous example, the following statement:
baz = *foo;

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;

// baz equal to foo (1776)


// baz equal to value pointed to by foo (25)

The reference and dereference operators are thus complementary:

& 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:

Explain the basics of pointers

Apply the syntaxes of pointer initialization, declaration.

Design programs using pointers

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

49. To what extent did you learn on the material in the


lab?
50. Are you able to apply knowledge gained in the lab to
similar problems?
51. Are you able to analyze and interpret programs given
in the lab?

52. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

53. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
54. Were you able to function as a group in the lab?

55. Were you able to interpret effectively the procedures


and questions asked in the lab?
56. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

91 | P a g e

Lab 12:
Passing Pointers to Functions
Objectives:

To understand idea of Pointers and function

To understand passing pointers to functions

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.

Introduction and Theory:


C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a
pointer type.
Following a simple example where we pass an unsigned long pointer to a function and change the
value inside the function which reflects back in the calling function:
#include <iostream>
#include <ctime>

using namespace std;


void getSeconds(unsigned long *par);

int main ()
{

92 | P a g e

unsigned long sec;

getSeconds( &sec );

// print the actual value


cout << "Number of seconds :" << sec << endl;

return 0;
}

void getSeconds(unsigned long *par)


{
// get the current number of seconds
*par = time( NULL );
return;
}

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;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;

return 0;
}

double getAverage(int *arr, int size)


{
int

i, sum = 0;

double avg;

for (i = 0; i < size; ++i)


{
sum += arr[i];
}

avg = double(sum) / size;

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:

Be able to understand function and pointers

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

97 | P a g e

Lab 13:
Dynamic Memory Allocation
Objectives:

To understand idea of Dynamically allocating memory

To understand Declaration, Initialization, and Accessing memory at runtime

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.

Introduction and Theory:


C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter
as a pointer type.
Dynamic memory
In the programs seen in previous chapters, all memory needs were determined before program
execution by defining the variables needed. But there may be cases where the memory needs of a
program can only be determined during runtime. For example, when the memory needed
depends on user input. On these cases, programs need to dynamically allocate memory, for
which the C++ language integrates the operators new and delete.

Operators new and new[]

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

Enter columns for matrix2:3


Enter values in matrix1:
11 5 21
19 2 62
8 9 7
Multiplication of matrices is not possible

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:

Explain the basics of runtime memory allocation

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

9. To what extent did you learn on the material in the


lab?
10. Are you able to apply knowledge gained in the lab to
similar problems?
11. Are you able to analyze and interpret programs given
in the lab?

12. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

13. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
14. Were you able to function as a group in the lab?

15. Were you able to interpret effectively the procedures


and questions asked in the lab?
16. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

102 | P a g e

Lab 14:
Structures
Objectives:

To understand idea of Structures

To understand Declaration, Initialization, and Accessing structures Members

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.

Introduction and Theory:


Structure is the collection of variables of different types under a single name for better
visualisation of problem. Arrays is also collection of data but arrays can hold data of only one
type whereas structure can hold data of one or more types.

How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier(name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:
struct person {
char name[50];
int age;

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.

How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as:
person bill;
Here, a structure variable bill is defined which is of type structure person. When structure
variable is defined, then only the required memory is allocated by the compiler. Considering you
have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of int is 4 bytes
and memory ofchar is 1 byte. Hence, 58 bytes of memory is allocated for structure
variable bill.

How to access members of a structure?


The members of structure variable is accessed using dot operator. Suppose, you want to
access ageof structure variable bill and assign it 50 to it. You can perform this task by using
following code below:
bill.age = 50;

Example 1: C++ Structure


C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct person {
char name[50];
int age;

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

<< "\nDisplaying Information." << endl;


<< "Name: " << p1.name << endl;
<<"Age: " << p1.age << endl;
<< "Salary: " << p1.salary;

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:

Explain the basics of structures

Apply the syntaxes of user defined data types.

Design programs using any specific entities having specific attributes..

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

108 | P a g e

Lab 15:
Files
Objectives:

To understand idea of files

To understand the storage of data permanently on hard drive

Prerequisites:

Study Notes given on , Filing

Resources:
Personal computer installed with the latest version of Code::Blocks.

Introduction and Theory:


So far, we have been using the iostream standard library, which provides cin and cout methods
for reading from standard input and writing to standard output respectively.

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.

void open(const char *filename, ios::openmode mode);


110 | P a g e

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

Append mode. All output to that file to be appended to the end.

ios::ate

Open a file for output and move the read/write control to the end of the file.

ios::in

Open a file for reading.

ios::out

Open a file for writing.

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];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


114 | P a g e

cin >> data;


cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

115 | P a g e

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

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

Writing to the file


Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

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:

Explain the basics of files

Apply the syntaxes of wrinting and stroring data into a file

Design programs using permanently storage of data

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

119 | P a g e

Lab 16:
Files
Objectives:

To understand idea of Reding, writing and accessing files randomly

To understand writing complete information to files

Prerequisites:

Study notes provided for files

Resources:
Personal computer installed with the latest version of Code::Blocks.

Introduction and Theory:


File Position Pointers:
Both istream and ostream provide member functions for repositioning the file-position pointer.
These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified
to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning
relative to the beginning of a stream, ios::cur for positioning relative to the current position in a
stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of
bytes from the file's starting location. Some examples of positioning the "get" file-position
pointer are:
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
120 | P a g e

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

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:

Explain the advanced concepts of files

Accessing the file data randomly.

Design programs using advanced concepts of files.

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

1. To what extent did you learn on the material in the


lab?
2. Are you able to apply knowledge gained in the lab to
similar problems?
3. Are you able to analyze and interpret programs given
in the lab?

4. Are you able to identify, formulate and solve


electrical engineering problems based on the
knowledge acquired in the lab.?

5. Can you design an application/ software to fulfill


certain specifications based on the knowledge
acquired in the lab?
6. Were you able to function as a group in the lab?

7. Were you able to interpret effectively the procedures


and questions asked in the lab?
8. Comment whether your work in the lab has an
impact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

123 | P a g e

Das könnte Ihnen auch gefallen