0% found this document useful (0 votes)
620 views178 pages

Itp Manual 2019

This document provides instructions for completing labs in an introduction to programming course, including labs on Microsoft Word, PowerPoint, control structures, loops, arrays, functions, strings, pointers, and structures. It outlines the objectives, concepts, procedures, and homework for each lab topic. Time boxes are provided to help students allocate their time for quizzes, setup, walkthrough tasks, and practice tasks for each lab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
620 views178 pages

Itp Manual 2019

This document provides instructions for completing labs in an introduction to programming course, including labs on Microsoft Word, PowerPoint, control structures, loops, arrays, functions, strings, pointers, and structures. It outlines the objectives, concepts, procedures, and homework for each lab topic. Time boxes are provided to help students allocate their time for quizzes, setup, walkthrough tasks, and practice tasks for each lab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 178

Capital University of Science and

Technology Islamabad

LAB MANUAL

INTRODUCTION TO PROGRAMMING

DEPARTMENT OF COMPUTER SCIENCE


1
Capital University of Science & Technology
Islamabad
Department of Computer Science,
Faculty of Computing

Lab Course Development Team

Supervision and Coordination


Dr. Muhammad Tanvir Afzal
Associate Professor
Faculty of Computing

Lab Designers

Mr. Husnain Rafiq


Jr. Lecturer
Faculty of Computing

Mr. Omaid Ghayyur


Jr. Lecturer
Faculty of Computing

2
Capital University of Science & Technology
Islamabad
Department of Computer Science,
Faculty of Computing

Table of Contents

Lab 1 – Introduction to MS word and PowerPoint 4


Lab 2 – Escape Sequences 8
Lab 3 – Control Structures 44
Lab 4 – Nested if-else and Switch 58
Lab 5 – Loops 82

Lab 6 – Nested Loops 97


Lab 7 – Arrays 108
Lab 8 – Multi Dimensional Array and Sorting 118
Lab 9 – Intro to Functions 129
Lab 10 – Functions and Array 143
Lab 11 – Strings 155
Lab 12 – Pointers 164
Lab 13 – Structures 174

3
Capital University of Science & Technology
Islamabad
Department of Computer Science,
Faculty of Computing

Lab Manual for Computer Programming


Lab 1: Introduction to Microsoft Word and Microsoft PowerPoint

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.

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
3 Quiz 45 min 45 min
7.2 Setting-up Microsoft Word 5 min 5 min
7.3 Walkthrough Tasks 2-3 min 70 min
8 Practice tasks 5-20 min 55 min

3. Quiz [Expected time = 45 minutes]

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.

Difference between a document and a presentation


You may recall various font and font size that you have practiced during the MS Word Lab. As presentations
are projected to a group of people, font sizes are larger than for print documents (typical font sizes are 24
to 36 points). The large font sizes limit the content of an individual slide, so the content for each slide should
be carefully selected. Points are often made with abbreviated, incomplete sentences. Complete paragraphs
are even rarer. A single slide often makes a single point. Separate slides are required to integrate the single
points made on other slides.

Following are a few advantages of using PowerPoint for presentations.


• PowerPoint will help students to present their assignments and projects
• PowerPoint in the lecture halls is an effective way of presenting teaching material to students.
• PowerPoint can be used to create interactive presentations containing text, art, animation, and
audio and video elements

6. Homework before Lab


6.1 MS Office Installation
Copy the MS office setup from the \\dataserver\jinnah\ITCLAB$. Try to install it at home. Open MS word
from the start menu and try to do the following task. For opening MS word you can also refer to section 6
of this document.
1

Figure 10: MS Word Help System

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

[Expected time = 5 min]


7. Procedure & Tools
7.1 Tools
• Desktop Computer
• Microsoft Windows operating system, XP or any latest Edition
• Microsoft Word 2007
• Microsoft PowerPoint

7.2 Setting-up Microsoft Word 2007


1. Click on start menu > program files>Microsoft Office> Microsoft Word 2007.

Figure 1: Start Menu to Start MS Word

7.2.1 Walk Through Task for MS Word [Expected time = 50 minutes]


This section is designed such a way that you can complete the following tasks independently. However if
there is any ambiguity you can refer it to the lab instructor.

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

Select ‘Executive Report’ ‘and click ‘Create’.

Figure 2: Insert template

Insert Cover Page:


Pages group is in the far left of the insert tab. You can insert from the three categories for pages which are;
Cover Page, Blank Page, and Page Break as shown in figure 2. These features are useful if you are creating
a professional or long document.

Figure 2: Pages Group

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.

Cover page Exercise: Creating a Cover Page

1. Click the Insert tab to make it the active tab.

Cover Page down


arrow
Figure 3: Cover Page
2. To open the Built-in Cover Page Gallery, click the down arrow to the right of Cover Page in the
Pages group on the Insert tab as shown in figure 4.

Figure 4: Inserting Cover Page

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

Figure 5: 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.

Figure 6: Selecting Rows and Columns


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

Figure 9: Inserting Caption

Write the caption of the figure and click ‘OK’

Figure 10: Illustrations

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.

Figure 11: Table of Contents

Exercise: How to add Table of Contents


1. Apply heading styles to your chosen headings.
2. Move the insertion point to the place where you want the Table of Contents to appear.
3. Click the References tab on the Ribbon and then click the Table of Contents button found in the
Table of Contents group.
4. Click the Table of Contents style you want to use.
5. To customize your TOC, click the Table of Contents button and select Insert Table of Contents Field.
6. Click the Update Table button in the Table of Contents group of the References tab.
7. Click OK to update the table.
8. Save your file after you update the tables.
9. To delete a TOC, select the entire table and press Delete.

13
Figure 8: Adding Table of Contents

Figure 9: Insert 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

Figure 14: Insert Table of Figures

7.2.2 Walk through Task for MS PowerPoint [Expected time = 50


minutes]

Home ribbon

Figure 15: 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.

Figure 16: Layout

1. Make two of the slides as tile slide, third and fourth one as size and content layout and last one
should be blank.

2. Write your name and registration number on first title slide.

3. on second slide write topic as "Computers "

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

Computer Components of Computers


• A computer is a general purpose device that • A general purpose computer has four main
can be programmed to carry out a finite set of components:
arithmetic or logical operations. – the arithmetic logic unit (ALU)
• a sequence of operations can be readily – the control unit
changed, the computer can solve more than – the memory
one kind of problem. – the input and output devices (collectively termed
• The first electronic digital computers were I/O).
developed between 1940 and 1945. • These parts are interconnected by buses, often
made of groups of wires.

Figure 17: Output of Sample Slides

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

To apply a theme to selected slides 4


Click the Slides tab, located on the left side of the window.
1. Hold down the Ctrl key and then click to select the slides to which you want to apply a
theme.
2. Choose the Design tab as shown in arrow 1 of figure 18.
3. Click the More buttons in the Themes group as shown in arrow 2 of figure 18.
4. Right-click the theme you want to apply. A menu appears.
5. Click Apply to Selected Slides

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.

Figure 19: Apply background Styles

19
Figure 20: New Slide with Custom Design

After applying theme and background style 6, presentation would look similar to following slides:

Mouse Monitor Floppy disk drive


 A general purpose computer has four main
keyboard Printer hard disk drive
components:
› the arithmetic logic unit (ALU) joystick Loudspeaker optical disc drive,

› the control unit image scanner Teleprinter


› the memory
Webcam
› and the input and output devices (collectively
termed I/O). graphics tablet

These parts are interconnected by buses, often microphone


made of groups of wires

7/11/2013 4 7/11/2013 5

Figure 21: Output of Custom Design Slides

Animations:

Figure 22: Animations Tab

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.

Figure 23: Custom Animations

• 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.

A. Apply animations on text and images on all slides.


B. Choose Text animation from emphasis on all headings and Diamond from entrance
for all other text bullet by bullet.

Figure 24: Applying 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.

Figure 25: Transition Sound

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.

Figure 26: Managing Slide Transitions

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

8.1 Practice Task 1 [Expected time: 20


min]
Create a Word document on the topic of your choice using templates. The document should contain the
following features.
1. It should contain table of contents.
2. It should have page numbers on each page in the footer.
3. Document must have a Title page with your name and registration number on it.
4. Document must have tables and figures in it with proper captioning.
5. It should contain a table of figures

8.2 Practice Task 2 [Expected Time 15 min]


1. Create a PowerPoint presentation of 8-10 slides. The Topic of presentation will be “Computers

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).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 3 Quiz 40
2 5 Home task 20
3 7.3 Walkthrough Tasks 10
4 8.1 to Practice tasks and Testing 30
8.2

10. Further Reading


10.1 Books
Microsoft word 2007 for Beginners.

25
Capital University of Science & Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 2: Escape Sequences and Variables arithmetic

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.

Relevant Lecture Readings

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.

4.2 Printing special characters


There are certain characters which have special meanings in C++. For example double quotation marks (“),
single quotation mark (‘), question marks (?)etc. For example, you know, the double quotation marks
(“) is used to print a text stream in the cout object. For example the following statement in C++:

cout<<“Hello World”;

willbe print as:


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

will be print as:

“Hello” World

The details of further escape sequences can be found in Appendix A.

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.

4.5 Type Casting

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.

