Date post: | 02-Mar-2018 |
Category: |
Documents |
Upload: | muhammad-zain-yousaf |
View: | 216 times |
Download: | 0 times |
of 123
7/26/2019 CP Manuals Updated3
1/123
1 | P a g e
COMPUTER PROGRAMMING (CS1112)
LABMANUAL
Revised Date
February 2015
DEPARTMENT OF ELECTRICAL ENGINEERING
THE UNIVERSITY OF LAHORE
7/26/2019 CP Manuals Updated3
2/123
2 | P a g e
Revision History
Revised Date Revised By Revised Topics
February 05, 2015 Sadaf Inam
1. Lab Manual # 1 is added to
introduce the software
Code::Blocks instead of
Turbo along with revision of
previous concepts.
2. Theory is added with
Manuals to assist student in
understanding concepts
3. Overall the format of everymanual is changed andconceptual programs areadded at the end of each lab
September, 2014 Sadaf Inam Code::Blocks installation
and project creation manual
was added.
February, 2014 Sadaf Inam Some programs were added
from book.
7/26/2019 CP Manuals Updated3
3/123
3 | P a g e
CERTIFICATE OF APPROVAL
It is certified that the lab manual titled Computer Programming, in scope and in quality, coversthe objectives and topics defined in the course outline.
Remarks by Mentor: ----------------------------------------------Nabeel Shehzad
Assistant Professor
Department of Electrical EngineeringThe University of Lahore
Remarks by HOD: -------------------------------------------------
Dr. Asrar ul Haq SheikhProfessor
Department of Electrical EngineeringThe University of Lahore
7/26/2019 CP Manuals Updated3
4/123
4 | P a g e
Contents
Lab 01Part 01: ......................................................................................................................................... 6
Introduction to Programming Using Code::Blocks .............................................................................. 6
Lab 01Part 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: ...................................................................................................................................... 36Initializing 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
7/26/2019 CP Manuals Updated3
5/123
5 | P a g e
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
Opening a File: ............................................................................................................................................ 110
Closing a File .............................................................................................................................................. 112
Writing to a File: ............................................................................................................................................ 113
Reading from a File: ...................................................................................................................................... 113
Read & Write Example: ................................................................................................................................. 113
Lab 16:...................................................................................................................................................... 120
Files ...................................................................................................................................................... 120
7/26/2019 CP Manuals Updated3
6/123
6 | P a g e
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.
7/26/2019 CP Manuals Updated3
7/123
7 | P a g e
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 aPreprocessor.
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
For example, the following statement includes the header file iostream in a C++ program:
#include
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/26/2019 CP Manuals Updated3
8/123
8 | P a g e
Create a C++ project in Code::Blocks:
1. Start Page:
2. Create a new Project:
For creating a new project, select the Filebutton from menu bar then select Project.
7/26/2019 CP Manuals Updated3
9/123
9 | P a g e
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.
7/26/2019 CP Manuals Updated3
10/123
7/26/2019 CP Manuals Updated3
11/123
11 | 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.
7/26/2019 CP Manuals Updated3
12/123
12 | 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.
7/26/2019 CP Manuals Updated3
13/123
13 | P a g e
After pressing the Finish button, a new window will appear like below:
7/26/2019 CP Manuals Updated3
14/123
14 | 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.
7/26/2019 CP Manuals Updated3
15/123
15 | 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 theBuild button from the menu bar and then selectBuild and Run. Short key for this is F9.
7/26/2019 CP Manuals Updated3
16/123
16 | 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.
7/26/2019 CP Manuals Updated3
17/123
17 | 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 revisesimple conditions structure
To understand theNested 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;
7/26/2019 CP Manuals Updated3
18/123
18 | P a g e
}
I fis 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.
Elsepart is combined with theifpart.Elsepart 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;elsestatement-block;
}else
{if ( condition )
statement-block;else
statement-block;}
Innerifwill execute if the outer ifis executed otherwise the elsepart will execute. In the nested
elsestructure if the innerifis false then its elsepart will execute.
7/26/2019 CP Manuals Updated3
19/123
19 | 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:
Enter a number: 49
Output: Odd Number
Example2:
Enter a number: 22
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:
Enter a number: 12
Output: Positive Number
Example2:
Enter a number: -8
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:
Enter first number: 12
Enter second number: 10
Output: First Number is
greater
Example1:
Enter first number: 3
Enter second number: 10
Output: Second Number
is greater
Example2:
Enter first number: 8
Enter second number: 8
Output: Both are equal
4. Write a program that takes input of number from user then prints whether the number is
divisible by 7 or not.
Example1:
Enter a number: 49
Number is divisible by 7
Example2:
Enter a number: 22
Number is not divisible by 7
7/26/2019 CP Manuals Updated3
20/123
20 | 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:
Enter a number: 53235
Numerical Palindrome
Example2:
Enter a number: 26126
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:
Enter a number: 6
It is divisible by 2 and 3
both.
Example2:
Enter a number: 8
It is divisible by 2 only
Example3:
Enter a number: 5
It is not divisible by 2
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:
Enter the character: b
Output: B
Example2:
Enter the character: ?
Output: ?
Example3:
Enter the character: 9
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:
Enter 5 numbers:
3 7 9 17 99
Output:
Numbers are in ascending
Example2:
Enter 5 numbers:
32 15 11 9 1
Output:
Numbers are in descending
Example3:
Enter 5 numbers:
2 6 1 72 8
Output:
Numbers are in unordered
7/26/2019 CP Manuals Updated3
21/123
21 | 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:
Enter the value of x: 5
Enter the value of y: 0
Output: point is on X-axis
Example2:
Enter the value of x: -3
Enter the value of y: 4
Output: point is in 2nd
quadrant
Example3:
Enter the value of x: 0
Enter the value of y: 0
Output: point is on origin
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:
Enter first number: 9
Enter second Number: 4
Output:
Both are not multiple of eachother
Example2:
Enter first number: 6
Enter second Number: 3
Output:
Second number is a multipleof first number
Example3:
Enter first number: 9
Enter second Number: 81
Output:
First number is a multiple ofsecond 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.
7/26/2019 CP Manuals Updated3
22/123
22 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
1. To what extent did you learn on the material in thelab?
2. Are you able to apply knowledge gained in the lab tosimilar problems?
3. Are you able to analyze and interpret programs given
in the lab?
4. Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
5. Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
6. Were you able to function as a group in the lab?
7. Were you able to interpret effectively the proceduresand questions asked in the lab?
8. Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
23/123
23 | 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 underswitch
To understand the concept of breakin 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/elsestructure.
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/elsestructure. General syntax of switch structure is:
switch ( expression){
case value1:statementsbreak;
7/26/2019 CP Manuals Updated3
24/123
24 | P a g e
case value2:statementsbreak;
case valueN:
statementsbreak;
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.
7/26/2019 CP Manuals Updated3
25/123
25 | 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:
Enter a number from 1 7: 6
Output: Saturday
Example2:
Enter a number from 1 7: 10
Output: Invalid Input
2. Write a program that takes input of a number then prints whether is it even or odd.
Example1:
Enter a number: 6
Output: Even
Example2:
Enter a number: 9
Output: Odd
3. Write a program that takes input of a number then prints whether is it negative or positive.
Example1:
Enter a number: 16
Output: positive
Example2:
Enter a number: -19
Output: Negative
4. Write a program that takes input of a number as month (1-12) then prints month accordingly
Example1:
Enter a number from 1 12: 9
Output: September
Example2:
Enter a number from 1 12: 23
Output: Invalid Input
5. Write a program that takes input of an alphabet then prints whether it is a vowel or
consonant.
Example1:
Enter an alphabet: k
Output: Consonant
Example2:
Enter an alphabet: A
Output: Vowel
7/26/2019 CP Manuals Updated3
26/123
26 | 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:
Enter first number: 6
Enter Second number: 3
Enter Operator: +
Output: 9
Example2:
Enter first number: 5
Enter Second number: 2
Enter Operator: *
Output: 10
Example3:
Enter first number: 8
Enter Second number: 2
Enter Operator: >
Output: Invalid Operator
7. Write a program that takes input of an alphabet then prints whether it is a capital alphabet or
not.
Example1:
Enter an alphabet: M
Output: Upper case Letter
Example2:
Enter an alphabet: a
Output: Not Capital Letter
Example3:
Enter an alphabet: 9
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:
Enter an alphabet: m
Output: Lower case Letter
Example2:
Enter an alphabet: B
Output: Not small Letter
Example3:
Enter an alphabet: 9
Output: Not Small Letter
9. Write a program that takes input of a capital alphabet then prints it in small alphabet.
Example1:
Enter an alphabet: A
Output: a
Example2:
Enter an alphabet: h
Output: Invalid input
Example3:
Enter an alphabet: 0
Output: Invalid input
10.Write a program that takes input of a small alphabet then prints it in capital alphabet.
Example1:
Enter an alphabet: b
Output: B
Example2:
Enter an alphabet: H
Output: Invalid input
Example3:
Enter an alphabet: 19
Output: Invalid input
7/26/2019 CP Manuals Updated3
27/123
27 | 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 theswitch structurein the program.
7/26/2019 CP Manuals Updated3
28/123
28 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
1. To what extent did you learn on the material in thelab?
2. Are you able to apply knowledge gained in the lab tosimilar problems?
3. Are you able to analyze and interpret programs given
in the lab?
4. Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
5. Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
6. Were you able to function as a group in the lab?
7. Were you able to interpret effectively the proceduresand questions asked in the lab?
8. Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
29/123
29 | P a g e
Lab 03:Repetition Control Structure (Counter -
Controlled For and While Loop)
Objectives:
To understand repetition usingfor and while loop
To understand the counter controlledfor 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.
7/26/2019 CP Manuals Updated3
30/123
30 | 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 offor 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 3550.
2. Write a program to print the squares and cubes of all the numbers from 15.
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.
7/26/2019 CP Manuals Updated3
31/123
31 | P a g e
Example1:
Enter starting Number: 4
Enter ending Number: 6
Output:
16 64
25 125
36 216
Example2:
Enter starting Number: 1
Enter ending Number: 2
Output:
1 1
4 8
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:
Enter 8 Numbers: 2 4 6 0 1 3 1 5
Output:
Sum of even Numbers = 12
Example2:
Enter 8 Numbers: 1 4 2 0 1 8 1 5
Output:
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:
Enter 8 Numbers: 2 4 6 0 1 3 1 5Output:
Total even Numbers = 4
Total odd Numbers = 4
Example2:
Enter 8 Numbers: 1 4 2 0 1 8 1 5Output:
Total even Numbers = 3
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:
Enter 6 Numbers: 24 61 50 11 37 41
Output:
Numbers between range 3550 : 3
Numbers out of range = 3
Example2:
Enter 6 Numbers: 44 61 50 11 37 41
Output:
Numbers between range 3550 : 4
Numbers out of range = 2
7. Write a program to print the table of a number entered by the user from 15.
7/26/2019 CP Manuals Updated3
32/123
32 | P a g e
Example1:
Enter a Number: 4
Output:
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
Example2:
Enter a Number: 6
Output:
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
8. Write a program to take input of a number from user and find its factorial by increment
method.
Example1:
Enter a Number: 5
Output:
Factorial = 120
Example2:
Enter a Number: 3
Output:
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:
Enter a Number: 5
Output:
Prime Number
Example2:
Enter a Number: 60
Output:
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:
Enter a Number: 5
Enter power: 3
Output:
Example2:
Enter a Number: 2
Enter power: 5
Output:
7/26/2019 CP Manuals Updated3
33/123
33 | 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:
Enter a 4 digit Number: 5401
Output:
Sum of the digits = 10
Example2:
Enter a 4 digit Number: 6225
Output:
Sum of the digits = 15
Lab Outcomes:
After performing this lab, the students will be able to:
Explain the basics offor and whileloops
Apply the syntaxes offor and whileloop structure.
Design programs usingfor and whileloop structure.
Solve hard problems of repetitive nature usingforand do-whileloop 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
1 2
1 2 3
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.
$$$$$$$$$$$$$$$
%%%%%%%%%%
% %
7/26/2019 CP Manuals Updated3
34/123
34 | P a g e
$$$$$$
% %
% %%%%%%%%%%%
3. Write the programs to print the following patterns.
2 4 6 8 104 6 8 10 126 8 10 12 148 10 12 14 16
****
************
*********
H I J K L MI J K L MJ K L MK L M
L MM
10 0 0 00 1 0 0 00 0 1 0 0
0 0 0 1 00 0 0 0 1
** *
* * ** * * *
* * * * *
1 3 5 7 9 13
1 3 5 7 9
1 3 5 7
1 3 5
1 3
1
7/26/2019 CP Manuals Updated3
35/123
35 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
1. To what extent did you learn on the material in thelab?
2. Are you able to apply knowledge gained in the lab tosimilar problems?
3. Are you able to analyze and interpret programs given
in the lab?
4. Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
5. Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
6. Were you able to function as a group in the lab?
7. Were you able to interpret effectively the proceduresand questions asked in the lab?
8. Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
36/123
36 | 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 frombook, 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:
7/26/2019 CP Manuals Updated3
37/123
37 | P a g e
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySizemust be an integer constant greater than
zero and typecan 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];
7/26/2019 CP Manuals Updated3
38/123
38 | 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
using namespace std;
#include
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
7/26/2019 CP Manuals Updated3
39/123
39 | P a g e
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Lab Assignments:Program#1:
Write a program that declares an array abc of 10 elements of type int. Initialize each element ofarray 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. Thenfind 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:
7/26/2019 CP Manuals Updated3
40/123
40 | 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.9Values 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 Ais 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 54 61 78 29 30 31 6 52Enter values in 2nd array: 21 4 54 61 78 29 30 31 6 52
Both Arrays are equal
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 anotherarray 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 34Values 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 itis in ascending order, descending order or unordered.OutputEnter numbers in the array 97 45 37 35 28 24 20 14 10 8
Array is in Descending Order
7/26/2019 CP Manuals Updated3
41/123
7/26/2019 CP Manuals Updated3
42/123
42 | 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 isonly 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.OutputEnter 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 ofits input value. (Histogram)OutputEnter numbers in the array: 7 5 0 9 12 4 18 7 13 5
7 *******5 *****
012 ************
4 ****
18 ******************
7 *******13 *************
5 *****
7/26/2019 CP Manuals Updated3
43/123
43 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
9. To what extent did you learn on the material in thelab?
10.Are you able to apply knowledge gained in the lab tosimilar problems?
11.Are you able to analyze and interpret programs given
in the lab?
12.Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
13.Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
14.Were you able to function as a group in the lab?
15.Were you able to interpret effectively the proceduresand questions asked in the lab?
16.Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
44/123
44 | 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 bya nullcharacter '\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."
7/26/2019 CP Manuals Updated3
45/123
45 | P a g e
chargreeting[6]={'H','e','l','l','o','\0'};
If you follow the rule of array initialization, then you can write the above statement as follows:
chargreeting[]="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
usingnamespacestd;
intmain ()
{
chargreeting[6]={'H','e','l','l','o','\0'};
cout
7/26/2019 CP Manuals Updated3
46/123
46 | P a g e
Greetingmessage:Hello
C++ supports a wide range of functions that manipulate null-terminated strings:
S.N. Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 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
#include
usingnamespacestd;
intmain ()
{
charstr1[10]="Hello";
7/26/2019 CP Manuals Updated3
47/123
47 | P a g e
charstr2[10]="World";
charstr3[10];
int len ;
// copy str1 into str3
strcpy(str3,str1);
cout
7/26/2019 CP Manuals Updated3
48/123
7/26/2019 CP Manuals Updated3
49/123
49 | P a g e
Write a program that takes a string and a character from user as input then remove that characterfrom the string and print the final string.OutputEnter the string:He that lives upon hope will die fasting
Enter the character you want to remove: iFinal 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.OutputEnter 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 ofstrings
Apply the syntaxes ofstring initialization, declaration.
Design programs usingstrings and loops plus conditions.
7/26/2019 CP Manuals Updated3
50/123
50 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
17.To what extent did you learn on the material in thelab?
18.Are you able to apply knowledge gained in the lab tosimilar problems?
19.Are you able to analyze and interpret programs given
in the lab?
20.Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
21.Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
22.Were you able to function as a group in the lab?
23.Were you able to interpret effectively the proceduresand questions asked in the lab?
24.Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
51/123
51 | 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:
intthreedim[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:
7/26/2019 CP Manuals Updated3
52/123
52 | P a g e
type arrayName [x ][y ];
Where typecan be any valid C++ data type and arrayNamewill 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 form a[ 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.
inta[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:
inta[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:
intval =a[2][3];
7/26/2019 CP Manuals Updated3
53/123
53 | 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
usingnamespacestd;
intmain ()
{
// an array with 5 rows and 2 columns.
inta[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
// output each array element's value
for(inti =0;i
7/26/2019 CP Manuals Updated3
54/123
54 | 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 foreach element. Output would be as follows.
1 2 3 4 5 6123456
Program#2:A program that generates the following output using a 2-D array. (Use nested loops to storevalues in array)
Program#3:A program that reads two 2-d arrays as 3*3 matrices then calculates and stores their product intoanother 2-d array of size 3*3.Array A
Array B
Product of Array A and B is
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
6 7 8 9 10 11
7 8 9 10 11 12
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
3 5 6
1 9 2
12 10 7
4 6 7
2 3 5
3 8 6
30 81 82
28 49 64
89 158 176
7/26/2019 CP Manuals Updated3
55/123
55 | 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.
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 a33a23 a32)(a12(a21 a33a23 a31) +a13(a21 a32a22 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.
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 elementdirectly above it (if any). A Pascal triangle of size 7 is as follows.
Program#8:A program that takes an array of 8 strings to store names in it then display only those names thatstarts with letter A.
3 1 12
1 9 1012 10 7
+1 +1 +1 +1 +1 0
+1 +1 +1 +1 0 -1
+1 +1 +1 0 -1 -1
+1 +1 0 -1 -1 -1
+1 0 -1 -1 -1 -1
0 -1 -1 -1 -1 -1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 11 5 10 10 5 1
1 6 15 20 15 6 1
7/26/2019 CP Manuals Updated3
56/123
7/26/2019 CP Manuals Updated3
57/123
57 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
25.To what extent did you learn on the material in thelab?
26.Are you able to apply knowledge gained in the lab tosimilar problems?
27.Are you able to analyze and interpret programs given
in the lab?
28.Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
29.Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
30.Were you able to function as a group in the lab?
31.Were you able to interpret effectively the proceduresand questions asked in the lab?
32.Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
58/123
58 | 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 definitionprovides 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.
7/26/2019 CP Manuals Updated3
59/123
59 | 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_typeis the data type of the valuethe 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
intmax(intnum1,intnum2)
{
// local variable declaration
intresult;
7/26/2019 CP Manuals Updated3
60/123
60 | P a g e
if(num1 >num2)
result =num1;
else
result =num2;
returnresult;
}
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 orodd. Pass an integer value as an argument to a function. The function returns 1 if number is Evenand 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 avowel and otherwise returns 0.
Program#5:
Write a function lcm() that takes two parameters as input then returns their least commonmultiple to the main.
7/26/2019 CP Manuals Updated3
61/123
61 | P a g e
Program#6:
Write a function reverse() that takes an integer input as argument and returns its reverse. Forexample 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 commondivisor to the main.
Program#8:
Write a function perfect() that takes input of an integer variable then returns 1 if it is perfect, 0otherwise. (A number is perfect if sum of factors including 1 but not the number itself is equal tothe 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 offunctions
Apply the syntaxes offunctions with some value being returned from the function.
Design programs using modular approach.
7/26/2019 CP Manuals Updated3
62/123
62 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
33.To what extent did you learn on the material in thelab?
34.Are you able to apply knowledge gained in the lab tosimilar problems?
35.Are you able to analyze and interpret programs given
in the lab?
36.Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
37.Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
38.Were you able to function as a group in the lab?
39.Were you able to interpret effectively the proceduresand questions asked in the lab?
40.Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
63/123
63 | 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:
intmax(intnum1,intnum2);
Parameter names are not importan in function declaration only their type is required, so following is
also valid declaration:
intmax(int,int);
7/26/2019 CP Manuals Updated3
64/123
7/26/2019 CP Manuals Updated3
65/123
65 | P a g e
// function returning the max between two numbers
intmax(intnum1,intnum2)
{
// local variable declaration
intresult;
if(num1 >num2)
result =num1;
else
result =num2;
returnresult;
}
I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result:
Maxvalue 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 Description
Call by valueThis 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.
http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_value.htmhttp://www.tutorialspoint.com/cplusplus/cpp_function_call_by_value.htmhttp://www.tutorialspoint.com/cplusplus/cpp_function_call_by_value.htm7/26/2019 CP Manuals Updated3
66/123
66 | P a g e
Call by pointerThis 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.
Call by referenceThis 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
usingnamespacestd;
intsum(inta,intb=20)
{
intresult;
result =a +b;
return(result);
}
http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_pointer.htmhttp://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htmhttp://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htmhttp://www.tutorialspoint.com/cplusplus/cpp_function_call_by_pointer.htm7/26/2019 CP Manuals Updated3
67/123
67 | P a g e
intmain ()
{
// local variable declaration:
inta =100;
intb =200;
intresult;
// calling a function to add the values.
result =sum(a,b);
cout
7/26/2019 CP Manuals Updated3
68/123
68 | P a g e
Program#2:
Write a function that takes two integer parameters as input and prints all tables between these
two numbers.
OutputEnter 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 numbersbetween them.OutputEnter first number 10
Enter second number 40All 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 10Enter second number 40
Enter third number 89
Before function call x=10, y=40, z=89After function call x=89, y=10, z=40
7/26/2019 CP Manuals Updated3
69/123
69 | P a g e
Program#5:
Write a function triangle() that takes an integer input as argument and prints its triangle. Forexample if user enters 6 the function should print the following triangle shape. (triangle wouldalways start with letter Z).Output
Enter a number: 6Z Y X W V U
Z Y X W V
Z Y X W
Z Y X
Z Y
Z
Program#6:Write a function triangle() that takes an integer input as argument and prints its triangle. Forexample if user enters 9 the function should print the following triangle shape. (Make sure thatthe input integer is odd if user enters an even number the input should be entered again)OutputEnter a number: 16
Plese enter an odd number: 9
9 7 5 3 1
7 5 3 1
5 3 1
3 1
1
Program#7:
Write a program that takes 8 inputs from user in main using loop. Each time an input is given itis passed to a function Slarge(). Slarge function takes one input as parameter and keeps record oflargest number and second largest number entered till now. (Hint: use global variables to keeprecord of largest and second largest numbers)Output
Enter numbers: 1652
11
90
1673
65
7/26/2019 CP Manuals Updated3
70/123
70 | 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
7/26/2019 CP Manuals Updated3
71/123
71 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
1. To what extent did you learn on the material in thelab?
2. Are you able to apply knowledge gained in the lab tosimilar problems?
3. Are you able to analyze and interpret programs given
in the lab?
4. Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
5. Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
6. Were you able to function as a group in the lab?
7. Were you able to interpret effectively the proceduresand questions asked in the lab?
8. Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
72/123
72 | 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.
#includeusingnamespacestd;voiddisplay(intmarks[5]);
intmain() {intmarks[5] = {88, 76, 90, 61, 69};display(marks);return0;
}
voiddisplay(intm[5]) {cout
7/26/2019 CP Manuals Updated3
73/123
73 | 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 dif ference while passing array as an argument rather than variable.
void display(int m[5]);
The argument used marksin the above code represents the memory address of first
element of arraymarks[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.
7/26/2019 CP Manuals Updated3
74/123
74 | P a g e
#includeusingnamespacestd;voiddisplay(intn[3][2]);
intmain() {intnum[3][2] = {{3, 4},{9, 5},{7, 1}
};display(num);return0;
}voiddisplay(intn[3][2]) {
cout
7/26/2019 CP Manuals Updated3
75/123
75 | P a g e
function as arguments. The function then extract given number of characters from the string.
OutputEnter 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 negativenumbers to the left and positive numbers to the right.OutputEnter numbers in the array: 3 -5 1 3 7 0 -15 3 -7 -8The 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.
OutputEnter 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: Tthere 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 thenprints the smallest even element and smallest odd element of the arryOutputEnter 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 of6*80 size) then pass that array to a function named swap(). The swap() function will swap firstname with last name and print the array of strings.OutputEnter 6 names:
Abdul MananAli Hamza
Bilal Ahmad
http://thinkexist.com/quotation/there_are_two_tragedies_in_life-one_is_to_lose/7715.htmlhttp://thinkexist.com/quotation/there_are_two_tragedies_in_life-one_is_to_lose/7715.htmlhttp://thinkexist.com/quotation/there_are_two_tragedies_in_life-one_is_to_lose/7715.htmlhttp://thinkexist.com/quotation/there_are_two_tragedies_in_life-one_is_to_lose/7715.html7/26/2019 CP Manuals Updated3
76/123
76 | P a g e
M. Salman
Zahid Khan
Rehan Ali
After function call names areRehan Ali
Ali HamzaBilal AhmadM. 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
4 5 6
7 8 9
Note that neighbours of A[0][0] are 2, 4, and 5
Therefore B[0][0] = 2 +4 + 5 =11
Similarly, neighbours of A[1][1] are 1, 2, 3, 4, 6, 7, 8, 9
Therefore 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
11 19 13
23 40 27
17 31 19
7/26/2019 CP Manuals Updated3
77/123
77 | 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 5= Excellent
Questions Rating
(1 to 5)
Remarks
1. To what extent did you learn on the material in thelab?
2. Are you able to apply knowledge gained in the lab tosimilar problems?
3. Are you able to analyze and interpret programs given
in the lab?
4. Are you able to identify, formulate and solveelectrical engineering problems based on theknowledge acquired in the lab.?
5. Can you design an application/ software to fulfillcertain specifications based on the knowledgeacquired in the lab?
6. Were you able to function as a group in the lab?
7. Were you able to interpret effectively the proceduresand questions asked in the lab?
8. Comment whether your work in the lab has animpact on the society.
Additional Comments (if any):
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
7/26/2019 CP Manuals Updated3
78/123
78 | 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, recursionis 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 abase 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
7/26/2019 CP Manuals Updated3
79/123
79 | P a g e
myFunction(--counter);
return;
}
}
This recursion is not infinite, assuming the function is passed a positive integer value. What will theoutput be?
Consider this function:
void myFunction( int counter)
{
if(counter == 0)
return;
else
{
cout
7/26/2019 CP Manuals Updated3
80/123
80 | P a g e
Program#2:
Write a program that takes two numbers from user as first and second of the Fibonacci Seriesand then takes the number of the term that user wants to find in the series. You have to write arecursive function to perform this task.
Program#3:
Write a recursive program that takes two numbers from user and calculates quotient usingrecursive 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 0or 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 isnonzero 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 functionthen returns the largest number among array elements.
Program#7:
The expression of computing C (n,r), the