Itp Manual 2019
Itp Manual 2019
Technology Islamabad
LAB MANUAL
INTRODUCTION TO PROGRAMMING
Lab Designers
2
Capital University of Science & Technology
Islamabad
Department of Computer Science,
Faculty of Computing
Table of Contents
3
Capital University of Science & Technology
Islamabad
Department of Computer Science,
Faculty of Computing
4
Lab 1: Introduction to Microsoft Word and
Microsoft PowerPoint
1. Introduction
MS Word enables you to write letters, reports, memos and much, much more quickly and
efficiently. It will also enable you to print the documents out and store them for future reference, modifying
or altering them as you wish.
In this lab you will learn the basic working of Microsoft PowerPoint. Like MS Word, MS PowerPoint
is a part of Microsoft Office Suite and there are several features that you may find similar to MS Word.
Microsoft PowerPoint is a software product used to perform computer-based presentations. Microsoft
PowerPoint is a part of Microsoft Office package that creates and plays presentations. There are several
features that you may find similar to MS Word. We will however, concentrate only on those features that
are specific to MS PowerPoint.
4. Objective
• Use of templates to prepare reports
• Learning about writing styles
• Acquiring knowledge about References tab and its different options
• Getting working knowledge about inserting figures and tables in a document
• To create the first presentation
o Formatting Text boxes
o Basic Slide design and layout
o Inserting multimedia such as graphics, animation and sound in the presentation
• To Manage Slide Show
5
5. Concept Map
As mentioned in the introduction in this lab you will learn about insert, references and view tabs and also
the different options within these tabs. Insert tab is useful to represent your ideas in graphical and tabular
form. It can also be used to add mathematical equations and geometrical symbols. You can add Table of
contents in your document by using reference tab. View tab provides you the ability to view the document
in different layout.
A PowerPoint presentation is a good way to convey pieces of information, usually in the form of an outline,
to a large audience. Generally, PowerPoint presentations are appealing to users because they are easy to
create and edit and generally small enough to fit onto a CD or a USB You may think about various scenarios
in which a presentation is made: in a lecture hall while teaching the students, marketing a product to sell,
explaining a new scientific concept, etc.
1. Click on the blue Question Mark to go to Microsoft Office Help as shown in figure 10. The Office
Help is really good. After opening the help try to search the shortcut key for following tasks in MS Word
2007.
• Create a new document of the same type as the current or most recent document
• Open a document
• Close a document
6
• Save a document
Templates
Templates are a collection of styles and formatting settings, and they can save you a ton of time when
creating a new document. You can find templates for almost any type of document, from flyers to resumes,
and birthday cards to banners. You can also create your own templates to save yourself from having to
remake documents from scratch.
Go to File menu and click ‘New’. Select Sample templates to use the built-in templates.
7
Figure 1: Insert template
8
Cover Page is the title page of the document. Word 2007 provides a number of preformed cover pages to
give your document a professional look.
3. Scroll down and click the desired cover for the document from the Cover Page Gallery. Use the
scroll bar or scroll arrow to see all the cover page choices.
4. A Cover page will be added to your document.
Style Group
9
The fourth group on the Home ribbon is the Style group as shown in figure 29. Styles are a collection of
formatting options that you can apply to text. When you use styles to format your document, you can
quickly and easily apply a set of formatting choices consistently throughout your document.
A style is a set of formatting characteristics, such as font name, size, color, paragraph alignment and
spacing. Some styles even include borders and shading. For example, instead of taking three separate steps
to format your heading as 16-point, bold, Cambria, you can achieve the same result in one step by applying
the built-in Heading 1 style. You do not need to remember the characteristics of the Heading 1 style. For
each heading in your document, you just click in the heading (you don’t even need to select all the text),
and then click Heading 1 in the gallery of styles.
Tables
Word provides tables option for placing data in a more formal way.
1. Click on table in insert tab. (Figure 6)
2. To add Rows and Columns, select top to bottom for rows & left to right for columns (Figure .7)
3. Click to apply when happy with the selection.
4. Click on the box to enter text.
5. Observe the new tab opened "Table Tools". You can use this tool to apply further formatting to
your created table.
Figure 5: Tables
10
Columns
Rows
Illustrations
Using Illustrations you can add pictures of all types and styles to your document. Followed is detail
description on how to add illustrations.
Picture
The first selection in Illustrations is Insert a picture from a file. When you click on this a window will open
for you to browse to a photograph or other picture you have saved on your computer.
Insert Caption
Right click on the image and select ‘Insert Caption’.
11
Figure 1
12
Table of Contents
While writing long documents consisting of several main and sub headings it becomes a difficult task to
read and find relevant text. Microsoft Word helps deal with issue by assembling a table of contents (TOC)
for you, listing headings each with appropriate page number. It also takes care of counting pages, and even
updates the TOC for you if the document’s page numbers change. When you create a TOC, Word searches
your document for headings to include, recognizing them by the Styles applied.
13
Figure 8: Adding Table of Contents
14
Figure 10: Insert Table of Contents
Table of Figures
Exercise: How to add Table of Figures
1. Apply caption to your figures.
2. Move the insertion point to the place where you want the Table of figures to appear.
3. Click the References tab on the Ribbon and go to Captions section.
4. Click on ‘Insert table of figures’.
5. Choose your desired style and click ‘OK’.
15
Figure 13: Insert Table of Figures
Home ribbon
16
Slides
New Slide:
1. Click on home ribbon
2. Click on new slide button
3. New slide will be shown in your presentation
Layout:
Different slide layouts are used to manage the arrangement of content on the side.
Click the layout you want. The layout appears in the slide pane of the PowerPoint window.
1. Make two of the slides as tile slide, third and fourth one as size and content layout and last one
should be blank.
4. Search text from internet and add some points about computers in the successive two slides and
last slide should be having pictures of computers.
17
Ali Hamza Computers
BC111012
Themes
Applying theme to your slides:
• A theme is a set of colors, fonts, and special effects. Themes provide attractive backgrounds for
your PowerPoint slides.
• To apply a theme to all of the slides in your presentation:
– Choose the Design tab.
– Click the More buttons in the Themes group.
– Click the design as shown in arrow 3 of figure 18 you want.
18
Figure 18: Applying Themes
Change fonts to Arial, colors to origin and add Metro effects in Design Tab. (Arrow 4 in figure 18)
Background:
You can add a dramatic effect to your theme by applying a background.
1. Choose the Design tab.
2. Click the Background Styles button.
3. Click the background you want.
19
Figure 20: New Slide with Custom Design
After applying theme and background style 6, presentation would look similar to following slides:
7/11/2013 4 7/11/2013 5
Animations:
20
Preview:
Preview: This button previews the animated slides being set by using slide transitions of the presentation.
Animations:
Animations control how objects move onto, off of, and around your slides. Transitions control how your
presentation moves from one slide to the next
Custom Animation:
You can animate the objects on your PowerPoint slides. PowerPoint provides four types of animations as
shown in figure 22.
• Entrance
An Entrance animation determines the manner in which an object appears on a slide; for example,
an object can move onto a slide.
• Emphasis
An Emphasis animation does something to draw attention to an object; for example, the object
can become larger.
• Exit
An Exit animation determines the manner in which an object leaves a slide; for example, an object
can move off a slide.
• Motion Paths.
A Motion Paths animation determines how an object moves around a slide; for example, an object
can move from left to right.
To choose an effect:
1. Select the object you want to animate.
2. Choose the Animations tab.
3. Click the Custom Animation button . The Custom Animation pane appears.
4. Click the Add Effect button . A menu appears.
21
5. Choose the type of effect you want. A submenu appears.
6. Click the effect you want. PowerPoint applies the effect.
To modify an effect:
1. Click the down arrow next to the Start field on the Custom Animations pane and then select the
start method you want.
2. Click the down arrow next to the Property field on the Custom Animations pane and the select
the property you want. The Property field might be labelled Direction, Size, or some other
property.
3. Click the down arrow next to the Speed field on the Custom Animations pane and then select the
speed you want to apply to your animation.
To preview the animation, click the Play button on the Custom Animations pane.
Explore all of them yourself and animate your text and slides. slide show should display presentation in
effective manner with animations on each slide.
22
Transition Sound
This button allows you to add some sound during slid transitions of your presentation. You can select
various sounds from this option.
• In the pane that contains the Outline and Slides tabs, click the Slides tab.
• Select slide thumbnail of the slide that you want to add a sound to.
• On the Transitions tab, in the Timing group, click the arrow next to Sound, and then do one of
the following:
1. To add a sound from the list, select the sound that you want.
2. To add a sound not found on the list, select Other Sound, locate the sound file that you want
to add, and then click OK.
Select transition sound for the presentation that must not be annoying for the audience.
23
Transition Speed
It sets the speed of the slide transition to be slow, medium or fast.
1. All slides should advance one by one at mouse click or keyboard keys.
Apply To all
This button applies all settings being chosen on all slides in the presentation.
Advance Slide
To advance the slides to the next one, set the duration of the transition between the previous slide and the
current slide. For performing this task, do the following:
On the Transitions tab, in the Timing group, type or select the speed that you want: Mouse click
To advance the slide when you click the mouse, on the Transitions tab, in the Timing group, select the On
Mouse Click check box. Automatically After
To advance the slide after a specified time, on the Transitions tab, in the Timing group, in the After box,
enter the number of seconds that you want.
8. Practice Tasks
This section will provide practice exercises which you need to finish during the lab. You need to finish the
tasks in the required time. When you finish them, put these tasks into your lab designated Folder
announced by lab instructor
24
and their use” and create a presentation with following features applied to them:
2. Adapt Calibri style for text
3. Use blue and black color schemes for text
4. Use bullets and numberings to list down the types of computers.
5. Apply slide animation (shape plus) and text animations (motion paths in all directions) and slides
should be change as per set time of 1 sec.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).
25
Capital University of Science & Technology Islamabad
Department of Computer Science,
Faculty of Computing
26
Lab 2: Formatting using Escape Sequences
1. Introduction
This lab will introduce you about how to format the output screen for C++ program using escape sequence.
Further details about escape sequences will be discussed in the concept map (section 4 of this document).
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8, your
lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until
section 5. You will start your practical work from section 6 onward in the lab.
a) Lecture No. 2
b) Text Book: Computer Programming by D. S. Malik, Third edition, pages: 70-77
2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
8 Evaluation Task 30mins for each assigned task 60 mins
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Specialized Tasks 15mins 15mins
7 Practice tasks 10 mins for each task 70 mins
Total Time 170 mins
27
3. Objective of the Experiment
• To get basic understanding of Visual studio environment.
• To practice formatting and outputs in C++ using escape sequences.
• To get knowledge of different alerts generated through escape sequences.
4. Concept Map
4.1 Printing characters which are not part of a Keyboard
There are different types of characters on the keyboard such as: alphabets, numbers, and special symbols.
These symbols can be printed on the output screen as per the requirement. However, there are certain
characters which are not available on the keyboard and thus cannot be printed directly from a keyboard.
For example, when we want to print new line, there is no key on the keyboard which can be used directly
to print a new line. Similarly, if you want to print vertical tab, you do not have a key on the keyboard to
print it. In these scenarios, the escape sequences will help you. For example using the escape sequence,
“\n”, will help you to print a new line. Similarly, using the escape sequence, “\v”, will help you to print a
vertical tab etc. The details of further escape sequences can be found in Appendix A.
cout<<“Hello World”;
However, these are certain times, when you need to print the quotation marks (“) itself in the text. To
achieve this task, you can use escape sequence, For example, the following statement in C++
cout<<“\”Hello\” World”;
“Hello” World
28
4.3 Generating Sounds
If you want to generate a sound from your program at a typical point, you can use escape sequence to
achieve this. For example, writing “\a” will make a bell alert in the program. The details of further escape
sequences can be found in Appendix A.
4.4 Variables
Generally our program needs to manipulate data. For example, when we want to add marks of all subjects
of a students to get total marks. For manipulation, we need to store this data. The C++ provides us
different type of variables to store different data. For example, numeric values are stored in int, short,
and long variables. Different types of variables are presented in the appendix A. For further details, please
read the mentioned reference pages in the introduction.
Sometimes, we need to convert one data type to another data type for different purposes. For example,
suppose the marks of students are stored in float type and you want to apply modulus operator (%) on
this. You know we cannot use modulus operator on float types, therefore, we need to convert the marks
into int type, then we can apply modulus operator. Similarly, there will be different needs and scenarios
when we need to convert one data type to another. For this purpose, C++ provides us a type casting
mechanism.
gives us
There are many operators available in c++ which can be used to perform different tasks. One such type
is known as arithmetic operators. These include addition, subtraction, multiplication etc. The details can
be read from Appendix A.
int a=7;
int b=8;
int c=0:
c= a+b;
a=a+1;
b=b-1;
29
There is a binary operation addition on the variables a and b. then we increment the variable a by 1 and
decrements variable b by 1. However, C++ allows us incrementing or decrementing a variable within the
same expression (such in previous example c= a+b)
For this you can write the following code instead of the preceding code:
int a=7;
int b=8;
int c=0:
c= (a++)+ (b--);
You must have noticed that we have not used the increment and decrement operator in a separate line,
instead we used “++” and “--” within the main expression. These operators are called unary operators.
We can use a++, or ++a. Both will have different meaning. For example a++, will be evaluated after the
expression has been evaluated. In the above case after evaluating the addition operator, the ++ will be
evaluated. In this case ++ is post increment. However, ++a, would mean that first increment a by 1 and
then use this in the expression. For more details, read the reference material assigned to you (as written
in the introduction of this lab task.).
Q1. Write a C++ program which would print the following screen as output:
******************************
* Welcome to my program *
****************************** Q2:
Q2. Write a C++ program which would print the following screen as output:
Q3. Write a program that takes radius of circle from user and calculate the area of circle using the following
formula. Area = πr2.
30
Q4. Take temperature in Fahrenheit as input from user and display in Celsius
C = (F - 32) * 5 / 9
6. Procedure& Tools
6.1 Tools
Visual Studio 2008.
31
Figure 2: Opening File Menu
32
Figure 4: Selecting Source File Folder
33
.
Figure 6: Select CPP file
When you click the Add button,A new file would be added to your existing project as shown in the Figure7.
**********
* Hello *
* World *
34
6.3.1 Writing Code
Remember you created a file with name “myprog” in the task 6.2.7.now write the following code as shown
in the Figure 8. Write the code in the intended form as shown.
6.3.2 Compilation
After writing the code, now you are ready to compile it. For compilation, select ‘Build Solution’ from the
‘Build’ option in the menu bar as shown in the Figure 9.
When you click on build solution, the compiler would start processing your program. The progress of build
activity would be displayed on the output window as shown in the Figure 10.
35
Figure 10: Build Activity
The progress would show whether the build was successful or not. It would display the errors if any.
Otherwise it would display the message “Build succeeded”
.
**********
* Hello *
* World *
Remember you created a file with name “myprog” in the task 6.2.7. now write the following code as shown
in the Figure 8. Write the code in the intended form as shown.
36
Figure 11: Writing the C++ code
Final output
37
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to finish
the tasks in the required time. When you finish them, put these tasks in the folder specified by your lab
instructor.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$****************************$
***********\\\WELCOME to CP*******
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Name | Zubair
ENo | 1234
38
Dept | EE
Rank | Lecturer
Sal | 12,000
Allownces | Amount
House Rent | 1000
Medical | 1500
TA/DA | 2000 Bonus
| 50000
Make a program which will read an integer variable count from user and then write each of the following
statements in cout and note the output.
1. ++count,
2. -- count,
3. count ++,
4. count - -
a. Addition
b. Subtraction
c. Division
d. Multiplication
e. Square
39
7.10 Practice Task 10 [Expected time = 10 mins]
Write a program that reads a four digit number from user, then the program separates digits of the number
e.g 4567 to be displayed as:
4
5
6
7
b) Write a program that defines variables Num1, Num2, Num3, and Num, as integer Solve
the following expression on notebook by supposing some values of each variable, then
execute your program for the same values and see the difference if any.
Num1 + Num2 / Num3 + Num + Num2++ where Num1, Num2 and Num3 are
all integer type variables
c) Write a program that defines variables m, n, p, and amount, as integer Solve the following
expression on notebook by supposing some values of each variable, then execute your
program for the same values and see the difference if any.
(m + n) / (p + amount)
Write a program in C++ which would swap the values of two variables without using the third variable.
In this Lab, you have learned that how the escape sequences are used to format the output
40
7.9 Testing
For this task, no test cases are required. The instructor will check the outputs of the practice tasks.
Practice Input Output Confirm
Tasks
7 Number1:7 Addition15
Number2: 8 Postfix Increment: 7
Prefix Increment:9
Postfix Decrement: 9
Prefix Decrement:7
8 Count: 8 Prefix Increment:9
Prefix Decrement:8
Postfix Increment:8
Postfix Increment:9
9 Number1:4 Addition:12
Number2: 8 Subtraction: -4
Division: 2
Square of Number1:
16
Square of
Number2:64,
Multiplication:32
10 3247 3
2
4
7
11 a:4 Expression Output:97
b: 3
c: 4
d: 5
Num2: 4
12 Number1:6 Number1:4
Number2: 4 Number2:6
41
T11
T2
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
42
Appendix A – Escape Sequences
Escape
Represents
Sequence
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\ " Double quotation mark
\\ Backslash
\? Literal question mark
\ooo ASCII character in octal notation
\xhh ASCII character in hexadecimal notation
Unicode character in hexadecimal notation if this escape sequence
\xhhhh is used in a wide-character constant or a Unicode string literal.
For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese
character for one is \x4e00".
Double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
43
Capital University of Science & technology Islamabad
Department of Computer Science,
Faculty of Computing
44
Lab 3: Control Structures (Selection) and Relational
Operators
1. Introduction
This lab will introduce you the concepts of how to use the Control Structures (selections) such as: if, ifelse,
if-else-if. Furthermore, you will also learn the relational operators such as >, >=, <= etc. The relational
operators are frequently used in conditions to make number of decisions. There is another important type
of operators (logical operators) which are often used with conditions. However, the current lab will not
focus on this. The logical operators will be covered in the next lab.
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8, your
lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section
5. You will start your practical work from section 6 onward in the lab.
2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
8 Evaluation Task 30 mins for each assigned task 60 mins
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Specialized Tasks 30 mins 15 mins
7 Practice tasks As mentioned with each task 70 mins
45
Total Time 170 mins
4. Concept Map
We will review some important concepts regarding selections (conditions) in this section. The selection is
used to control the execution of your program and to make number of decisions. You will learn along with
examples about this.
if (number<0) number=
-1 * number;
if (marks>50)
cout<<”Passed”; else
cout<< failed;
You can use as many if-statements after the else part, for example, consider the following code:
if (marks>90)
cout<<”Grade is A”;
else if (marks>85)
cout<< “Grade is B”;
else
cout<< “Fail”;
The above statement will output the grade “A” for all students scoring more than 90 marks. However, the
grade of the students will be B who have scored more than 85 marks and less than 90, similarly, the
remaining students will get F grade. The statement will be executed in a way that first statement will be
checked, if the students marks are greater than 90, then the grade will be shown as “A” and the remaining
46
parts will not be executed (The else part). If the students marks are less than 90, then the first statement
would be evaluated as false, and the control will be passed to the else if (marks >85) statement.
if (marks>90)
cout<<”Grade is A”;
cout<<”congratulations,
you have performed
excellent”;
If the marks are more than 90, the program will display the following output:
Grade is A
Congratulations, you have performed excellent
However, suppose if the marks are less than 90, then guess what you will get:
Nothing ….
Surprisingly. This will not happen; however, for the marks less than 90, the following would be printed on
screen:
This is due to the fact that c++ considers only one statement as associated with the condition, and the
statement
cout<<”congratulations, you have performed excellent”
is not part of the if-statement, and as the if has been evaluated as false therefore the above statement will
be executed
if (marks>90)
{
cout<<”Grade is A”;
cout<<”congratulations, you have performed excellent”; }
Now both statements will be associated with the if-statement. In case the if-statement is false, none of the
above statements will be executed.
47
5. Homework before Lab
5.1 Problem solution modeling
After reading the reference material mentioned in the introduction, now you are ready to
design the solution of the following problems.
Follow your text book, and solve the problem no. 1 to 8 mentioned on the page number 226 and 227.
Bring the solution with you and submit this to lab instructor.
1. Write a program that takes a number from the user and tells what is the equivalent month of this
entered number e.g. if the user enters 6 then system should display it is JUNE.
2. Write a program to input five number from user and check the number are divisible by 3 then
print the message on the screen that “the number is divisible by three”. Otherwise print “The
number is not divisible by three”.
1. Write a program that asks the user for two numbers and then print the maximum and minimum
number to the user.
2. Write a program that displays a menu to the user. Press 1 to find a sum of the numbers given by the
user Press 2 to find whether the number is even or odd
48
Figure 1: Selecting Microsoft Visual Studio
49
Figure 3 (a): Selecting New Project
50
Figure 4: Selecting Source File Folder
51
.
Figure 6: Select CPP file
When you click Add button, A new file would be added to your existing project as shown in the Figure7.
52
Figure 8: Writing the C++ code
6.2.2 Compilation
After writing the code, now you are ready to compile it. For compilation, select ‘Build Solution’ from the
‘Build’ option in the menu bar as shown in the Figure 9.
53
..
Figure 9: Compiling the C++ program
When you click on build solution, the compiler would start processing your program. The progress of build
activity would be displayed on the output window as shown in the Figure 10.
The progress would show whether the build was successful or not. It would display the errors if any.
Otherwise it would display the message “Build succeeded”
.
Now run the program by pressing Ctrl+F5 from keyboard or selecting play option from Debug menu (Debug
menu can be accessed from the Figure 10). When you press Ctrl+F5, the compiler would start executing
the program and would display the final output to your screen as shown in the Figure 11.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by your
lab instructor.
54
7.1 Practice Task 1 [Expected time = 20 mins]
Write a program that able to compute the pay of both types of employees: retired one’s and employed, the
retired employees will receive pension and it will be computed and displayed with proper variables and
messages. The pension of the employer will be fixed and will be computed on the basis of age, if the age of
the retired employer is between 60 to 70 years then its pension will be 30000 and if the age is greater than
70 then the pension will be 40000. The pay of the employer will be computed on daily worked hours and
the net pay will be shown with the proper messages of gross salary. The pay of the employer will be 1000
rupees per day if he/she worked for 8 hours and if it works more than 8 hours, then he will be payed 300
rupees per hour but the extra time can only be utilized at maximum of 3 hours.
Marks Grades
Greater than 90 A
Greater than or equal to 86 and less than 90 A-
Greater than or equal to 81 and less than 86 B+
Greater than or equal to 77 and less than 81 B
Greater than or equal to 72 and less than 77 B-
Greater than or equal to 68 and less than 72 C+
Greater than or equal to 63 and less than 68 C
Greater than or equal to 58 and less than 63 C-
Greater than or equal to 54 and less than 58 D+
Greater than or equal to 50 and less than 54 D
Below 50 F
7.5 Testing
Now you need to perform the following test cases for all practice tasks mentioned above. The test cases have
been made available in Table 2.
55
Table 2: Test cases
7.2 99 A
76 B-
49 F
79 B
83 B+
7.3 Salary1=50000 Maximum salary is = 99000
Salary2=45000 Minimum salary = 10000
Salary3=39000
Salary4=99000
Salary5=12000
Salary6=58000
Salary7=54000
Salary8=25000
Salary9=10000
Salary10=10400
The lab instructor will give you unseen task depending upon the progress of the class.
8. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).
56
4 9 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10
9. Further Readings
9.1 Books
Text Book:
C++ Programming by D.S Malik, Third Edition Reference
Books:
1. Beginning C++, the complete language, by Ivor Horton, Wrox Publishers.
2. How to Program in C++, Dietel and Dietel
9.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
57
Capital University of Science and Technology
Islamabad
Department of Computer Science,
Faculty of Computing
58
Lab 4: Nested If-else and Logical Operators
1. Introduction
In the previous lab, you have learned how to use conditions and have learned three different types of
conditions (simple if-statement, if-else statement and if-else-if statements, and compound statements).
Those statements worked for a single condition; however, there are certain real problems when we need
to make the decision based on two or more conditions. In this case we can use nested-if or can use logical
operators. You will learn in detail about nested-if and logical operators in this lab. The concept map
presented in this lab will guide you when and where to use nested-if or logical operators. The logical
operators have been made available in the Appendix – A for your reference.
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8, your
lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You will start your
practical work from section 6 onward in the lab.
a) Lecture No. 7
b) Text Book: Computer Programming by D. S. Malik, pages: 175-184, 192-198, 203-204
c) Revise Quick Review available at 219-220
59
6.2 Specialized Tasks 30 mins 15 mins
7 Practice tasks As mentioned against each task 70 mins
Total Time 170 mins
4. Concept Map
We will introduce the nested-if condition and logical operators in this section. Furthermore, we will study
where and when to use these concepts in C++ program. When an if-statement is included within another
if-statement then we say that this is nested-if. For evaluating more than one condition, we can use either
nested-if or logical operators. There are three logical operators available in C++. For example logical-and
(&&), logical-or (||), and logical-not (!). We will study them one by one.
if (percentage>=70 )
{
if (age <16)
{
cout<<”Congratulations! You are eligible for the scholarship”;
}
}
The nested-if statement is executed in the following way, first, the statement (percentage>=70 ) will
be evaluated, if the statement is true then the control is passed to the first statement within this
ifstatement. The first line within this if-statement is again an if-statement, now the statement age (
<16) will be evaluated. Here if this statement is also true, then the student will be given the
scholarship. We can use logical-and to solve the same problem as well. This will be discussed in the next
section.
60
4.2 Logical-and (&)
The same problem (discussed in section 4.1) can be solved with using logical-and operator (&) between both
conditions. For example, consider the following code:
To understand the above statement, revise your concepts from the previous course of ITC. The logicaland is
evaluated as true if both values (conditions) are true. For revision, you can have a look on the Appendix A.
For the above code, if both conditions are true, then the statement will be executed. The difference between
using logical-and and nested-if has been explained in the next section.
4.3 Similarities and Differences for the use of nested-if and logical-and
For the example used in the section 4.1 and 4.2, there is no difference, one can use any of them (nestedif
or logical-and)
Code A:
if (percentage>=70 )
{
if (age <16)
{
cout<<”Congratulations! You are eligible for the scholarship”;
}
}
Code B:
if (percentage>=70 && age <16)
{
cout<<”Congratulations! You are eligible for the scholarship”;
}
In this scenario, both codes will output the same. However, there are certain differences in using nested-
if and logical-and (&&). There are some scenarios where use of nested-if is better, however, there are
some other scenarios where the use of logical-and(&&) is better. For example, consider the following case.
61
if (percentage>=70 )
{
if (age <16)
{
cout<<”Congratulations! You are eligible for the scholarship”;
}
cout<<”Your percentage is more than 70”;
}
However, you probably, will not like to write the above code in the following way.
if (percentage>=70 )
{
if (age <16)
{
cout<<”Congratulations! You are eligible for the scholarship”;
}
62
else {
cout<<”Sorry, you did not get the scholarship”;
}
}
else
{
cout<<”Sorry, you did not get the scholarship”;
}
The “cout” statement will be executed if any of the conditions is true. For example either the person has
achieved more than 70% marks or his/her age is less than 16, the scholarship will be awarded to that
person.
the above statement will be evaluated as false because the condition (5==5) is evaluated as true and
logical-not (!) will make it false, as the if-statement is evaluated as false, therefore, the cout-statement will
not be executed. Similarly, we have written the previously discussed example by incorporating logical-not
(!)
63
Now we have both logical-and and logical-not. You know that logical-and will be evaluated as true if both
conditions are true. The first condition would be true when percentage is more than or equal to 70,
however, the second condition would be true when the age is more than or equal to 16. Remember, from
previous discussion that whenever the inner condition (age<16) is false, the logical-not (!) will make it
true. Therefore, the scholarship will be given to only those students whose percentage is greater than or
equal to 70 and whose age is more than or equal to 16.
switch (expression)
{
case value1:
statements……
break; case
value2:
statements..….
break;
.
.
. case
valuen:
statements
break;
default:
statements….
}
Where switch, case, break, and default are the reserve words and have particular meanings which you
will learn in this lab. Please note that the break statement is an optional statement. This means you can
use this statement or not depending upon the situation. You will learn the effect of including and
excluding a break statement in the next section.
64
The expression sometimes, is referred to, selector. First the expression in the switch statement is
evaluated. Subsequently, the corresponding case is executed. It is not mandatory that the expression is
an identifier. It can be a identifier or an expression. However, the value of the expression should be
integral only.
In such a menu driven statement, using switch statement is encouraged. This will make your code more
readable.
You can program this problem using the following code:
When user enters the value 1, the user will get the following output:
When user enters the value 2, the user will get the following output:
When user enters the value 3, the user will get the following output:
65
You selected the option to see the profit statement
However, consider that if we exclude the break statement (recall from the previous section that the
break statement is optional), then the output will be changed for different inputs. For example:
consider the following code without break statements.
int option;
cout<<” Enter 1 to purchase products”;
cout<<” Enter 2 to sale products”;
cout<<” Enter 3 to see the profit statement =”;
cin>>option;
switch (option)
{
case 1:
cout<<”You selected the option to purchase products”;
case 2:
cout<<”You selected the option to sale products”;
case 3:
cout<<”You selected the option to see the profit statement”;
default:
cout<<”You have selected the wrong value”;
When user enters the value 1, the user will get the following output:
When user enters the value 2, the user will get the following output:
When user enters the value 3, the user will get the following output:
When the break statement is not included then from onward a true case, all cases will be executed until
the switch statements ends, or a break occurs. For example consider the following example, for more
clarification.
66
int option; cout<<” Enter 1 to purchase
products”; cout<<” Enter 2 to sale products”;
cout<<” Enter 3 to see the profit statement =”;
cin>>option; switch (option)
{
case 1:
cout<<”You selected the option to purchase products”;
case 2:
cout<<”You selected the option to sale products”;
break;
case 3:
cout<<”You selected the option to see the profit statement”;
default:
cout<<”You have selected the wrong value”;
}
In this switch statement, we have written a break statement after the statement associated with case 2.
When user enters the value 1, the user will get the following output:
The user will not get the output You selected the option to see the profit statement because
there is a break after second case.
When user enters the value 2, the user will get the following output:
The statement cout<<You selected the option to see the profit statement will not be
executed because there is a break after the second case.
Finally, when user enters the value 3, the user will get the following output:
If user enters any statement other than 1, 2, or 3 (for which we have written cases), in that case, the default
statement is executed.
67
4.8 The character value in the expression
We learned in the previous section that the value of the expression could be an integral. In the previous
example, you have learned how integer values are used in the switch statement. Now we will learn how
the character values can be used in the switch statement. Consider the following example; consider you
want to make a program that converts Pakistani Rupee into different international currencies such as:
Euro, Dollar, and Riyal.
switch(option)
{ case ‘E’:
cout<<”You selected the conversion from Rupee to Euro”;
break;
case ‘D’:
cout<<”You selected the conversion from Rupee to Dollar”;
break;
case ‘R’:
cout<<”You selected the conversion from Rupee to Riyal”;
break;
default:
cout<<”Wrong input”;
}
68
For the better understanding of this program, remember, the discussion on the break statement in the
previous section.
int marks;
cout<< “Enter your marks”;
cin>>marks;
switch(marks>=50)
{
case 1:
cout<<”Congratulations, you have qualified the examination”;
break;
case 0:
cout<<”Sorry, you have not qualified the examination ”;
break;
}
In this case, the expression will be evaluated as logical-true or logical-false. If the marks are greater than
or equal to 50, then the statement “ cout<<”Congratulations, you have qualified the
examination”; will be executed, otherwise, the statement “ cout<<”Sorry, you have not
qualified the examination ”; will be executed. As the expression is logical-true or logical-false,
therefore, you can use “true” instead of 1 and “false” instead of 0 as shown below.
int marks;
cout<< “Enter your marks”;
cin>>marks;
switch(marks>=50)
{
case true:
cout<<”Congratulations, you have qualified the examination”;
break;
case false:
cout<<”Sorry, you have not qualified the examination ”;
break;
}
69
int value;
cin>>value;
switch (value%10)
{ case 0:
cout<<”The unit place digit is Zero”;
break;
case 1:
cout<<”The unit place digit is One”;
break;
case 2:
cout<<”The unit place digit is Two”;
break;
case 3:
cout<<”The unit place digit is Three”;
break;
case 4:
cout<<”The unit place digit is Four”;
break;
case 5:
cout<<”The unit place digit is Five”;
break;
case 6:
cout<<”The unit place digit is Six”;
break;
case 7:
cout<<”The unit place digit is Seven”;
break;
case 8:
cout<<”The unit place digit is Eight”;
break;
case 9:
cout<<”The unit place digit is Nine”;
break;
}
70
Program listing using Boolean varriables Program listing using bits
boolean bool1, bool2, bool3, bool4, unsigned char ch=181;
bool5, bool6, bool7, bool8;
bool1=true; //the equivalent of 10110101 is
bool2=false;
bool3=true;
bool4=true;
bool5=false;
bool6=true;
bool7 = false;
bool8=true;
From the above program, you have a clear idea that on one side, when using Boolean variables, we have
to define eight Boolean variables to store the result-status of eight students, however, on the other hand,
we have used only one character (which will take only one byte) to store the result-status of eight
students. Remember, we cannot access bit by bit using C++, therefore, we had to define the equivalent
values of Boolean variables into one unsigned character. The right most bit one mean that the first
student is passed; similarly the second bit from the left is zero which means that the second student is
failed. Recall, how the binary values are converted to their equivalent decimal. We have converted it and
it was 181 in decimal, therefore, we assigned the value 181 to the unsigned character variable “ch”. You
have seen that we were not able to set each and every bit of the variable. To set the individual bits, we
need to perform bitwise operators with intelligence. The bitwise operators, again, cannot be applied on
a single bit, but you can use them intelligently to set individual bits. We have used unsigned character
because for the signed value, the most significant bit is reserved to store the sign bit (positive and
negative).
Note: The ordering of bits is machine dependent. Some hardware architectures consider the left most
bit as the most significant bit, while other considers, the right most bits as the most significant bit. In the
above example, we have considered a hardware architecture which considers the left most bits as the
most significant. If you use a computer architecture which uses the right most bits as the most significant
bits, then you need to tune your program accordingly.
71
5. Homework before Lab
5.1 Problem solution modeling
Write the pseudo-code for the following problems:
1. Write a program that calculates salary and medical charges for the employees. There are two types
of employee’s permanent and daily wages. The daily wages employee are paid 400 per hour while
permanent employees are paid 800 per hour. First ask the user for employee type and then ask
for either calculating salary or medical charges. Permanent employees are paid 5% medical
charges of their total salary while daily wages are paid 3% of medical charges. After calculating for
one employee it should ask the user for continuation.
2. Write a program which asks the user to either convert the number of days into hours or minutes.
Based on the option entered by user your program should calculate the result accordingly.
1. Write a program that asks the user for three numbers and then print the maximum and minimum
number to the user.
2. Write a program which asks the user to enter number of days. Subsequently, the user can either
Select any of the following options:
Based on the option entered by user, your program should calculate and display the results
accordingly.
void main(){
char ch1='A', ch2='B';
switch(ch1) Output
{
72
case 'A':
cout << "Outer A \n";
switch(ch2)
{
case 'A':
cout<<"Inner A\n";
break;
case 'B':
cout<<"Inner B\n";
}
break;
case 'B':
cout << "Outer B \n";
}
}
• Write a program which would calculate the grades of students against their score. The grading criteria
is as follows:
• Remember you created a file with name “myprog” in the task 6.1, now write the following code as
shown in the Figure 1. Write the code in the intended form as shown on the next page:
73
.
Figure: Writing the C++ code
74
Figure 1: Writing the C++ code
6.2.2 Compilation
After writing the code, now you are ready to compile it. For compilation, select ‘Build Solution’ from the
‘Build’ option in the menu bar as shown in the Figure 2.
75
..
Figure 2: Compiling the C++ program
.
When you click on build solution, the compiler would start processing your program. The progress of build
activity would be displayed on the output window as shown in the Figure 3.
The progress would show whether the build was successful or not. It would display the errors if any.
Otherwise it would display the message “Build succeeded”.
Now run the program by pressing Ctrl+F5 from keyboard or selecting play option from Debug menu (Debug
menu can be accessed from the Figure 2). When you press Ctrl+F5, the compiler would start executing the
program and would display the final output to your screen as shown in the Figure 4.
76
Figure 4: Final output
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to finish
the tasks in the required time. When you finish them, put these tasks in the folder specified by your lab
instructor
His monthly gas bill charges are 10% of his salary, electricity bill charges are 5% of his salary. His
monthly fueling charges are 10% of his salary, and his house rent charges are 15 %. Your program
will calculate and display the corresponding charges based on the selection (1, 2, 3, or 4)
On the selection of account type, the user will open an account by providing an initial amount. In current
account the initial amount for opening an account would be 2000 and for savings it would be 5000. After
choosing the account type and opening the account with initial amount, your program will display the
following menu:
77
In current account the user cannot withdraw more than 10000 rupees. In Savings account the user cannot
withdraw more than 25000. When the user withdraws amount make sure that amount should not be more
than the balance in account and at the end of withdrawal transaction, there should be minimum of 500
rupees for each account.
Write a program that ask the users to enter three characters. Then the program should display the following
menu
The program should perform sorting of these three characters in ascending or descending order as per the
user requirement.
After selecting the appropriate employee calculate salary and medical charges for the employees. Following
menu would be displayed:
The daily wages employees are paid 400 per hour while permanent employees are paid 800 per hour.
When you would calculate the salary, first you need to ask for the number of hours for which the
employee has worked so far. The permanent employees are paid 5% medical charges of their total salary
while daily wages are paid 3% of medical charges. For calculating medical allowance no further
selection/input is required.
7.8 Testing
For the tasks mentioned in Section 7, following are the test cases. The instructor will check the outputs of the
practice tasks accordingly.
78
6.2 Enter your marks Grade is: B
Marks:85 Grade is: D
Marks:65 Grade is: F
Marks:40 Grade is: D
Marks: 60
79
8. Evaluation Task (Unseen) [Expected time = 60 mins]
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$
80
Appendix A – Logical Operators
a b a && b a b a || b a !a
true true true true true true true False
true false false true false true False True
false true False false true true
false false False false false false
&& OPERATOR || OPERATOR ! OPERATOR
81
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
82
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
1. Introduction
In the last two lab, you have learned how to use a typical control structure i.e conditions. There is
another control structure which is known as repetition structure or loops. The loops also control the
flow of your program. This lab will introduce you about different loops and their usage. You will also
learn the scenarios where a typical type of loop can be used.
The section 2 presents a table that outlines some major activities and tasks you will do as the part of
this lab. Table 1 also provides the estimated-time for each activity, which will help you to organize
your tasks well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept
Map”) discusses and provides a comprehensive introduction of the topic. Section 5 lists the set of
home-tasks you are required to complete before this lab. Section 6 presents a “walkthrough task” that
you will do as the first practical activity during your lab. The walkthrough task has many small steps
which you should follow as directed in-order to complete the task and to get the desired output. After
that, you will be ready to work on some tasks on your own. The section 7 lists practice tasks for this
purpose. As the part of section 8, your lab instructor will give you some tasks at runtime and will
evaluate those according to the criteria mentioned in section 9. Section 10 lists some further reading
links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You will start your
practical work from section 6 onward in the lab.
83
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
4. Concept Map
4.1 Why using loops
Loops are used in the program when certain types of statements are repeated in the program to
achieve a specific task. For example, consider the following scenario:
Suppose you want to display “Welcome to CP Course” 10 times on the screen
To achieve this, you know that you can write 10 statements in the following manner:
However, this is not elegant way to achieve this task, although the above statements will produce the
required output.
You can notice that the statement cout<<” Welcome to Cp Course\n”; is repeating 10 times.
This type of statements can be written using a loop. For example, consider the following code which
will print the same output:
84
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
for(int i=1;i<=10;i++)
cout<<”Welcome to Cp Course\n”;
Wow, this looks great. You have achieved the task of printing a message 10 times using just two lines.
Please notice, if we want to print the same message 20 times, we will just replace 10 with 20 in the
above code just like the followings:
for(int i=1;i<=20;i++)
cout<<”Welcome to Cp Course\n”;
How this program works, we will learn in the following sections. We will start formally describing loops.
The loops can be categorized into two major types such as: Pre-condition loops and post-condition loops
4.2.1 For-Loop
Consider the code written in the previous section
for(int i=1;i<=20;i++)
cout<<”Welcome to Cp Course\n”;
This loop is called for-loop. This loop has initialization such as int i=1 from where the loop is going to
be started. Then after semi-colon, there is a condition i<=20, and then the increment i++. The working
of this loop will be as follows:
85
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
is similar concept which you have learned in if-statements. For example, for compound
statements, we will write the loop in the following way:
for(int i=1;i<=20;i++)
{
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”;
}
b) The initialization statement and increment statements are optional to within the loop brackets.
For example, you can write the same code in the following way:
int i=1;
for(;i<=20;)
{
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”; i++;
}
c) The increment in the above code need not to be the increment, it could be decrement as well.
For example the same code can be rewritten as follows:
int i=20;
for(;i>=1;)
{
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”; i--;
}
We have used decrement instead of increment. This means we have counted the loop from
20 towards However, please note, we have also changed the condition as well. Now we are
starting loop from 20 and need to execute statements until the i remains greater of equal to
1.
d) If we start a loop from 20 and do not change the condition, then guess what will happen.
86
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
int i=20;
for(;i<=20;)
{
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”; i--;
}
Clearly observe that we have started a loop from 20 and decrement the condition variable I, this will
become 19, 18, 17… and so on, and our conditions is that repeat this loop until i remains less than or
equal to 20. The next numbers 19, 18, 17, … and so on will always remain smaller than 20. What do
you think when this loop will terminate, This will not terminate ever. This type of loop is called infinite
loop. BEWARE Of CREATING SUCH LOOPS.
There are different categories of controlling a loop. The for-loop comes under the category of
countercontrolled loop. You will learn about many different categories of controlling the conditions
of the loop in the next section where we will discuss the while loop.
4.2.2 while-Loop
The while-loop is also a pre-conditioned loop. The condition is evaluated first before executing the
statements of the loop. The previous code can be re-written with while loop in the following way.
int i=1;
while(;i<=20;)
{
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”; i--;
}
This loop is executed in the similar way as discussed previously about for-loop. This type of loop is called
counter controlled loop. However, there are some other types of controlling a loop.
87
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
int marks;
int sum=0;
const int sentinel=-1; // the marks of a student cannot be negative.
cout<<”Enter the marks of the student”;
cin>>marks;
while(marks!=sentinel)
{
sum=sum+marks;
cin>>marks;
}
cout<<”The total marks of this students are”<<sum;
Now the user is free to enter the marks of a student for any un-specified quantity. However, once the user
enters the -1, the loop is terminated.
4.3 do-while-Loop
The loops discussed in the above section are known as pre-condition loops. This means first the
condition is checked and then the associated statements are executed. However, there is another
type of loops, which are known as post-conditioned loops. This means the loop will execute at least
once and then will check the condition, if the conditions true the loop will execute again, otherwise
will be terminated. Such a loop can be implemented in C++ using do-while structure. The example
discussed in the section 4.2.2 has be re-written using do-while loop below:
int i=1;
do {
cout<<” Welcome to Cp Course\n”;
cout<<”Hello class”;
i++;
} while(i<=20);
88
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
1. Write a program that calculates following formula. User enters values of n and m then
calculate power-using loop. n ^ m. for example 2 power 3=8
2. Write a program to display all the numbers between 1 and “n” that are perfect squares. The
value of “n” will be input by the user.
3. Write a program which would print 3 and its multiples until the number 60. 5. Write a program,
which would find and display the product of all odd numbers from 1 to 50.
To achieve this task, you need to setup a file as you did in Lab-1. Refer to the 6.2 section of lab-1 for
setting up a project.
You need to practice the following task to get basic understanding of developing a small program using
repetition structures. When you finish this task, the following output will be printed.
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
89
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
2 x 9 = 18
2 x 10 =20
6.2.2 Compilation
After writing the code, now you are ready to compile it. For compilation, select ‘Build Solution’ from the
‘Build’ option in the menu bar as shown in the Figure 2.
90
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
When you click on build solution, the compiler would start processing your program. The progress of build
activity would be displayed on the output window as shown in the Figure 3.
The progress would show whether the build was successful or not. It would display the errors if any.
Otherwise it would display the message “Build succeeded”
.
91
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by
your lab instructor
****
***-
**--
*---
92
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
7.7 Testing
For the tasks mentioned in Section 7, following are the test cases. Perform these test cases to validate
your programs and write “Yes” in the last column of each table after successfully executing the test case.
93
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
2. Number = 2 Power 4
=2
3. Number= 10 Power 1
=0
4. Number =25 Power 0.04
=-1
5. Number 0 Power 1
=0
94
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
For testing Task no. 7.5, execute at-least one input from each of the test cases 7.1, 7.2, 7.3, 7.5 and press
‘Y’ or ‘y’ to continue the program and confirm the tasks in the table.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the
student has finished the complete/partial task(s).
95
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$
96
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
1. Introduction
In this lab, you will learn about nested loops.
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
97
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until
section 5. You will start your practical work from section 6 onward in the lab.
4. Concept Map
4.1 Nested Loops
In lab-6, you have already learned and practiced the loop structures which can be used to repeat/iterate
set of statements based on some number of iterations or based on some logical condition. Basically C++
98
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
provides three types of loops: for-loop, while-loop, and do-loop. To solve different problems, you have
exercised the use of loops in you program.
Consider a scenario, where you are required to repeat a complete loop. For example: you are asked to
write a C++ program that prints 6 lines (where each line contains 25 even numbers starting from 2 and
ending at 50) as shown below:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50,
cout<<endl; for(int
i=2;i<=50;i+=2)
cout<<i<<’, ’;
cout<<endl; for(int
i=2;i<=50;i+=2)
cout<<i<<’, ’;
cout<<endl; for(int
i=2;i<=50;i+=2)
cout<<i<<’, ’;
cout<<endl; for(int
i=2;i<=50;i+=2)
cout<<i<<’, ’;
cout<<endl; for(int
i=2;i<=50;i+=2)
cout<<i<<’, ’;
}
99
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
As you can see that it is not an elegant looking code although the output was correctly produced. Assume
that you are required to produce the similar output but instead of only 6 lines of output you were asked
to output 1000 lines. If you code you program as shown above, you can imagine how untidy looking source
code will be produced.
As you have noticed that in the above program we actually need to repeat the entire for loop (shown
below) to 6 or 1000 number of times.
for(int i=2;i<=50;i+=2)
cout<<i<<’, ’;
The more elegant solution to the problem would be to place the above shown loop inside another loop
(nesting of a loop) which iterates 6 or 1000 times. Following code shows the improved version of the
program: #include<iostream>
using namespace std;
void main()
{ for(int j=0;j<6;j++)
{ for(int i=2;i<=50;i+=2)
cout<<i<<’, ’;
cout<<endl;
}
}
Loop nesting (similar to nested if) is a code arrangement where we place a complete loop inside another
loop. Above code shows that we have placed i-loop (which prints even numbers on the screen) inside
another loop (which repeats the inner loop 6 times). Loop nesting can be done at two or some higher
levels as required. In C++, you are allowed to nest loops (loop inside another loop) at any level of nesting.
For example a level 3 loop nesting means that there are three loops which are nested in a hierarchy such
as:
#include<iostream>
using namespace std;
void main()
{ for(int i=0;i<3;i++)
{ for(int j=0;j<=3;j++)
100
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
{
for(int k=0;k<3;k++)
cout<<”\nHello World!”;
}
}
}
In the above shown code “Hello World!” will be printed on screen 27 times (3 * 3 * 3 = 27). In C++, you
can nest any kind of loop (for, while, or do loop). For example: a while loop may contain for loop (as a
nested loop). Or a do loop may contain a while loop which further contains a for loop, etc. Some of the
nested loops example is given below:
4.3 Summary
• Loops are very useful programming constructs which can be used to iterate set of statements.
• Repetition of code sometime requires that we iterate a complete loop several times. This type of
nested repetition is supported by C++ which allows any kind of loop to be nested.
• Loop nesting helps to reduce code-size (as the simple loops do).
101
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
5.3.2 Task-2
Write a C++ program that asks the user to enter a number N .After that, print N lines using asterisk (*) in
a triangle shape as shown below;
Sample Input:
Enter number of lines to print: 6
Sample Output:
*
* *
* **
* ***
* ****
* *****
6. Procedure& Tools
6.1 Tools
Visual Studio 2008.
102
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
void main(){
int list=10;
Output
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
list = 2 * i + 5;
if (i % 2 == 0)
list = list - 3;
}
}
for (int i = 0; i < 5; i++){
cout<<list<<endl;
}
}
103
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)
104
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by the
lab instructor.
Sample Output:
Write a programs that ask the user to type a value and check whether it is prime or not.
105
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The program should compute the result until user don’t enter -1.
7.4 Testing
Test Cases for Practice Task-1:
Sample Input-1 Sample Output-1
P=1, Q=10 6 has maximum of 4 divisors.
Sample Input-2 Sample Output -2
P=11, Q=18 12 has maximum of 6 divisors. 18
has maximum of 6 divisors.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).
106
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
11. Assignment
The lab instructor will give you unseen task of lab 7 as an assignment which is to be submitted by lab 8.
107
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
108
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
a) Lecture No. 15
b) Text Book: Computer Programming by D.S. Malik, second edition, pages: 475—495, and 504—521
109
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Above statements defines an int type array named marks, having size: 5 (capable of storing five values).
In the similar way, you can create array of any basic type, Examples:
Individual array elements can be accessed using same name (array name) along its index. An index (which
must be an integer value) indicates relative position of an element/value within an array. In C++, array
are 0-index based, it means that index of the starting/first element of an array is 0. For example: int
marks[5]; defines an int-type array having five elements, where first value or element will be at index 0,
second on index 1, thirds element at index 2, fourth at index 3, and the fifth element at index 4. Examples:
As you have learned that array elements can be accessed using index values. Therefore, it is common and
a very convenient way to access array elements using loops (mainly for-loop). For example, below shown
code gets input from the user for all five elements of array marks.
110
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
C++ language does not provide any boundary-check; it means C++ does not prohibit access of array
elements beyond the array size. Therefore, it is the responsibility of the programmer to access only valid
array elements (within the limit of array size) otherwise runtime errors or system crash may occur.
Similar to simple variables, arrays can also be initialized. To initialize an array, you have to provide a
comma ( , ) separated list of values (enclosed in braces “{“ and “}” ). All values to be used in initialization
should belong to the same data-type the array processes. In the following example, an array named marks
(int type) is being initialized:
int marks[4] = {87, 90, 73, 91};
char country[9] = {‘P’,’A’,’K’,’I’,’S’,’T’,’A’,’N’,’\0’};
14.2 Summary
• Arrays are very useful data-structure that helps to process large amount of data of same-type.
Arrays simplify coding of the programs (processing large amount of similar data) using fewer code
lines as compared to the non-array based C++ program having same functionality.
• All array elements are accessed using same name, which helps to group related set of values using
same variable-name and results in improved code readability and maintainability.
Sample Input:
Please enter elements for array:
111
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
10 8 5 9 14 7 12 10 1 2
Sample Output:
Maximum Number: 14
5.3.2 Task-2
Write a C++ program that takes five alphabets from the user and ask the user to delete any alphabet. You
should store the alphabets in a char array.
Sample Input:
Please enter 5 alphabets:
PIUDA
Alphabet to be deleted: D
Sample Output:
After Deletion Array:
PIUA
112
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
16.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2)
113
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
114
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Sample Outputs:
Sorted Array
2 4 6 8 10
Sample Outputs:
Ascending order array
2 4 5 8 9
17.5 Testing
Test Cases for Practice Task-1:
Sample Input-1 Output 1(a) Output 1(b)
12 8 2 4 2 5 9 3 2 7 144 64 4 16 4 25 81 4 49 144 81
Sample Input-2 Output 2(a) Output 2(b)
2 8 3 4 10 5 9 3 2 1 4 64 9 16 100 25 81 9 4 1 9 81 9
115
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
116
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
117
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
118
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
119
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
0 1 2 3 4
0
int marks_of_three_students[3][5];
1
Row 2
index
Above C++ code creates a two dimensional array having 3 rows (indexed from 0—2) and 5 columns
(indexed from 0—4). In a 2D array, accessing an array element requires two index values (one for row
and other for column). For examples: cout<<marks_of_three_students[1][3]; Prints value of the
element at 2nd row and 4th column.
As you have learned that it is very convenient to access singe dimensional arrays using for-loops. Similarly,
to conveniently access elements of a 2D array, generally nested for-loop (to generate both the row index
and column index) is used as shown in the below code example:
Similar to one-dimensional arrays, 2D arrays can also be initialized. To initialize a 2D array, you have to
provide comma ( , ) separated lists of values (enclosed in braces “{“ and “}” ) where each list corresponds
120
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
to specific row of the 2D array. All values to be used in initialization should belong to the same data-type
the 2D array processes. In the following example, a 2D named table (int type) is created and being
initialized:
The above C++ statement will create a 2D array having 3 rows and 4 columns (total 12 int type elements).
First list of numbers will be use to initialize row-0, second list of values are placed in row-1, and the third
list at row index-2 as shown below:
0 1 2 3
0 7 9 3 21
1 30 1 9 16 Column
Row index
2 45 87 4 10
index
Suppose that the largest string (for example, name) in your list is 10 characters long and
your list has 5 names. You can declare a two-dimensional array of characters of
5 rows and 10 columns as follows
char list[5][11];
0
1
2
3
4
121
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
24.3 Sorting
Sorting data means arranging values in some pre-defined order based on their numerical value etc.
Sorting an array means to arrange array elements in a certain order (ascending or descending). In
ascending-order, values are arranged in an array such that smaller values are followed by the larger ones,
e.g., 11, 36, 56, 98, 201. In descending-order, values of an array are arranged such that larger values are
placed first then the smaller values e.g., 201, 98, 56, 36, 11. There are many ways (algorithms) to sort an
array, in this course you will learn to sort an array using bubble-sort algorithm.
Bubble-sort algorithm performs N-1 steps, to sort an array. Here N refers to the size of an array (number
of elements in the array). In each step, the complete array is traversed and comparisons are made for pair
of adjacent values. Based on the element’s value and the order to sort (either ascending or descending)
those values may be swapped. For more details, kindly review lecture 15.
5.3.1 Task-1
Write a C++ program that asks the user to enter 10 integer values in an array. After entering 10 elements
arrange in ascending order and display it on output screen.
Sample Input:
Please enter elements for array:
10 8 5 9 14 7 12 10 1 2
Sample Output:
Sorted Array: 14 12 10 10 9 8 7 5 2 1
24.4 Summary
• Arrays are very useful data-structure that helps to process large amount of data of same-type.
Arrays simplify coding of the programs (processing large amount of similar data) using fewer code
lines as compared to the non-array based C++ program having same functionality.
• Sorting is the process of arranging data-items or values in a certain order. One of the main
advantages of using sorting is that it helps arranging data in a more meaningful way or desired
order (based on programmers need).
122
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
5.1.1 Problem description: Write pseudo-code of a program that calculates the sum of odd numbers of a
matrix.First, create a 2D array having 5 rows and 5 columns. After that, the program should sum all those
numbers in the matrix which are odd.In the end, print the calculated sum.
123
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
124
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
26.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2)
125
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
number in the matrix and its location or index values. The program should print the smallest number and
its location (row and column) and also print their count.
Sample Input:
Please enter data for matrix of 5 x 5:
2 6 18 49 8
33 15 11 17 13
8 21 47 37 28
12 12 12 12 12
2 3 4 5 6
27.5 Testing
Test Cases for Practice Task-1
Sample Input-1 Sample output 1
1, 2, 3, 4 1, 10, 1, 4
10, 4, 3, 9 2, 4, 8, 3
3, 3, 7, 5
1, 8, 7, 5 4, 9, 5, 2
4, 3, 5, 2
Sample Input-2 Sample output 2
7, 1, 9, 4
5, 3, 2, 2 Left diagonal sum is larger than right diagonal sum
1, 1, 6, 1
3, 11, 5, 8
126
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
127
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
128
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
129
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You will start your
practical work from section 6 onward in the lab.
130
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
To execute the statements within some function that function is called or invoked. Functions are invoked
by a function–call-statement which consist of function name and information the function requires
before starting its execution called arguments.Before calling a function, it must be declared. A function
declaration consists of function return type, function name, and arguments types. A function declaration
(also called function prototype) does not provide actual implementation or statements a function
executes. Following code show a function declaration:
int
multiplyTwoNums(int,int);
A function definition combines function prototype followed by function body (consisting of one or more
statements). For example following code defines a function named “multiplyTwoNums”:
131
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
In the above code, a function named “multiplyTwoNums” is defined. The return type of the function is
int which shows that the function will return a value which will be of type int. The function takes two
parameters (as shown in above code): num1 and num2 of type int. The parameters listed in the function
definition are also called formal parameters. The opening “{“and closing braces “}” indicates start and
end of the function body. There are two statement in the above shown function body. In the first
statement, an int type variable named “result” is created and the multiplication result (num1 * num2) is
assigned to it. In the second statement, the calculated result is returned to the main program from where
the function was called.
In the below main function, first two numbers are read from the user (using variables n1 and n2). Then,
the function “multiplyTwoNums” is invoked using two parameters (n1 and n2). The value of n1 parameter
will be copied in num1 (formal parameter in the function multiplyTwoNums) , while the n2’s value will
be copied in num2 in the called function. Therefore, we this type of parameter passing is often known as
pass by value.
The main-function (below) first reads two numbers from the user (using variables n1 and n2). Then, the
function “multiplyTwoNums” is invoked using two parameters (n1 and n2). The value of n1 parameter
will be copied in num1 (formal parameter in the function multiplyTwoNums) , while the n2’s value will
be copied in num2 in the called function. Therefore, we this type of parameter passing is often known as
pass by value.
void main ( )
{
int n1, n2, res;
cout<<”\n Enter first number: “;
cin>>n1;
Cout<<”\n Enter first number: “;
cin>>n2;
res = multiplyTwoNums (n1, n2); //Call the
function
132
cout<<”\n Result = “<<res;
}
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
34.2 Pass by reference:
The call by reference method of passing arguments to a function 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 passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value. So
accordingly you need to declare the function parameters as reference types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by
its arguments.
For now, let us call the function swap() by passing values by reference as in the following example –
#include<iostream>
usingnamespace std;
// function declaration
void swap(int&x,int&y);
Put together above code in a file, compiled and executed and see the results.
34.3 Summary
• Functions help to organize code which results in better understanding of the program structure,
easy to fix bugs, and code reusability.
• Functions can be grouped and packaged into some kind of library (for example functions related
to mathematical operations).
• Using functions result in more memory efficient programs; because the variables defined within
the functions are created at the time the function is invoked and they are destroyed when a
function terminates or completes.
Write a pseudo-code in which two functions are called from the main() function. One function receives
parameters from the main () function as by-value (pass-by-value) while the other function receives the
values from the main() function as reference. You need to print the values sent from the main() function
after calling each function and see the difference.
1. Write a function int reverse(int n) which reverse the digits in its parameter and return the
results.
For example, if n is 927, then it would be 729. Apply the function in a program that asks the
user to enter the 10 numbers and reverse them.
2. Write a function that would calculate an item’s sale price based on the item’s purchase price
plus the tax. The function prototype isdouble Sale_Price (double, double).
The first parameter is the purchase price and the second parameter is the tax. The function
will return the sale price of the product. its formula is:
134
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Call the above function in the main() function and pass purchase price and tax from main to the function.
The returned value from the function is displayed in the main () function.
135
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
36.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)
136
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Write a program that implements isVowel that returns the value true if a given character is a vowel
and otherwise returns false. Mention proper function declaration/prototype, and function call from
137
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
mainbody.
Out comes
The outcomes of this lab were:
a) You have learnt functions: pass-by-value
b) You have learnt functions: pass-by-value
c) You have learned the scenarios where to use pass-by-value and where to use pass-by-reference
37.5 You have practiced different tasks how to use pass-by-value and pass-by-
reference. Testing
Test Cases for Practice Task-1
1267 4 digits
1267 1+2+6+7=16
5 120
4 24
138
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
First Number = 8 16
Second Number =2
Operator = *
Do you want to continue [Y/N]=y
First Number=0 16
Second Number=16
Operator=%
Do you want to continue [Y/N]=y
First Number = 4 16
Second Number=12
Operator = +
Do you want to continue [Y/N]=y
First Number=256 16
Second Number =16
Operator=/
Do you want to continue [Y/N]=y
First Number = 32 16
Second Number=16
Operator = -
Do you want to continue [Y/N]=N
139
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
40.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
140
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
141
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You will start your
practical work from section 6 onward in the lab.
2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
8 Evaluation Task 55mins for all assigned task 55mins
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5mins 5mins
6.3 Specialized Tasks 30mins 30mins
7 Practice tasks 60 mins 60mins
Total Time 170 mins
3. Objective of the Experiment
• To get basic understanding of pass by reference using array.
• To learn and practice passing arrays to function.
4. Concept Map
In Lab 11, you have already learned basic concept about arrays and function.
If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received.
4.1. Way-1
Formal parameters as a pointer as follows – this method will learn on lab 14
142
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
.
.
.
}
4.2. Way-2
Formal parameters as a sized array as follows −
4.3. Way-3
Formal parameters as an unsized array as follows −
4.4. Way-4
Formal parameters as 2d-array as follows −
Now, consider the following function, which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed through the
array as follows –
143
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
#include<iostream>
usingnamespace 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};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance,5);
// output the returned value
cout <<"Average value is: "<< avg << endl;
return0;
}
When the above code is compiled together and executed, it produces the following result −
As you can see, the length of the array doesn't matter as far as the function is concerned because C++
performs no bounds checking for the formal parameters.
144
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
5.3.1 Task-1
Write a C++ functions bool isPalindrome(char arr[],int size) which take character array and check
whether array is palindrome or not. Palindrome is a word, phrase, or sequence that reads the same
backwards as forwards. Example madam, racecar etc
6. Procedure& Tools
6.1 Tools
Visual Studio 2008.
In the source file created in the project “findAverageUsingPointers” write following C++ code:
145
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Figure 4:
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2).
146
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to finish
the tasks in the required time. When you finish them, put these tasks in the folder specified by the lab
instructor.
(B) Next, call the function “findEvenSum( int p[] )” and pass the array from the main( ) function. The
“findEvenSum( )” function should calculate the sum of even values stored in the array and then print the
sum on the screen.
(C) Then, from the main( ) call the function “searchThirdSmallest( int p[] )” function by passing the array. The
“searchThirdSmallest( int p[] )” function should find the third smallest value in the array and should return
that value or number to the main( ) program.
(D)After that, the main( ) should call the function “findGreater( intp[] )” by passing the array. The function
“findGreater( int p[] )” should first get an integer value M from the user. Then, it should find and print all
of those numbers which are greater than M (integer value entered by the user).
147
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
(E)Then, the main( ) should call the function “reverseValues( int p[] )” by passing that array. The function
should reverse array values, i.e., value at index 9 should be placed at index 0, value at index 8 should be
moved to index 1 and so on.
(F) In the end, the main( ) should call the function “displayAboveAvarage( int p[] )” by passing that array.
The function should first find the average of array values and then display only those elements which are
greater than average.
IMPORTANT NOTE: In all of the four functions, array must be accessed using pointer notation only
(array access through subscript notation is not allowed).
Sample Inputs:
Enter values in the array:
10
22
54
9
87
102
44
11
99
56
Enter a number: 70
Sample Outputs:
Even Sum of the array is: 288
Third smallest value is: 11
Numbers greater than 70 are: 87, 102, 99
Array with reversed values is: 56, 99, 11, 44, 102, 87, 9, 54, 22, 10
Above average values are: 56, 99, 102, 87, 54
148
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
7.3 Testing
149
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
11. Assignment
Lab instructor will give you unseen task of lab 14 and practice tasks of lab 15 as an assignment to be
submitted by lab 15.
150
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
151
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
In the Lab-7, you have already learned how to deal with data consisting of sequence of characters (text).
Sequence of characters can be manipulated using character arrays (char [ ]). Actually, character array is
the way C language deals with the text data; therefore it is also called “C-String”.
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
e) Lecture No. 21
f) Text Book: Computer Programming by D.S. Malik, second edition, pages: 446—472
152
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The string data-type provides many built-in functions to ease the tasks related to text manipulation. Some
of the example tasks which can be performed using built-in string functions are: text comparison,
combining two text values (concatenation), finding occurrence of some character or sequence of
characters in a text, and replacing/erasing some parts of the text. The ‘Appendix A’ shows some of the
most used string functions along their parameter specification/meaning. String is not the built-in data
type rather it is part of the C++ standard library. Therefore, to use string types you have to include the
corresponding library in the program using include statement:
#include <string>
C++ provides a specialized data-type (called string) to handle or manipulate text. A string type variable
can store same information but provides many useful methods/functions to process the text. C++’s string
type has several other advantages too over C-String (character array) as discussed below:
5.1.1 Problem description: Write pseudo-code of program that finds number of occurrences of a string
(based on at-least two characters) in another string (for example a sentence). The program should get
input in a string “str1” representing a sentence (terminated by”.”). Then, it should ask the user to enter
another string “str2”. In the end program should display the count or number representing total
occurrences of “str2” in “str1”.
Sample Output:
Total Vowels: 6
A: 1
E: 1
I: 2
O: 2
U: 0
5.3.2 Task-2
Write a C++ program that asks the user to enter a string. After that, the program should ask for another
string in a variable named “str_new”. Take another string input in the variable named “str_old”. In the
end, the program should replace the “str_new” with “str_old”. In the end the program prints the update
string.
Sample Input:
Please enter a string: Java programming is a great fun!
Enter word to replace: Java
Enter word to replace with: C++
Sample Output:
C++ programming is a great fun!
154
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
time = 5 mins]
Setup Visual Studio and make a project named “WordCounter”. For setup details please refer to the Lab-
1 section 6.2.
155
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
46.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2)
Sample Inputs:
My name is Ali Raza
Sample Outputs:
1) String length: 19
2) azaR ilA si eman yM
3) My name is Ali Raza Hello World
4) 7
5) my name is ali raza hello world
Sample Inputs:
Enter a number: +92214352682
Sample Outputs:
This number belongs to Karachi
Do you want to enter another number (y/n): n
End of program. Bye!
47.4 Testing
Test Cases for Practice Task-1
Sample Input-1 Y<X is the same as X>= Y
Output-A Length: 26
Output-B Y=>X sa emas eht si X<Y
Output-C Y < X is the same as X>= Y Hello World
Output-D 6
Output-E Y<x is the same as x>=y
157
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
50.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
159
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
160
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
The section 2 presents a table that outlines some major activities and tasks you will do as the part of this
lab. Table 1 also provides the estimated-time for each activity, which will help you to organize your tasks
well. Section 3 presents some of the learning objectives for this lab. Section 4 (“Concept Map”) discusses
and provides a comprehensive introduction of the topic. Section 5 lists the set of home-tasks you are
required to complete before this lab. Section 6 presents a “walkthrough task” that you will do as the first
practical activity during your lab. The walkthrough task has many small steps which you should follow as
directed in-order to complete the task and to get the desired output. After that, you will be ready to work
on some tasks on your own. The section 7 lists practice tasks for this purpose. As the part of section 8,
your lab instructor will give you some tasks at runtime and will evaluate those according to the criteria
mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
2. Activity Time-boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Specialized Tasks 30 mins 30 mins
7 Practice tasks 20 mins for each task 60 mins
8 Evaluation Task 55 mins for the assigned task 55 mins
Total Time 170 mins
4. Concept Map
Every data-item you create in your C++ program has two essential attributes: its value, and memory-
address. For example: when you create a char type variable char ch = ‘A’; one byte of memory is
161
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
reserved against this statement and the initial value is stored in some memory location which has some
specific address as shown in Figure-1
Until now, you have dealt only with the values of variables. To obtain memory address of a variable you
are required to use address-of operator (&) with variable name, for example:
cout << &ch;
The above C++ statement will print the memory address of the variable “ch”. If you want to save this
memory-address in some variable you can do this, but for that you require a special variable that can store
addresses (not the values).
A pointer is a special kind of variable that can store only memory addresses. To create a pointer variable,
you can use asterisk * between its data-type and its name as shown in below statement:
int* ptr;
Above C++ statement creates a pointer named ptr. This pointer variable is created using integer type
therefore ptr can store memory-address of integer variables only. Hence, if you need to store memory
address of some other variable having different type you have to create pointers of those types: char*
ptr2; creates a char pointer (that can store memory addresses of char variables only). Following code
shows examples of different type pointer variables storing memory addresses of different variables.
162
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
There are many potential benefits of using memory-addresses and manipulating values indirectly, some
of these are mentioned below:
• Using pointers, a variable or data-item can be accesses in different parts of a program, where that
data-item may or may not be in the scope. Changing a variable’s value in one segment/part of the
program will also change the variable’s value in other parts of the program and will help to save
space by sharing data-items.
• Pointers can also be used to access arrays and its elements and is very useful in the case where
we need some processing on the array elements in some other part (function) of the program.
This concept is elaborated in detail in next lab.
• Pointers are very useful to share data-items or values across applications. In normal scenario, one
application (C++ program on a computer) does not know or cannot access variables from the other
C++ program on the same computer. Using pointers, applications can exchange memory
addresses and hence can access the data-items which belongs to other applications.
• Until now, we have to declare in advance (at compile time) the amount of memory required for
data items. Pointers help us to manage the allocation of memory dynamically (at run-time).
5.3.2 Task-1
Dry-run (do not use compiler) to evaluate following C++ code and write the output. Moreover, for each
code parts explain in one paragraph how you have achieved the reported output.
163
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
void main( ) void main( )
Char* str=”Pakistan
{ Zindabad”; { int *p, *q, *r;
int Marks = 101; int x = 200, y = 400;
int *Ref = &Marks; p = &x;
(*Ref)--; q = &y;
Marks--; r = p;
cout<<Marks<<”
”<<*Ref<<endl; *r = (*p) + 100;
cout<<*p<<
cout<<(str+7); ” “<<*r<<endl;
cout<<x<<” “<<y<<endl;
} *q=(*r) + (*p);
Output: cout<<x<<” “<<y<<endl;
}
Output:
6.1 Tools
Visual Studio 2008.
To achieve the desired results, you need to follow the following instructions:
164
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by the
lab instructor.
165
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Important Note: Please use pointer notation to access array elements (do not use array notation [ ])
Write a C++ program that creates two double-type one dimensional arrays Radius and Area of size 10
elements each. In array Radius, get 10 input values (radius of 10 circles). The program should calculate the
area of circles for 10 inputted radius values, and store in the corresponding positions in array Area. In the
end, program should display 10 calculated areas for the circles.
Important Note: Use pointer notation to access elements of arrays “Radius” and “Area” (for input,
computation, and output).
Formula: Area = 3.14 * (radius * radius);
Sample Input:
Enter 10 radius values:
3.1
2.5
4.2
33.1
3.6
2.9
3.0
1.24
7.3
2.4
Sample Output:
Calculated area of 10 circles:
30.1754
19.625
3440.2154
40.6944
26.4074
166
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
28.26
4.828
167.3306
18.0864
7.5 Testing
Test Cases for Practice Task-1
167
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
Sample Input Sample Output
Hello World hELLO wORLD
pAKISTAN Pakistan
proGramMinG is FUn PROgRAMmINg IS fuN
PointeRs pOINTErS
168
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
8. Evaluation Task (Unseen) [Expected time = 55 mins]
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s
10.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\
169
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
170
Lab 13: Structures
51. Introduction
In this lab, you will learn about “structures”. A structure is a collection of data-items possibly based on
different data-types. The section 2 presents a table that outlines some major activities and tasks you will
do as the part of this lab. Table 1 also provides the estimated-time for each activity, which will help you
to organize your tasks well. Section 3 presents some of the learning objectives for this lab. Section 4
(“Concept Map”) discusses and provides a comprehensive introduction of the topic. Section 5 lists the set
of home-tasks you are required to complete before this lab. Section 6 presents a “walkthrough task” that
you will do as the first practical activity during your lab. The walkthrough task has many small steps which
you should follow as directed in-order to complete the task and to get the desired output. After that, you
will be ready to work on some tasks on your own. The section 7 lists practice tasks for this purpose. As the
part of section 8, your lab instructor will give you some tasks at runtime and will evaluate those according
to the criteria mentioned in section 9. Section 10 lists some further reading links.
Note: Before coming to the lab, you are required to read Lab contents until section 5. You
will start your practical work from section 6 onward in the lab.
To define a structure, you must use the struct keyword. The struct statement defines a new data-type,
with more than one member, for your program. The format of the struct statement as shown in the
following figure1:
Structures can be passed to function as well. The syntax of passing a structure is given below:
Arrays of structures can be passed to function as well. The syntax of passing a structure is given below:
172
You can define pointers to structures in very similar way as you define pointer to a variable of any data-
type as shown in the following example:
After that, you can store the memory address of a structure variable in the pointer. To obtain the memory-
address of a structure variable use “&” (address-of operator) before the structure name as follows:
Ptr_part = &keyboard;
Moreover, to access the members of a structure using the pointer to that structure, you may use the →
(arrow operator) or * (dereferencing) and “.” (dot) operators combination as shown in the examples
below:
cout<< ptr_part->cost; cout<<(*ptr_part).cost;
A structure is a collection of multiple data types that can be referenced with single name. There are several
advantages of using structures:
• Using structures in a program to group logically related data-items will make it easy to handle
large amount of data.
• Structures simplify passing data to functions. For example, instead of passing multiple variables
individually, you may group those in a structure and pass as a single data-item.
173
55.2 Practices from home
5.3.1 Task-1
Write a program that stores information about laptops in a computer shop. The program stores the
records of 100 laptops. For each laptop, it stores information such as its model, it’s price, and its memory
size. The “Laptop” structure definition is given below. The program should take input for all the 100
laptops in the shop. In the end, the program should display the information of all those laptops which has
price above 60000.
struct Laptop
{
string model;
int price;
int memory_size;
};
5.3.2 Task-2
Write a C++ program for the pseudo-code problem mentioned in section 5.1.1. Modify this problem such
that it should print the names of only those students whose CGPA is above average. Hint: For this, first
you have to find the average CGPA of the class.
In the source file created in the project “EmployeeRecords” write following C++ code:
56.3.2 Compilation
175
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2).
After entering data for all the 10 employees, the program displays names of only those employees whose
basic salary is above 50000.
176
and the relevant grade. It should also find and print the highest score and the name
of the students having the highest score.
Student data should be stored in a struct variable of type studentType, which has
four components: studentFName and studentLName of type string, testScore of type int (testScore is
between 0 and 100), and grade of type char. Suppose that the class
has 20 students. Use an array of 20 components of type studentType.
Your program must contain at least the following functions:
57.4 Testing
Test Cases for Practice Task-1:
1. Your program should output the titles of only the books whose price is above 600.
177
Employee Number : 125 : Arshad
First Name : Hassan : DHA, Isb, Pakistan.
Last Name : Arshad : 0333-25622211
Address: DHA, Isb, Pakistan : 75000
Landline # : 0333-25622211
Salary : 75000
178