For example using the following statement:

static_cast <int> 7.2

gives us

4.6 Arithmetic Operators

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.

4.7 Unary Operators


Suppose you want to achieve the following

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.).

5. Home work before Lab


5.1 Problem solution modeling
Solve the question number 1 and question 2 on the page number 109 of your text book. You need to bring
this code with you and need to give this code to the lab instructor.This code will be evaluated and it
carries certain marks as can be seen from the section 9, Table 2.You can use escape sequences represented
in Appendix A for formatting purposes.

5.2 Practices from home

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:

*** My Introduction ***


*Name: Your Name *
*DOB: Your Birthdate *
*City: Your city *
*Prog: Your Prog *
*The End*

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.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]

6.2.1 Open visual studio 2008.


1) Go to start menu.
2) Click on Microsoft Visual Studio Folder.
3) Now select Microsoft Visual Studio as shown in the Figure 1.

Figure 1: Selecting Microsoft Visual Studio

6.2.2 Open File Menu.


1) Go to File menu.
2) Select ‘New’, a sub-window will open as shown in the Figure 2.
3) Select Project from the sub-window.

31
Figure 2: Opening File Menu

6.2.3 Select New Project.


1) Click on Project.
2) When you click on Project, a dialog box will open. On the dialog box, there are various options like
Windows Application, Console Application, DLLetc as shown in the Figure 3 (a).
3) From ‘Application Type’, Select Console Application as Figure 3 (b).
4) From additional options, select empty project as shown in the Figure 3 (b).

Figure 3 (a): Selecting New Project

Figure 3 (b): Selecting New Project

6.2.4 Selection of source folder.


After the step 6.2.3, you will see a screen just like shown in the Figure 4.
There would be different options like Add, Cut, Copy etc. Click on Add and a submenu will open.

32
Figure 4: Selecting Source File Folder

6.2.5 Selection of Working File.


Various options would appear. Click on add New Item to select a working file as show in the Figure 5.

Figure 5: Selecting New Item

6.2.6 Selection ofcpp file.


From the various options, click on C++ File (.cpp) as shown in the Figure 6.

33
.
Figure 6: Select CPP file

6.2.7 Give the name to the file.


Write the name of your file in the ‘Name’ field as shown in the Figure 7.

Figure 7: Writing Name of the file

When you click the Add button,A new file would be added to your existing project as shown in the Figure7.

6.3 Walk-through Task [Expected time = 15


mins]
After completing 6.2task, now you are ready for the specialized task. You need to practice the following
task to get basic understanding of developing a small program using escape sequences. When you finish
this task, the following output will be printed.

**********
* Hello *
* World *

To achieve such output, you need to follow the following instructions .

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.

Figure 8: Writing the C++ code

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.

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.

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”
.

6.3.3 Executing the Program


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.

**********
* Hello *
* World *

Figure 11: Final output

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.

7.1 Practice Task 1 [Expected time = 10


mins]
Your need to print the formatted output like shown below:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$****************************$
***********\\\WELCOME to CP*******
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

7.2 Practice Task 2 [Expected time = 10


mins]
Your need to print the formatted output like shown below:

*** My Introduction ***


*Name: Your Name *
*DOB: Your Birthdate *
*City: Your city * *Prog: Your
Prog *
* The End *

7.3 Practice Task 3 [Expected time = 10


mins]
Write a C++ program which would print the following screen as output:

Course Code | Course Name | Credit Hour


CS1114 | ITC | 4
CS1234 | Computer Programming | 4
CS1123 | Cal-I | 4
CS1121 | Algebra | 3
CS1124 | Discrete Maths | 3
Total | 5 |18

7.4 Practice Task 4 [Expected time = 10 mins]


Write a C++ program which would print the following screen as output:

Name | Zubair
ENo | 1234

38
Dept | EE
Rank | Lecturer
Sal | 12,000

7.5 Practice Task 5 [Expected time = 10 mins]


Write a C++ program which would print the following screen as output:

Month | Num of Hours


Jan | 100
Feb | 150
March | 130
April | 90
May | 110
June | 135

7.6 Practice Task 6 [Expected time = 10


mins]
Write a C++ program which would print the following screen as output:

Allownces | Amount
House Rent | 1000
Medical | 1500
TA/DA | 2000 Bonus
| 50000

7.7 Practice Task 7 [Expected time = 10


mins]
Write a program in C++ using escape sequence which would produce the sound of a bell when user enters
the character.

7.8 Practice Task 8 [Expected time = 10 mins]

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

7.9 Practice Task 9 [Expected time = 15 mins]


Write a program that reads two integers and output the result of following operation:

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

7.11 Practice Task 11 [Expected time = 10 mins]


a) Write a program that defines variables a, b, c, d as float and Num2 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.

a * (b + c * d) + ++ Num2 where a, b, c and d are float type


variables.

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)

7.12 Practice Task 12 [Expected time = 10 mins]

Write a program in C++ which would swap the values of two variables without using the third variable.

7.8 Out comes


The outcomes of this lab were:
a) You have learnt escape sequences in C++
b) You have practiced escape sequences in C++

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

Table 2: Testing of Practice Tasks

Practice Tasks Confirmation


T1
T2
T3
T4
T5
T6
T7
T8
T9
T10

41
T11
T2

8. Evaluation Task (Unseen) [Expected time = 60mins]

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).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 5 Procedures and Tools 10
3 6 and 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Books
Text Book:
Computer Programming by D.S Malik, second edition Reference
Books:
1. Beginning C++, the complete language, by Ivor Horton, Wrox Publishers.
2. How to Program in C++, Dietel and Dietel

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".

Name Description Size Range

signed: -128 to 127


Char Character or small integer. 1byte
unsigned: 0 to 255
signed: -32768 to 32767
short int (short) Short Integer. 2bytes
unsigned: 0 to 65535
signed: -2147483648 to
Int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int (long) Long integer. 4bytes 2147483647
unsigned: 0 to 4294967295
Boolean value. It can take one of two values:
Bool 1byte true or false
true or false.
Float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

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

Lab 3: Control Structures (Selection) and Relational Operators

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.

Relevant Lecture Readings:

a) Revise Lecture No. 5 and 6


b) Text Book: Computer Programming by D. S. Malik, Third edition
1. Read pages: 167-174 and 185 - 202
2. Read and understand the solved example starting at page 214.
3. Quick Review starting at page 219.

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

3. Objective of the Experiment


• To get basic understanding of selection control structures (if, if-else, if-else-if).
• To practice different programming task using selections.
• To get knowledge and to use the relational operators.

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.

4.1 One way Selection


Sometimes, we are only interested to make a decision for example, acquiring absolute value of a number.
In this case we just need to convert the negative number to the positive. However, if the number is already
positive then we do not need to do anything.

if (number<0) number=
-1 * number;

4.2 Two way Selection


Apart from the one-way selection, we need to tackle both the cases. For example if the marks of a student
are greater than 50, then the student is passed otherwise the student is failed.

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.

4.3 Compound Statements


In the above statements, we have used only one statement that would be executed after the true of false
condition. However, most of the times, we need to execute multiple statements after the condition
evaluated as true or false. For example, consider the following 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:

Congratulations, you have performed excellent

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

To tackle this situation, we need to do it in the following way.

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.

Furthermore, solve Write the pseudo-code for the following problems:

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”.

5.2 Practices from home

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

6. Procedure & Tools


6.1 Tools
Visual Studio 2008.

6.1 Setting-up Visual Studio 2008 [Expected time = 5


mins]
6.1.1 Open visual studio 2008.
1) Go to start menu.
2) Click on Microsoft Visual Studio Folder.
3) Now select Microsoft Visual Studio as shown in the Figure 1.

48
Figure 1: Selecting Microsoft Visual Studio

6.1.2 Open File Menu.


1) Go to File menu.
2) Select ‘New’, a sub-window will open as shown in the Figure 2.
3) Select Project from the sub-window.

Figure 2: Opening File Menu

6.1.3 Select New Project.


1) Click on Project.
2) When you click on Project, a dialog box will open. On the dialog box, there are various options like
Windows Application, Console Application, DLL etc as shown in the Figure 3 (a).
3) From ‘Application Type’, Select Console Application as Figure 3 (b).
4) From additional options, select empty project as shown in the Figure 3 (b).

49
Figure 3 (a): Selecting New Project

Figure 3 (b): Selecting New Project

6.1.4 Selection of source folder.


After the step 6.2.3, you will see a screen just like shown in the Figure 4.
There would be different options like Add, Cut, Copy etc. Click on Add and a submenu will open.

50
Figure 4: Selecting Source File Folder

6.1.5 Selection of Working File.


Various options would appear. Click on add New Item to select a working file as show in the Figure 5.

Figure 5: Selecting New Item

6.1.6 Selection of cpp file.


From the various options, click on C++ File (.cpp) as shown in the Figure 6.

51
.
Figure 6: Select CPP file

6.1.7 Give the name to the file.


Write the name of your file in the ‘Name’ field as shown in the Figure 7.

Figure 7: Writing Name of the file

When you click Add button, A new file would be added to your existing project as shown in the Figure7.

6.2 Walk-through Task [Expected time = 15 mins]


After completing 6.2 task, now you are ready for the specialized task. You need to practice the following task
to get basic understanding of developing a small program using selections and relational operators.

6.2.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.

52
Figure 8: Writing the C++ code

• Write the output of the following 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.

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”
.

6.2.3 Executing the Program

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.

Figure 11: 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.

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.

7.2 Practice Task 2 [Expected time = 30 mins]


Write a program that takes the marks from the user and tells the grade corresponding to the marks. The
marks and corresponding grades are mentioned below:

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.3 Practice Task 3 [Expected time = 20 mins]


Write a program which reads salaries of 10 employees of an organization. The program will tell, what the
maximum salary is and what the minimum salary is

7.4 Out comes


The outcomes of this lab were:
a) You have learnt control structures (selections) in C++
b) You have practiced different tasks how to use selections.
c) You have practiced different relational operators

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

Practice Tasks Input Output Confirm


6.3 Num1 = 30 Line 1: a is not equal to b
Num2= 5 Line 2: a is not less than b
Line 3: a is greater than b
Line 4: a is not equal to b

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

7.6 Evaluation Task (Unseen) [Expected time = 60 mins]

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).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 5.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 and 8 Practice tasks and Testing 70

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$\

Appendix – A – Relational Operators


Operator Description Example

Checks if the value of two operands is equal or


== (A == B) is not true.
not, if yes then condition becomes true.
Checks if the value of two operands is equal or
!= not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater
> than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
>= than or equal to the value of right operand, if (A >= B) is not true.
yes then condition becomes true.
Checks if the value of left operand is less than
<= or equal to the value of right operand, if yes (A <= B) is true.
then condition becomes true.

57
Capital University of Science and Technology
Islamabad
Department of Computer Science,
Faculty of Computing

Lab 4: Nested If-else and Switch

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.

Relevant Lecture Readings:

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

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.1 Setting-up Visual Studio 5 mins 5 mins

59
6.2 Specialized Tasks 30 mins 15 mins
7 Practice tasks As mentioned against each task 70 mins
Total Time 170 mins

3. Objective of the Experiment


• To get basic understanding of nested-if conditions
• To get basic understanding of logical operators.
• Where and when to use ‘nested-if’ and ‘logical-and’.
• To practice how the nested-if and logical operators are used in a C++ program.

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.

4.1 Nested-if statement


When we want to make decisions based on more than one conditions then one way of achieving this is
using nested-if condition. For example, consider the following example. A student is given a scholarship, if
and only if his/her percentage is more than 70% and he/she is below 16 years of age. Here, you need to
notice that there are two conditions and if both conditions are fulfilled then the student will be given
scholarship, otherwise, no scholarship will be awarded. To accomplish such task you can use the concept
of nested-if in the following way.

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:

if (percentage>=70 && age <16)


{
cout<<”Congratulations! You are eligible for the scholarship”;
}

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)

4.3.1 Scenario 1: Nested-if and Logical-and (&&) are similar Consider


the followings two codes:

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.

4.3.2 Scenario 2: Nested-if is better than Logical-and (&&)

Consider the following code:

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 && age <16)


{
cout<<”Congratulations! You are eligible for the scholarship”;
}
if (percentage>=70)
{
cout<<”Your percentage is more than 70”;
}

4.3.3 Scenario 3: Logical-and (&&) is better than nested-if


Consider the following code.

if (percentage>=70 && age <16)


{
cout<<”Congratulations! You are eligible for the scholarship”;
}
else
{ cout<<”Sorry, you did not get the
scholarship”;
}

You will not like to write it 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”;
}

4.4 Logical-or (||)


Apart from logical-and (&&), there is another logical operator which is known as logical-or (||). You can
refresh your concepts of logical operators by looking into the appendix A available at the end of this lab. In
the logical-or (||), the condition is considered as true if any of the conditions are true. For example, re-writing
the previous example with logical-or (||) would look like the following

if (percentage>=70 || age <16)


{
cout<<”Congratulations! You are eligible for 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.

4.5 Logical-not (!)


The logical-not (!) is used before any condition and it will reverse the evaluation of the condition. For
example, if the condition is true, the logical-not (!) will make it false, if the condition is false, then the
logical-not (!) will make it true. Consider the following example. logical-not (!):

if (!(5==5)) cout<<”5 is not


equal to 5”;

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
(!)

if (percentage>=70 && (!(age <16)))


{
cout<<”Congratulations! You are eligible for the
scholarship”;
}

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.

4.6 Switch Statement


Remember, in your previous lab, you have studied a control structure, selection, using if-statement.
However, there is another way selection or branching statement in c++, known as switch statement. The
if-statement can be used to evaluate logical-expressions (remember logical-operators that you studied
in the Lab 4). However, the switch-statement do not require the evaluation of logical expressions. The
switch statement is used to p ick from number of alternatives provided by the system. The general syntax
of the switch statement is as follows:

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.

4.7 The break statement


In this section, we will give a basic example of switch statement with and without the break statement.
Consider that we want to print the following output where user have multiple options, out of which the
user can pick one option to be executed at one time.

Enter 1 to purchase products


Enter 2 to sale products Enter 3 to
see the profit statement =

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:

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”;
break;
case 2:
cout<<”You selected the option to sale products”;
break;
case 3:
cout<<”You selected the option to see the profit statement”;
break; default:
cout<<”You have selected the wrong value”;
}

When user enters the value 1, the user will get the following output:

You selected the option to purchase products

When user enters the value 2, the user will get the following output:

You selected the option to sale products

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:

You selected the option to purchase products


You selected the option to sale products
You selected the option to see the profit statement

When user enters the value 2, the user will get the following output:

You selected the option to sale products


You selected the option to see the profit statement

When user enters the value 3, the user will get the following output:

You selected the option to see the profit statement

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:

You selected the option to purchase products


You selected the option to sale products

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:

You selected the option to sale products

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:

You selected the option to see the profit statement

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.

char option; cout<<”Enter character E to change Rupee into equivalent value in


Euro”;
cout<<”Enter character D to change Rupee into equivalent value in dollar”;
cout<<”Enter the character R to change Rupee into equivalent value in Riyal”;
cin>>option;

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

There are two important points to be noted here:


1) For the character value, you need to enclose it in a single quotation mark.
2) The program will work fine for the upper case characters only. If user enter “d” in lowercase
rather than upper case, then the program will output “cout<<”Wrong input”;. To tackle
both uppercase and lowercase character, you can write the following code:
switch(option)
{ case ‘E’:
case ‘e’:
cout<<”You selected the conversion from Rupee to Euro”;
break;
case ‘D’:
case ‘d’:
cout<<”You selected the conversion from Rupee to Dollar”;
break;
case ‘R’:
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.

4.9 The relational operator in the expression


In the expression of the switch statement, one can use relation operators which will be evaluated as true
of false, for example consider the following example followed by a discussion on it.

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

4.10 Complex expression in the switch statement


In the previous section, you have learned how an integer, character, and relational operator can be used
in the expression of switch statement, however, in this section, you will experience that the use of
complex expression is allowed in the switch statement. Consider the following example. The user enters
a number and program finds the digit at unit place and displays it.

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

4.11 Bitwise Operators


The bitwise operators works on the bits of the data. Most of the time, you do not need them, however,
you must be aware of these operators. You can use them when you want to reduce the space of your
program. For example, consider, an example, suppose you want to store the data of eight students
whether they are passed or failed. According to your knowledge until now, you can use eight Boolean
type variables to store such data where the true means that the student is passed and false mean that
the student is failed (Remember, a Boolean type variable can store only two values: true or false). Each
Boolean type variable will hold one byte in the memory. However, to make your program more space
efficient, you can use only one byte to store this data. The comparison of code using both Boolean
variables and one byte has been given below.

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.

5.2 Practices from home

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:

Press 1 for converting the number of days into hours


Press 2 for converting the number of days into minutes

Based on the option entered by user, your program should calculate and display the results
accordingly.

6. Procedure & Tools


6.1 Tools
Visual Studio 2008.
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.

6.2 Walk-through Task [Expected time = 15 mins]


In this specialized task, you will learn that how the practice task 2 of third lab can be achieved with the help
of nested-if statement.
• Write the output of the following code

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:

Greater than and equal to 90 A grade


Greater than and equal to 80 B grade
Greater than and equal to 70 C grade
Greater than and equal to 60 D grade
Less than 60 F grade

Use nested if-else to achieve this task.

• 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

6.2.1 Writing Code


Remember you created a file with name “myprog” in the task 5.1.8. now write the following code as shown
in the Figure 1. Write the code in the intended form as shown.

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.

Figure 3: 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”.

6.2.3 Executing the Program

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.

Figure 4: Final output

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

7.1 Practice Task 1 [Expected time = 20 mins]


Write a program that reads 10 integers and then finds and prints all the numbers that are divisible by 5.

7.2 Practice Task 2 [Expected time = 20 mins]


1. Write a program which calculates the monthly Budget of a person. The program will read the
monthly salary of the person. Then give following options:

Press 1 to calculate gas bill charges


Press 2 to calculate electricity bill charges Press
3 to calculate fueling charges.
Press 4 to calculate house rent charges

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)

7.3 Practice Task 3 [Expected time = 30 mins]


Write a program which asks the user to open a bank account either Current or Savings. Your program will
display the following menu at the start:

Press 1 for Current Account


Press 2 for Savings Account

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:

Press a for Deposit the money


Press b for withdrawing the money

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.

7.4 Practice Task 4 [Expected time = 20 mins]

Write a program that ask the users to enter three characters. Then the program should display the following
menu

1. Sort in Ascending order


2. Sort in Descending order

The program should perform sorting of these three characters in ascending or descending order as per the
user requirement.

7.5 Practice Task 5 [Expected time = 15 mins]


Write a program that displays the following menu to the user:
Press 1 for Permanent Employee
Press 2 for Daily wages Employee

After selecting the appropriate employee calculate salary and medical charges for the employees. Following
menu would be displayed:

Press a to calculate Salary


Press b to calculate medical charges.

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.7 Out comes


The outcomes of this lab were:
a) You have learnt nested-if control structures in C++
b) You have practiced different tasks how to use selections.
c) You have practiced logical operators

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.

Table 2: Testing of Practice Tasks

Practice Tasks Sample Input Sample output Confirmation

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

7.1 Enter product type: Sales tax = 14.97


1 (for toothpaste)
2 (for shampo)
1
Enter price = 499

7.2.1 Account Type: 1 Available Balance: 1500


Amount: 2000
Deposit Amount: 1000
Withdraw amount: 1500
7.2.2 Account Type: 2 Rs. 500 must be available
Amount: 5000 after withdraw transaction,
Deposit Amount: 500 please enter the amount
Withdraw amount: 5400 again.
Withdraw amount : 4500 Available balance = 1000
T4 Enter the number
Number: 2 Number is not odd Number is
Number: 3 not divisible by 5 Number is
Number1: 6 prime
Number2: 5 Addition is 11
Number1: 8
Number2: 6 Subtraction is 2
Number1: 5
Number2: 6 Multiplication is
30
T5 Enter your choice
Your choice: 1
Enter your salary
5000 Your medical allowance is: Rs.
Enter your choice 500
Your choice: 1
Enter your salary
8000
Your house rent is: Rs. 800
T6 Enter the first number First Number is 4
4 Second number is
Enter the second number 6 6

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).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 5.1 Problem Modeling 20
2 5.3 Home work 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Books Text
Book:
Computer Programming by D.S Malik, second edition Reference
Books:
1. Beginning C++, the complete language, by Ivor Horton, Wrox Publishers.
2. How to Program in C++, Dietel and Dietel

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

Lab 5: Repetition Structure Loops

82
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 5: Repetition Structures - Loops

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.

Relevant Lecture Readings:

a) Lecture No. 11 and 12


b) Text Book: Computer Programming by D. S. Malik, pages: 232-289
c) Revise Quick Review available at 289-290

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
8 Evaluation Task As mentioned 60 mins
5.1 Evaluation of Design 20 mins 20 mins

83
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

6.1 Setting-up Visual Studio 5 mins 5 mins


6.2 Specialized Tasks 30 mins 15 mins
7 Practice tasks As mentioned against each task 70 mins
Total Time 170 mins

3. Objective of the Experiment


• To get basic understanding of loops
• To learn about post-condition and pre-condition loops.
• To learn different possible expressions which can be used in loops To practice how the
loops can be used in the program.

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

cout<<” Welcome to Cp Course\n”;


cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;
cout<<” Welcome to Cp Course\n”;

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 Pre-condition Loops


The pre-condition loops first checks the condition, if the condition is true then the statement
associated with loops are executed, otherwise not. There are two pre-conditions loops such as: for-
loop and whileloop. First we will discuss for-loop followed by the other pre-condition loop : while-
loop.

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:

a) First the initialization will be done.


b) Then condition will be checked. Then the statements associated with this loop will be executed.
At the moment, there is only one statement that is associated with this loop.
c) After the statement execution, the increment will be done i.e i will become 2.
d) Then the step (b) and (c) will be repeated until i becomes 21. At that stage the condition will be
false and the loop will terminate. Then the next statements will be executed in a flow.

There are some important points to be noted:


a) If we want to associate another statement with loop, then we must enclose the statements in
brackets, otherwise only the first statement will be considered as associated with the loop. This

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.

Sentinel-Controlled while loop


Sometimes, we do not know how many times we will execute a loop. For example, we want to sum
the marks of all registered courses of a student. However, we do not know how many courses a typical
student has registered. For example, for a student ‘a’, we want to execute the loop 4 times, while for
a student ‘b’, we want to execute the loop 5 times etc. in this scenario, we define a sentinel or read
sentinel from the user, and when this sentinel is entered the loop is terminated. For example, consider
the following scenario:

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

5. Home work before Lab


5.1 Problem solution modeling
Write the pseudo-code that will find the sum of all even numbers for the numbers between 2 and
1000.You need to bring this code with you and need to give this code to the lab instructor. This code
will be evaluated and it carries certain marks as can be seen from the section 9.

5.2 Practices from home

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.

6. Procedure & Tools


6.1 Tools

Visual Studio 2008.

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.

6.2 Walk-through Task [Expected time = 15 mins]

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.1 Writing Code


To achieve such output, you need to follow the following instructions. Write the following code as shown
in the Figure 1. Write the code in the intended form as shown:

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.

90
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

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.

Figure 3: 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”
.

6.2.3 Executing the Program


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.

91
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

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

7.1 Practice Task 1 [Expected time = 10 mins]


Write a program that asks the user to type 10 integers. The program must compute how many even and
odd numbers were entered along with number that are divisible by 7.

7.2 Practice Task 3 [Expected time = 15 mins]


1. Write a program that enter a number from user and display its factorial. e.g. factorial of 5 is
1 X 2 X 3 X 4 X 5=120. Where is N<=10.

7.3 Practice Task 4 [Expected time = 15 mins]


Write a program in C++ using repetition structures to print the following pattern. You are not allowed
to use nested loops.

****
***-
**--
*---

92
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

7.4 Practice Task 5 [Expected time = 15 mins]


Put the program from 7.1 until 7.5 in a do-while loop Once the program gives the output, the user
will see another message “Do you want to continue again *Y/N+”, if user enters ‘Y’ or ‘y’, the program
will execute again, however, on pressing any key other than ‘Y’ or ‘y’, the program will terminate.

7.6 Out comes


The outcomes of this lab were:
a) You have learnt loops control structures in C++
b) You have learned different scenarios to use for, while, and do-while loops
c) You have practiced different tasks how to use loops.

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.

Table 2: Testing of Practice Task 1


Practice Task 1 Confirmation
S.No. Inputs Expected Output
1. 1,1,1,1,1,1,1,1,1,1 10 Odd Numbers
2. 2,4,5,6,7,8,9,10,2,1 6 Even Numbers, 4 Odd
Numbers
3. 2,4,6,8,10,12,14,16,18,20 10 Even Numbers

Table 3: Testing of Practice Task 2


Practice Task 2 Confirmation
S.No. Inputs Expected Output
1. Number = 1 Power 1
=2

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

Table 4: Testing of Practice Task 3


Practice Task 3 Confirmation
S.No. Inputs Expected Output
1. Number=1 1*1=1
Limit= 1
2. Number 5 5*1=5
Limit= 2 5*2=10
3. Number = 10, Error.
Limit = -1
4. Number =4 Power=5 4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
5. Number=100 No output
Limit=0

Table 5: Testing of Practice Task 4


Practice Task 4 Confirmation
S.No. Expected Output

94
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

1. This program should display the figure shown in


section 7.4

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.

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).

Table 8: Evaluation of the Lab


Sr. No. Task No Description Marks
1 5.1 Problem Modeling 20
2 5.3 Home work 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Books
Text Book:
Computer Programming by D.S Malik, second edition
Reference Books:
1. Beginning C++, the complete language, by Ivor Horton, Wrox Publishers.
2. How to Program in C++, Dietel and Dietel

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

Lab 6: Nested Loops

Lab 6: Nested Loops

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.

Relevant Lecture Readings:

a) Lecture No. 13—14


b) Text Book: Computer Programming by D.S. Malik, second edition, pages: 281—289, 473—495 c)
Quick review at pages 289-290

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 30 mins for each task 60 mins
8 Evaluation Task 55 mins for the assigned tasks 55 mins
Total Time 170 mins

3. Objective of the Experiment


• To get basic understanding of loops.
• To practice the use of nested loop structures.

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,

How will you code this program? Like below?


#include<iostream>
using namespace std;
void main()
{ 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<<’, ’;

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:

do { for(int i=0;i<10; i++)


cin>>a; { cin>>n;
for(inti=0;i<a;i++) total = i * n;
cout<<(i*i)<<” ”; while(total>20)
{
} while(a>10); cout<<”\nHello World”; total--
;
}
}

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).

5. Homework before Lab


5.1 Problem Solution Modeling
Write the pseudo-code of the following task. You are required to bring this code with you and submit
to your lab instructor.

101
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

5.1.1 Problem description


Write pseudo-code of program that finds “Prime Numbers” in the given range. First, ask the user to enter
two numbers M and N. Then, find prime numbers in the range M → N. Display all the prime numbers on
the screen.

5.2 Practices from home


5.3.1 Task-1
Write a program that can able to print the following pattern:
*
***
*****
*******
*********

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

6.2 Setting-up Visual Studio 2008 [Expected time =


5 mins]
Setup Visual Studio and make a project named “Print Triangle”. For setup details please refer to the Lab1
(Section 6.2.)

6.3 Walkthrough Task [Expected time = 30


mins]
• Write a C++ program that prints the following pattern on the screen.

• Dry run the below program.


• Write the output of the following code (assume code is error free)

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

6.3.1 Writing Code


In the source file created in the project “Print Triangle” write following C++ code:

103
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 1: C++ code for PrintTriangleprogram

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)

6.3.3 Executing the Program


A sample output after running the program is shown below:

104
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 2: Final output of Print Triangle program.

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.

7.1 Practice Task 1 [Expected time =


30 mins]
Write a program that can able to print the following pattern:
*
***
*****
*******
*********

7.2 Practice Task 2 [Expected time =


20 mins]
Write a C++ program that prints on the screen following diamond shape with given series of numbers.

Sample Output:

7.3 Practice Task 3 [Expected time = 30 mins]

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.

Test Cases for Practice Task-2:


The output of the screen should show the diamond pattern with exact numbers series as given in sample
output of tasks 2.
Practice Tasks Confirmation
T1
T2
T3

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).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1 and 7.2 Practice tasks and Testing 35

106
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

4 8 Evaluation Tasks (Unseen) 20


5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

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

Lab 07: Arrays

108
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 07: Arrays


11. Introduction

In this lab, you will learn about arrays

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.

Relevant Lecture Readings:

a) Lecture No. 15
b) Text Book: Computer Programming by D.S. Malik, second edition, pages: 475—495, and 504—521

12. 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 min for all assigned task 55 mins
Total Time 170 mins

109
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

13. Objective of the Experiment


• To get familiarize with the concept of arrays.
• Problem solving using one dimensional array and sorting array values.
• Introducing single-dimensional arrays in particular arrays.

14. Concept Map


14.1 Single-Dimensional Arrays
An array is basically a collection of data-items or values all based on same data-type. For example: A
student’s marks in five courses in a semester: 78, 91, 83, 67, and 89; represent a collection of five int type
numbers where each value represents his/her marks in a certain course. An array is a structured data-
type (collection of values) of some fixed size (number of elements/values) where all values are of same
type. To define an array you have to mention its type, name and size (number of elements/values the
array will contain). For example:
int marks[5];

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:

float GPA[4]; //To store GPA of last 4 semesters


double area_of_circles[10]; //To store area of 10 circles
char student_name[30]; //To store name of size 30 (maximum characters)

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:

cin>>marks[2]; //Gets marks from user and stores at 3rd


position

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.

for(int i=0;i<5; i++)


cin>>marks[i];

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.

15. Homework before Lab


15.1 Problem Solution Modeling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.

15.1.1 Problem description


Write pseudo-code of program that creates char array of 5 elements of type char. The array contains 5
vowels a, e, i, o, u. Ask the user to enter characters of their choice until the user enters a vowel. After user
enters a vowel the program should stop taking inputs. And display all the entered characters by user. To
check either a character entered is vowel or not your program should check the entered characters from
the array on each input. For example user enter q, d, f, a. The output should be q, d, f.

15.2 Practices from home


Write a C++ program that asks the user to enter 10 integer values in an array. After entering 10 elements
find the maximum number and display it on output screen.

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

16. Procedure & Tools


16.1 Tools
Visual Studio 2008.

16.2 Setting-up Visual Studio 2008 [Expected


time = 5 mins]
Setup Visual Studio and make a project named “StudentAvg”. For setup details please refer to the Lab-1
section 6.2.

16.3 Walkthrough Task


[Expected time = 30 mins]
Write a C++ program that reads marks of a class (having 5 students) from the user and places them in an
array of type float. After that, it should compute average marks obtained by the class. In the end, display
student number and their marks for all those students who got marks above average.

To achieve such output, you need to follow the following instructions.

112
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

16.3.1 Writing Code


In the source file created in the project “StudentAvg” write following C++ code:

Figure 1: C++ code for student average program.

16.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2)

16.3.3 Executing the Program


A sample output after running the program is shown below:

113
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 2: Final output student average program.

17. 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 told by your lab
instructor.

17.1 Practice Task 1 [Expected time = 20 mins]


Write a C++ program that creates two one dimensional arrays “A” and “B” of size 20 elements each. The
main program should get the input in the array “A” from the user and initialize array “B” with values “0”.
Your program should calculate the (number -2) of each element of array “A” and should store in the square
value in corresponding positions (index) in the array “B”. In the end, the main program (main function)
prints the calculated values of array “B”. Also display the values in array B which are Odd (if any).

17.2 Practice Task 2 [Expected time = 20 mins]


Write a C++ program that creates an array “A” having 5 elements (in the main function). Then, the program
asks the user to enter values in this array. After that, the program should replace each array element
which is odd with an even value (by adding 1 to it). In the end, the main program (“main”) shows the
updated array elements in ascending order.
Sample Inputs:
Enter 5 elements in array A:
4 5 9 8 2

114
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Sample Outputs:
Sorted Array
2 4 6 8 10

17.3 Practice Task 3 [Expected time = 20 mins]


Write a C++ program that creates an array “A” having 5 elements (in the main function). Then, the program
asks the user to enter values in this array. After that, the program should ask question from user are you
wanted to sort ascending or descending order kindly enter your choice that’s you want to search in the
array, also compute the sum of array for the ascending order and difference of array for the descending
order.
Sample Inputs:
Enter 5 elements in array A:
4 5 9 8 2
Press 1 for ascending and 2 for descending order
1

Sample Outputs:
Ascending order array
2 4 5 8 9

17.4 Out comes


After completing this lab, student will be use arrays in the program to store and manipulate large amount
of data.

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

Test Cases for Practice Task-2:


Sample Input Sample Output (a) Sample Output (b)
3 15 19 18 12 4 16 20 18 12 4 12 16 18 20
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
5 8 13 6 1 6 8 14 6 2 2 6 6 8 14

115
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Test Cases for Practice Task-3:


Sample Input Sample Output (a)
3 15 19 18 12 Ascending order array
Press 1 for ascending and 2 for descending order 19 18 15 12 3
2

Test Cases for Practice Task-3:

Practice Tasks Confirmation


T1
T2
T3

18. Evaluation Task (Unseen) [Expected time =


55 mins]
The lab instructor will give you unseen task depending upon the progress of the class.

19. 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).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1, 7.2, and 7.3 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

116
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

20. Further Readings


20.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

117
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 08: Multi-Dimensional Arrays and Sorting

118
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 08: Multi-Dimensional Arrays and Sorting


21. Introduction
In this lab, you will learn and practice multi-dimensional arrays, particularly 2-dimensional arrays. In
addition to the multi-dimensional arrays, arranging data in an array (sorting), you will learn about
functions too.

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.

Relevant Lecture Readings:

c) Lecture No. 17—18


d) Text Book: Computer Programming by D.S. Malik, second edition, pages: 504—521

22. 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 all assigned task 55 mins
Total Time 170 mins

119
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

23. Objective of the Experiment


• Introducing multi-dimensional arrays in particular 2D arrays.

24. Concept Map


As you have already learned in the previous lab (LAB-08), arrays are basically a collection of data-items or
values all based on same data-type. In C++, we can create arrays having single-dimension (a list), two
dimensions (a table), and even more than two dimensions. This lab will focus on two-dimensional arrays
and will also provide basic introduction of functions.

24.1 Multi-Dimensional Arrays


A 2 Dimensional (2D) array represents set of rows and columns in the form of a table. To declare a 2D
array, you have to provide two size values; first size represents number of rows while the second size
values represents number of columns of a 2D array.
Column index

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:

for(int i=0;i<3; i++) //For Row index


for(int j=0;j<5; j++) // For Column index
cin>>marks_of_three_students[i][j];

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:

int table[3][4] = {{7, 9, 3, 21}, {30, 1, 9, 16},{45, 87, 4,


10}};

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

24.2 Multi-dimensional character array:


Suppose that you need to perform an operation, such as alphabetizing a list of names. Because
every name is a c-string(), a convenient way to store the list of names is to use an array. Strings in
C++ can be manipulated using either the data type string or character arrays (C-strings).

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

It’s very easy to take input in two dimensional character arrays.

121
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

for(int i=0;i<3; i++) //For Row index


cin>>list[0];

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

25. Home work before Lab


25.1 Problem Solution Modeling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.

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.

26. Procedure& Tools


26.1 Tools
Visual Studio 2008.

26.2 Setting-up Visual Studio 2008 [Expected time =


5 mins]
Setup Visual Studio and make a project named “SumRowCol”. For setup details please refer to the Lab-1
(Section 6.2).

26.3 Walkthrough Task [Expected time =


30 mins]
Write a C++ program which calculates sum of each column and row separately. For this, first create a 2D
array (3 rows, 5 columns) and then ask the user to input values in the array. After that, first calculate sum
of each row separately and display that sum. Then, calculate sum of each column separately and display
that sum on the screen. To achieve such output, you need to follow the following instructions.

26.3.1 Writing Code


In the source file created in the project “SumRowCol” write following C++ code:

123
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 1: C++ code for sum Row-Col program

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)

26.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 2: Final output of sum Row-Col program.

27. 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.

27.1 Practice Task 1 [Expected time =


20 mins]
Write a C++ program that creates a 2D array having 4 rows and 4 columns. Then, ask the user to input
values for the 2D array or matrix. After that, the program should calculate transpose of a matrix.
Transpose is basically calculated by changing rows of matrix into columns and columns into rows. After
calculating, display the final matrix.

27.2 Practice Task 2 [Expected time = 20 mins]


Write a program that creates and then reads a matrix of 5 rows and 5 columns of type int. while reading;
the program should not accept values greater than 100. For any entered value greater than 100, the
program should ask for input repeatedly. After reading all numbers, the system should find the smallest

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.

27.3 Practice Task 3 [Expected time =


30 mins]
Write a C++ program that displays the row numbers of a matrix containing at least two even numbers.
First, the program should create a 2D array (5 rows, 5 columns). Then, ask the user to input values in the
matrix or 2D array. After that, program should display row number (or index) which have less then 2 prime
numbers. If no row (of the matrix) contains at least two prime numbers then the program should display
the message “No row found containing two prime numbers”.

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

Sample Output:Row number 1, 4 contains prime numbers less than 2.

27.4 Out comes


After completing this lab, student will be able to use string data type and its function for text manipulation.

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

Test Cases for Practice Task-2

126
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Sample Input-1 Sample output 1


13, 15, 76, 85 13, 10, 1, 74
10, 4, 73, 91 15, 4, 8, 3
1, 8, 17, 52 76, 73, 17, 15
85, 91, 52, 26
74, 3, 15, 26
Sample Input-2 Sample output 2
77, 1, 19, 74 77, 54, 11, 32
54, 3, 22, 62 1, 3, 19, 89
11, 19, 6, 11 19, 22, 6, 15
74, 62, 11, 85
32, 89, 15, 85

Practice Tasks Confirmation


T1
T2
T3

28. Evaluation Task(Unseen) [Expected time = 55 mins]

29. 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).
Table 2: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1, 7.2, and Practice tasks and Testing 35
7.3
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

127
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

30. Further Readings


30.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

128
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 09: Introduction to Functions and Pass by Value and Pass


by Reference

129
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 09: Introduction to Functions and Pass by Value and


Reference
31. Introduction
In the previous lab, you have acquired the basic understanding of functions, why functions are used? What
are function prototype, function definition and function calling. However, the current lab will introduce
you about the difference between pass-by-value and pass-by-reference. The function arguments can be
passed either by-value or by-reference. You will learn the scenarios where a typical type of passing is
beneficial.

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.

Relevant Lecture Readings:

a) Lecture No. 18 and 19


b) Text Book: Computer Programming by D. S. Malik, pages: 354-375
c) Revise Quick Review available at 402-404

32. 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 all assigned task 55 mins
Total Time 170 ns

130
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

33. Objective of the Experiment


• Basic understanding of functions and their usage.
• Learning how to structure code to improve code-readability and code reuse.
• To get basic understanding of functions: pass-by-value
• To get basic understanding of functions: pass-by-reference
• To understand the difference between pass-by-value and pass-by-reference.
• To practice how to write programs to achieve pass-by-value and pass-by-reference.

34. Concept Map


In the previous lab, you have learnt the detailed concepts of defining and calling functions. This lab will
introduce you about how the parameters can be passed using pass-by-value and pass-by-reference. When
you pass parameters by value than the actual parameters are copied to formal parameters. The changes
made within the function are not visible to the place from you called the function; however, if you pass
parameters by reference, then the address of formal parameters is copied to the actual parameters. This
means that both formal and actual parameters are pointing to the same memory location. The changes
made within the function in the formal parameters are visible to the actual parameters. You know that a
function can return only one value; however, if you pass parameters using pass-by-reference, then you
can return more than one values from a function.

34.1 Introduction to Functions


A function is a set of statements that are grouped together and given a specific name (function name).
Every C++ program must have at least one function and it should be named “main”. Execution of every
C++ program starts always from the main function. In addition to the main function, the programmer can
also create its own functions. User program can be divided into functions making the program easy to
understand and re-use the code. A basic guideline to create a function is that each function should
perform a specific task. You can create as many functions as required in your program.

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

int multiplyTwoNums(int num1,int


num2)
{
int result = num1 * num2;
return result;
}

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.

// function definition to swap the values.


void swap(int&x,int&y){
int temp;
temp = x;/* save the value at address x */
x = y;/* put y into x */
y = temp;/* put x into y */
return;
}

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

int main (){


// local variable declaration:
int a =100;
int b =200;
cout <<"Before swap, value of a :"<< a << endl;
cout <<"Before swap, value of b :"<< b << endl;
/* calling a function to swap the values using variable
reference.*/
133
swap(a, b);
cout <<"After swap, value of a :"<< a << endl;
cout <<"After swap, value of b :"<< b << endl;
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

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.

35. Homework before Lab

35.1 Problem Solution Modeling


Write the pseudo-code of the following task. You are required to bring this code with you and submit
to your lab instructor.

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.

35.1.1 Practices from home

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:

Tax Amount= purchase price *(Tax Rate/100)


The formula of calculating the final price of an item
is: Sale Price = Purchase price + Tax Amount

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.

36. Procedure& Tools


36.1 Tools
Visual Studio 2008.

36.2 Setting-up Visual Studio 2008 [Expected time = 5


mins]
Setup Visual Studio and make a project named “SumRowCol”. For setup details please refer to the Lab-1
(Section 6.2).

36.3 Walkthrough Task [Expected time = 30 mins]


After setting up the project, you are ready to write the code and execute it. In this task we will try to swap
two numbers using pass-by value and pass-by reference swap functions. The main function creates two
variables of int type and assigns the values 10 and 20. Then swap functions are called and variables are
passed by value and by reference. Please note the difference in both cases.

36.3.1 Writing Code


To achieve such output, you need to follow the following instructions. Write the following code as shown
in the Figure 1. Write the code in the intended form as shown.

135
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 2: Writing the C++ code

36.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)

36.3.3 Executing the Program


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.

136
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 3: Output of Walkthrough Task

37. 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.

37.1 Practice Task 1 [Expected time = 20


mins]
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:

Tax Amount= purchase price *(Tax Rate/100)


The formula of calculating the final price of an item
is: Sale Price = Purchase price + Tax Amount

37.2 Practice Task 2 [Expected time = 20 mins]


Write the definition of a void function that takes as input two decimal numbers. If the first number
is nonzero, it outputs the second number divided by the first number; otherwise, it outputs a message
indicating that the second number cannot be divided by the first number because the first number is 0.

37.3 Practice Task 3 [Expected time = 30 mins]


Write a function to print the diamond of size n. n will be taken input from user and pass as an argument
in function by reference.

37.4 Practice Task 4 [Expected time = 20 mins]

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

Sample Inputs-1 Sample Outputs-1

1267 4 digits

Test Cases for Practice Task-2

Sample Inputs-1 Sample Outputs-1

1267 1+2+6+7=16

Test Cases for Practice Task-3


Sample Inputs-1 Sample Outputs-1

5 120
4 24

Test Cases for Practice Task-4


Sample Inputs-1 Sample
Outputs-1

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

Practice Tasks Confirmation


T1
T2
T3
T4

38. Evaluation Task(Unseen) [Expected time = 55 mins]

39. 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).
Table 2: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10

139
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

3 7.1, 7.2, and Practice tasks and Testing 35


7.3
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

40. Further Readings

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

Lab 10: Functions and Arrays

Lab 10: Functions and Arrays


1. Introduction
In this lab, you will learn about passing variables and arrays into the function.

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.

Relevant Lecture Readings:

a) Lecture No. 27—28


b) Text Book: Computer Programming by D. S. Malik, second edition, Pages: 792—800 and 803—
815

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

void myFunction(int *param) {

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 −

void myFunction(int param[10]) {


.
.
.
}

4.3. Way-3
Formal parameters as an unsized array as follows −

void myFunction(int param[]) {


.
.
.
}

4.4. Way-4
Formal parameters as 2d-array as follows −

void myFunction(int param[][10]) {


.
.
.
}

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 –

double getAverage(int arr[],int size){


int i, sum =0;
double avg;

143
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

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


sum += arr[i];
}
avg =double(sum)/ size;
return avg;

Now, let us call the above function as follows −

#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 −

Average value is: 214.4

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. Homework before Lab


5.1 Problem Solution Modelling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.

5.1.1 Problem description:


Write pseudo-code of a program that creates an integer array of 30 elements. After that, the program
should pass this array (using reference pointer) to the function called “Find_Selective_Sum”. The function
“Find_Selective_Sum” should input two values (P and Q) from the user. After that, function
“Find_Selective_Sum” should calculate sum of all those elements which are between P and Q. In the end,
the calculated sum is returned to the main program.

5.2 Practices from home

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.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “findAverageUsingPointers”. For setup details please refer
to the Lab-1 section 6.2.

6.3 Walkthrough Task [Expected time = 30mins]


Write a C++ program that creates (in main function) an array of type float having 10 elements (for 10
students). After that, pass that array to the function named “inputValues” which takes input in that array.
For passing array, you should use reference pointers. After that, create another function named
“findAverage” and pass that array (using reference pointer) to that function. The “findAverage” function
should calculate the average of the marks of the 10students and update or report the average using a
reference variable (Note: Do not use return) to the main function. 6.3.1Writing Code

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).

6.3.3 Executing the Program


A sample output after running the program is shown below:

146
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 5: Final output of find average program

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.

7.1 Practice Task 1 [Expected time = 60mins]


Write a C++ program that creates an integer array having 30 elements. Then, implement 6 functions as
shown below:
(A) First, call the function “readArray( int p[] )” by passing the array from the main program. The “readArray(
)” function should get input from the user for each array element.

(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

7.2 Practice Task 2 [Expected time = 20mins]


Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main
function). After that, pass that array to a function called “Find_Max_Divisors” using reference pointer.
The function “Find_Max_Divisors” should find (and return) in the array that number which has highest
number of divisors. In the end, the main function displays that number having highest number of divisors.
.

148
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

7.2 Out comes


After completing this lab, students will be able to use pointers as formal parameters and passing arrays
to the functions using pointers.

7.3 Testing

Test Cases for Practice Task-1


Sample Inputs Sample Outputs
Array: 20, 89, 7, 132, 45, 65, 13, 78, 98, 11 Even sum: 328
Number: 35 Third smallest value: 13
Numbers greater than 35 are: 89, 132, 45, 65, 78, 98
Reversed Array: 11, 98, 78, 13, 65, 45, 132, 7, 89, 20
Above average values are: 98, 78, 65, 132, 89

Sample Inputs Sample Outputs


Array: 40, 9, 12, 87, 43, 87, 91, 78, 32, 17 Even sum: 162
Number: 40 Third smallest value: 17
Numbers greater than 40 are: 87, 91, 78
Reversed Array: 17, 32, 78, 91, 87, 43, 87, 12, 9, 40
Above average values are: 78, 91, 87, 87

Practice Tasks Confirmation


T1 (A)
T1 (B)
T1 (C)
T1 (D)
T1 (E)

149
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

8. Evaluation Task (Unseen) [Expected time = 55mins]


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).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1 Practice tasks and Testing 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Additional Material on Pointers:
Book: Starting out with C++ by Tony Gaddis, sixth edition Pages: 491—534

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

Lab 11: Manipulating Sequence of Characters using C++


“string” Data-type

151
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 11: Manipulating Sequence of Characters using


C++ “string” Data-type
41. Introduction

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.

Relevant Lecture Readings:

e) Lecture No. 21
f) Text Book: Computer Programming by D.S. Malik, second edition, pages: 446—472

42. 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 30 mins for each task 60 mins
8 Evaluation Task 55 mins for all assigned task 55 mins
Total Time 170 mins

43. Objective of the Experiment


• To get basic understanding of string data-type.
• To get familiarize and practice basic string functions.

152
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

44. Concept Map


To deal with sequence of characters, C++ provides its own specialized data-type based on string class. In
C++, std::string is the standard way to deal with the sequence of characters. A string variable can store
sequence of characters, letters, symbols (*, $, %), and non-keyboard characters such as escape sequences
[Lab-1]. Some of the examples of text that a string variable can store are: “Hello”, “BC050102”, “I Love
C++ Programming!”, “Grade:\n\tA”.

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>

44.1 String manipulation using specialized data-type


C/C++ provides character data-type to deal with individual character values. In C, character arrays are
used to deal with more than one characters or text. This character array is often referred as C-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:

44.1.1 Memory Storage


One of the main drawbacks of using character array is that it has fixed size in memory, whether or not you
utilize full allocated space. For example: if you create a character array based on 80 elements (characters),
in memory 80 bytes will be reserved for it. If you store “Pakistan” in this character array only 9 array
elements (including ‘\0’ or null character) will be utilize, other 71 bytes will remain allocated but un-
utilized. Strings have variable sizes and the amount of space they take up in memory depends on the
length of the string.

44.1.2 String Functions


C++ string type provides many built-in functions to ease text handling. That’s why using string type instead
of character arrays will ease writing programs in less time and with shorter source code. Furthermore,
you do not have to implement major text manipulation functionalities by yourself. In “Appendix A” list of
basic string functions is provided.

45. Home work before Lab


45.1 Problem Solution Modeling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.
153
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

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”.

45.2 Practices from home


5.3.1 Task-1
Write a C++ program that asks the user to enter a string. The program should count total number of vowels
in the input string. The output of the program should report vowel count for each vowel character (a, e, i,
o , u), and total or sum of all vowel count.
Sample Input:
Please enter a string: i love C++ programming!

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!

46. Procedure & Tools


46.1 Tools
Visual Studio 2008.

46.2 Setting-up Visual Studio 2008 [Expected

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.

46.3 Walkthrough Task


[Expected time = 30 mins]
Write a C++ program that counts total words in a sentence. First, get input in a string variable “prg” for a
paragraph (terminated by enter key). Your program should count total number of words in the paragraph
(using find function of string) and print that value on screen as follows:
You entered 20 words for the paragraph.

To achieve such output, you need to follow the following instructions.

46.3.1 Writing Code


In the source file created in the project “WordCounter” write following C++ code:

.Figure 1: C++ code for word counter program

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)

46.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 2: Final output of word count program

47. 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.

47.1 Practice Task 1 [Expected


time = 30 mins]
Write a C++ program that asks the user to enter a string value in a variable named “Str”. The input string
should be of size 20 characters (minimum). Next, apply following operation (in sequence) on the input
string:
1) Find and print the length of the string.
2) Display string in reverse order.
3) Concatenate “Hello World” to the string.
4) Count number of words in updated string.
5) Convert whole string in lowercase.

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

47.2 Practice Task 2 [Expected


time = 30 mins]
Write a C++ program which repeatedly asks the user to enter their contact numbers. Create a string
variable named “Phone_No” and take the input in the following pattern: “+92423672123” where the first
156
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
three characters represent country code (e.g., +92 as shown in the example pattern), next two characters
(e.g., 42 according the shown example number) represent the city code, while next 7 characters represent
the actual number.
Your task is to display appropriate messages for the numbers belonging to three cities: Islamabad (having
city code 51), Lahore (city code 42), and Karachi (city code: 21). Any number having different country code
or city code must be reported as “Un-known number“. Please also ensure that the user must enter the
number according to the shown pattern only and the size of the input string must be 12 characters.

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.3 Out comes


After completing this lab, student will be able to use string data type and its function for text manipulation.

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

Test Cases for Practice Task-2


Sample Input Sample Output Remarks
+9251111878787 Unknown Number Number is over 12 characters
+92333540061 Unknown Number Unknown city code
-92515254722 Unknown Number Wrong country code format
+43515254722 Unknown Number Unknown country code
+92515254722 This number belongs to Islamabad -
+92423454211 This number belongs to Lahore -
+92218123319 This number belongs to Lahore -

Practice Tasks Confirmation


T1
T2

157
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

48. Evaluation Task (Unseen) [Expected time =


55 mins]
The lab instructor will give you unseen task depending upon the progress of the class.

49. 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).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1 and 7.2 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

50. Further Readings


50.1 Strings Tutorial
A comprehensive list of string functions can be found at
http://www.prismnet.com/~mcmahon/Notes/strings

50.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

Appendix A – Basic String Functions


String Functions Description
size( ) Returns the length of the string
length( ) Returns the length of the string (same as size( ) function)
clear( ) Delete the contents of the string. Reset it to an empty string
empty( ) Return true if the string is currently empty, false otherwise
at (X) Return the character at position X (integer) in the string. Similar to using the [ ]
operator
substr(X, Y) Returns a copy of the substring (i.e. portion of the original string) that starts at
index X and is Y characters long. Both X and Y are integers.
substr(X) Returns a copy of the substring, starting at index X of the original string and going
to the end
158
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing
append(str2) Appends str2 (a string or a c-string) to the calling string
str1.compare(str2) Performs a comparison. A negative value return means str1 comes first. Positive
means str2 comes first. 0 means both strings are same.
str.find(str2, X) Returns the first position at or beyond position X (integer value), where the string
str2 is found inside of str sting variable.
str.find(CH, X) Returns the first position at or beyond position X where the CH (a character
variable) is found in str
str.insert(X, CH) Inserts the character CH into string str starting at position X (integer value).
replace(X, N, str) Replace N number of characters in the calling string, with value of “str” string
variable starting at position X (integer value).

159
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 12: Pointers

160
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Lab 12: Pointers


1. Introduction
Until this lab, you have learned to deal with values stored in variables. In this lab, we introduce the concept
how to acquire memory-address of a variable or an array. After obtaining the memory addresses, you will
learn to use this memory address to operate on the actual values or contents of that data-item.

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.

Relevant Lecture Readings:

a) Lecture No. 25—26


b) Text Book: Computer Programming by D.S. Malik, second edition, pages: 791—816

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

3. Objective of the Experiment


• To get basic understanding of pointer variables.
• To get familiarize and practice different program based on pointer variables.
• Manipulating arrays using pointers.

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

Figure 1: a char-type variable in memory.

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.

int marks = 91;


int* ptr_marks = &marks;

float CGPA = 3.2;


float* ptr_CGPA = &CGPA;

4.1 Dereferencing Pointers


C++ uses the * operator in yet another way with pointers. Whenever you use asterisk * operator in front
of a pointer variable this evaluates to its contents or value. Example:

int marks = 84;


int* ptr_marks = &marks;
cout<< *p; //will print 84 on the screen

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. Home work before Lab

5.1 Problem Solution Modeling


Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.

5.1.1 Problem description:


Write pseudo-code of a program that sorts (ascending) an integer array of size 20. First, create an integer
array having 20 elements. Then, create an integer pointer that points to that array. After that, get input
values from the user in that array and sort it (ascending). Please note: All array accesses must be done
using pointer notation.

5.2 Practices from home

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. Procedure & Tools

6.1 Tools
Visual Studio 2008.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “SwapValuesUsingPointers”. For setup details please refer
to the Lab-1 section 6.2.

6.3 Walkthrough Task [Expected time = 30 mins]


Write a C++ program that swaps values of two float type variables A and B. For swapping you can use
third variable temp to store values temporary. All accesses to the variables (A, B, and temp) should be
made through pointer notation only. In the end, print the values of variables (A, B) on the screen. Please
also note that during input (cin) and output (cout) the variables must be accessed through pointers only.

To achieve the desired results, you need to follow the following instructions:

6.3.1 Writing Code


In the source file created in the project “ValueSwap” write following C++ code:

164
Capital University of Science and Technology Islamabad
Department of Computer Science,
Faculty of Computing

Figure 2: C++ code for swapping two values using pointers

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2)

6.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 3: Final output of value swap program

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

7.1 Practice Task 1 [Expected time = 20 mins]


Write a C++ program that creates an integer array of a month and get the size of this array from the user.
The program should take input values (temperatures for all days of the month) from the user. The program
should display lowest temperature, highest temperature, and average temperature for the month.

Important Note: Please use pointer notation to access array elements (do not use array notation [ ])

7.2 Practice Task 2 [Expected time = 20 mins]


Write a C++ program called “Eliminate evens”. First, create an array named “values” having 10 elements
of integer type. Then, the program should ask the user to enter values (which may be negative as well as
positive) in this array. After that, the program replaces each array element which is odd with an even
value. Positive odds should be replaced by even values by adding 1 to them while the negative odd values
must be replaced by adding -1 to them. In the end, the program shows the updated array.
Please Note: Array input, output, and other accesses must be done using pointer notation only (no
subscript [ ] notation allowed).

7.3 Practice Task 3 [Expected time = 20 mins]

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.4 Out comes


After completing this lab, student will be able to use string data type and its function for text manipulation.

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

Test Cases for Practice


Task-2
Sample Sample Sample Sample Sample Sample
Inputs-1 Outputs-1 Inputs-2 Outputs-2 Inputs-3 Outputs-3
4 4 65 66 51 52
-6 -6 -37 -38 22 22
55 56 -11 -12 98 98
-7 -8 76 76 -7 -8
9 10 60 60 82 82
12 12 56 56 32 32
14 14 89 90 9 10
-21 -22 -41 -42 -3 -4
101 102 97 98 7 8
3 4 11 12 -1 -2

Test Cases for Practice Task-3


Sample Sample Sample Sample
Inputs-1 Outputs-1 Inputs-2 Outputs-2
3.2 32.1536 2.2 15.1976
8.4 6.42099 4.67 68.4799
1.43 221.558 6.43 129.823
2.91 26.5898 9.91 308.373
5.31 88.5358 1.31 5.38855
3.77 44.6285 5.31 88.5358
5.57 97.4182 5.75 103.816
4.2 55.3896 1.23 4.75051
1.31 5.38855 6.39 128.213
7.2 162.778 1.2 4.5216

Practice Tasks Confirmation


T1
T2
T3

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

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1, 7.2 and 7.3 Practice tasks and Testing 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings

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

Lab 13: Structures

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.

Relevant Lecture Readings:

g) Lecture No. 29—30


h) Text Book: Computer Programming by D. S. Malik, second edition, Pages 609—648.

52. 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 60 mins 60 mins
8 Evaluation Task 55 mins for all assigned task 55 mins
Total Time 170 mins

53. Objective of the Experiment


• To get basic understanding of structures and their use.
• Manipulating structures using pointers.
• Writing and reading structures to/from a file.

54. Concept Map


A structure in C++ is used to group logically related data-items. Just like arrays, all contained values within
the structure are accessed using the same i.e., structure name. The main difference between an array and
structure is that array combines data-items of same data-type while a structure may or may not have
data-items based on same data-type.
The data items in structure are called structure members, elements, or fields. Unlike arrays, each structure
member must be accessed using its name instead of index. A structure may have elements of varying sizes,
for example: a student structure having member such as name (string type), age (int type), gender (char
type), and CGPA (float type). The members of a structure are arranged in memory in the similar order as
they are defined in the structure definition.

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:

To access any member of a structure, we use the member access operator “ . “

part keyboard; // Declare keyboard of type


part
keyboard.cost = 480;
In order to store the 10 parts, array of structure should be created and you can access the each part data
separately.

part keyboard[10]; // Declare keyboard of type part


keyboard[8].cost = 480;

Structures can be passed to function as well. The syntax of passing a structure is given below:

void printData(part keyboard){ . . . }

Arrays of structures can be passed to function as well. The syntax of passing a structure is given below:

void printData(part keyboard[]){ . . .


}
1
Object Oriented Programming in C++ 4th Edition by Robert Lafore

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:

part *ptr_part; //pointer to structure “part”

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.

55. Home work before Lab


55.1 Problem Solution Modeling
Write the pseudo-code of the following task. You are required to bring this code with you and submit to
your lab instructor.

5.1.1 Problem description:


Write pseudo-code of a program that collects information about students of a class. Arrange this
information in the form of array of structures. The array should be of size 30 to store information for the
entire class. For each student, you should store information such as: name, registration number, age,
CGPA, and address. Get input from the user for all the 30 students. In the end, print names of only those
students whose CGPA is above 3.

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.

56. Procedure & Tools


56.1 Tools
Visual Studio 2008.

56.2 Setting-up Visual Studio 2008 [Expected


time = 5 mins]
Setup Visual Studio and make a project named “EmployeeRecords”. For setup details please refer to the
Lab-1 section 6.2.

56.3 Walkthrough Task


[Expected time = 30 mins]
Consider the following nested structure with name employee. The structure has members: employeeID
(int type), employeeName (string type), age (int type), gender (char type), and salary (employeeSalary
type). The employeeSalary structure contains three member elements: basicSalary (float type),
houseRent (float type), and medical (float type). The program should define an array of 10 employees in
the main( ) function. It is required to take input for all the 10 employees from the user. The program
should then display records of all those employees having basic salary greater than 50000.

struct employee struct employeeSalary


{ int employeID; {
string employeName; float basicSalary:
int age; float houseRent;
char gender; float medical;
employeeSalary };
salary;
}; 174
56.3.1 Writing Code

In the source file created in the project “EmployeeRecords” write following C++ code:

Figure 1: Code for Employee Records program.

56.3.2 Compilation

175
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section
6.3.2).

56.3.3 Executing the Program


A sample output after running the program is shown below:

Figure 2: Entering data for 30 employees

After entering data for all the 10 employees, the program displays names of only those employees whose
basic salary is above 50000.

57. 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.

57.1 Practice Task 1 [Expected time = 30 mins]


Write a program that maintains the record for 15 books of a student. In each record (for a single book), it
should store book id, book title, author and its price. The program should take input for all the 10 books
and store the data in array of structure. In the end, the program should display (after reading from the
file) titles of only those books whose authors are same

57.2 Practice Task 2 [Expected time = 30 mins]


Write a program that reads students’ names followed by their numerical scores.
The program should output each student’s name followed by the numerical score

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:

i. A function to read the students’ data into the array.


ii. A function to assign the relevant grade to each student (use your own
judgment to assign grades A, B, C, D or F based upon the students’ scores).
iii. A function to find the highest score.
iv. A function to print the names of the students having the highest score
.

57.3 Out comes


After completing this lab, students will be able to handle collection of information using structures.

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.

Test Cases for Practice Task-2:


Your program should take employee data from user as shown in the sample inputs. The program should
display records of only those employees whose salary is between 50,000 and 80, 000and they are resident
of Islamabad. A sample input and output of the program is given below:
Sample Inputs Sample Output
Employee Number : 123 Record Found of employee number “123”
First Name : Ahmed : 123
Last Name : Waqas : Ahmed
Address: G-9, Islamabad. : Waqas
Landline # : 051-4441234 : G-9, Islamabad.
Salary : 65000 : 051-4441234
Employee Number : 124 : 65000
First Name : Waqar
Last Name : Ahsan
Address: Gulbarg, Lahore Record Found of employee number “125”
Landline # : 042-8881234 : 125
Salary : 40000 : Hassan

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

Practice Tasks Confirmation


T1
T2

58. Evaluation Task (Unseen) [Expected time = 55 mins]


The lab instructor will give you unseen task depending upon the progress of the class.

59. 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).

Table 2: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4.1 Problem Modeling 20
2 6 Procedures and Tools 10
3 7.1 and 7.2 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

60. Further Readings


60.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

178

You might also like