0% found this document useful (0 votes)
352 views191 pages

Itp Manual 2021-Merged

This document provides instructions for completing labs in Introduction to Programming using Microsoft Word and PowerPoint. It outlines the tasks and time allotted for each lab activity, including quizzes, setting up the software, walkthrough tasks, and practice exercises. The labs aim to teach students how to use templates, styles, and formatting in Word, and how to design slides, insert multimedia, and manage slideshows in PowerPoint.

Uploaded by

Abdul Basit
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)
352 views191 pages

Itp Manual 2021-Merged

This document provides instructions for completing labs in Introduction to Programming using Microsoft Word and PowerPoint. It outlines the tasks and time allotted for each lab activity, including quizzes, setting up the software, walkthrough tasks, and practice exercises. The labs aim to teach students how to use templates, styles, and formatting in Word, and how to design slides, insert multimedia, and manage slideshows in PowerPoint.

Uploaded by

Abdul Basit
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/ 191

Capital University of Science

and Technology Islamabad

LAB MANUAL
V1.1 Spring 2021

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

Mr. Salman Ahmed


Lecturer
Faculty of Computing

Lab Designers

Ms. Aliza Tanveer


Jr. Lecturer
Faculty of Computing

2
Table of Contents

Lab 1: Introduction to Microsoft Word and PowerPoint ........................................................................................ 4


Lab 2: Introduction to Microsoft Excel ................................................................................................................. 26
Lab 3: Escape Sequences and Variables arithmetic .............................................................................................. 50
Lab 4: Control Structures (Selection) and Relational Operators........................................................................... 69
Lab 5: Nested If-else and Switch ........................................................................................................................... 84
Lab 6: Repetition Structure Loops ...................................................................................................................... 106
Lab 7: Nested Loops............................................................................................................................................ 119
Lab 8: Arrays ....................................................................................................................................................... 129
Lab 9: Multi-Dimensional Arrays and Sorting ..................................................................................................... 159
Lab 10: Introduction to Functions and Pass by Value and Pass by Reference .................................................... 172
Lab 11: Functions and Arrays.............................................................................................................................. 185
Lab 12: Manipulating Sequence of Characters using C++ “string” Data-type .................................................... 201
Lab 13: Pointers .................................................................................................................................................. 210
Lab 14: Structures ............................................................................................................................................... 222

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

Lab 1: Introduction to Microsoft Word and PowerPoint

4
Lab 1: Introduction to Microsoft Word and
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 25 min 25 min
7.2 Setting-up Microsoft Word 5 min 5 min
7.3 Walkthrough Tasks 2-3 min 60 min
8 Practice tasks 30 min 60 min

3. Quiz [Expected time = 25 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 \\172.16.0.2\softwares$\Office2019 1910 12130.20272 x64\Setup. 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 1. 1

1. Click on the Help tab to go to Microsoft Office Help as shown in Figure 1. 1. The Office Help is
really good. After opening the help try to search the shortcut key for following tasks in MS Word.
• 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

7. Procedure & Tools [Expected time = 5 min]

7.1 Tools
• Desktop Computer
• Microsoft Windows operating system, XP or any latest Edition
• Microsoft Word
• Microsoft PowerPoint

7.2 Setting-up Microsoft Word 2007


1. Click on start menu > type “word” > select “open” as shown in Figure 1. 2.

Figure 1. 2: Start Menu to open MS Word

7.2.1 Walk Through Task for MS Word [Expected time = 30 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.

7
Go to File menu and click ‘New’. Select template you want to use or search for the required templates as
shown in Figure 1. 3.

Figure 1. 3: Insert Template

Search ‘Project status report ‘and select one as shown in Figure 1. 4.

8
Figure 1. 4

Click “create” as shown in Figure 1. 5.

Figure 1. 5

9
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 1. 6. These features are useful if you are
creating a professional or long document.

Figure 1. 6: Pages Group

Cover Page is the title page of the document. Word 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 as shown in Figure 1. 7.

Figure 1. 7

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 1. 8.

10
Figure 1. 8: Insert 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 1. 9: Style Group

The fourth group on the Home ribbon is the Style group as shown in Figure 1. 9. 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

11
Figure 1: Table

Word provides tables option for placing data in a more formal way.
1. Click on table in insert tab. (Figure 1. 7)
2. To add Rows and Columns, select top to bottom for rows & left to right for columns (Figure 1. 10)
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 1. 10: Insert Table

Illustrations
Using Illustrations, you can add pictures of all types and styles to your document as shown in Figure 1. 11.

Figure 1. 11: Illustrations


12
Picture
The first selection in Illustrations is Insert a picture from a file. When you click on this a window will open
to browse to a photograph or other picture you have saved on your computer as shown in Figure 1. 12.

Figure 1. 12: Pictures

Smart Art
Smart Art allows you to add different graphs in your document as shown in Figure 1. 13.

Figure 1. 13: Smart Art

Insert Caption
Click “References” tab to make it active as shown in Figure 1. 14.

13
Figure 1. 14: References

Select a picture and click “Insert Caption”. Add a suitable caption for text and then click OK as shown in
Figure 1. 15.

Figure 1. 15: Insert Caption

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 1. 16: Table of Contents

14
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 as shown in Figure 1. 16.
4. Click the Table of Contents style you want to use as shown in Figure 1. 17.
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.

Figure 1. 17: Insert Table of Contents

15
Figure 1. 18: 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 as shown in Figure 1. 19 .

Figure 1. 19

4. Click on ‘Insert table of figure’. A table of figures dialog box will appear as shown in Figure 1. 20.

16
Figure 1. 20

5. Choose your desired style and click ‘OK’. Table of figures will be created as shown in Figure 1. 21.

Figure 1. 21: Table of Figures

7.2.2 Walk through Task for MS PowerPoint [Expected time = 30 minutes]

Home ribbon
Click on “Home” tab to make it active as shown in Figure 1. 21.

Figure 1. 22: Home Ribbon

17
Slides
Slides section allows you to add slides, manipulate it and change its layout etc.

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 drop-down pane of the PowerPoint window as
shown in Figure 1. 23.

Figure 1. 23: Layouts

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.

5. Output of above steps in shown in Figure 1. 24.

18
Figure 1. 24: 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.
– Select the theme you want to apply as shown in Figure 1. 25.

Figure 1. 25: Themes

To apply a theme to selected slides


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 figure.
3. Click the More buttons in the Themes group.
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.

Background:
You can add a dramatic effect to your theme by applying a background.
1. Choose the Design tab.
2. Click the Format Background button.

19
3. Click the background you want as shown in Figure 1. 26.

Figure 1. 26: Changing background of theme

Animations:
Animations allows you to add different animation styles to your slides. These styles can be applied to
slides and the text in slides as well as shown in Figure 1. 27.

Figure 1. 27: Animations

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 1. 28.

20
Figure 1. 28: 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 Add Animation button. The Animation pane appears.
5. Choose the type of effect you want. A submenu appears.

6. Click the effect you want. PowerPoint applies the effect.


21
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 as shown in Figure 1. 29.
2. Click the down arrow next to the Property field on the Custom Animations pane and then
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 duration field on the Timings 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 1. 29: Applying Animation on start method

To preview the animation, click the Play button on the Custom Animations pane.

Explore all of them yourself and animate your text and slides. Slideshow should display presentation in
effective manner with animations on each slide.

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.

• In the animation pane, select the item you want to add sound to and click on the drop-
down button, and then do one of the following:
22
▪ 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 2: Transition sound

Select transition sound for the presentation that must not be annoying for the audience.

Transition Speed
It sets the speed of the slide transition to be slow, medium or fast.

Figure 3: Managing Slides Transition

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.

Slide Zoom-in/Zoom-out
To zoom in on a particular slide while playing the slideshow press Ctrl and +.
To zoom out, press Ctrl and -.

Adding a Scrollbar in a slide


Scrollbars are used when the content on a slide is very large and all that content must be present
in the same slide.
23
To add scrollbar to a slide, follow the following steps:
1. Click the "File" tab on the ribbon. Click "Options" to open the PowerPoint Options dialog box.

2. Click "Customize Ribbon" and click the check box next to "Developer." Click "OK."

3. Click the "Developer" tab and click the "Text Box" button in the Controls group as shown in
Figure 1. 30.

Figure 1. 30

4. Click and drag over your slide to add the text box.

5. Right-click the text box and click "Properties" to open


its Properties dialog box.

6. Type or copy and paste the text box's contents into the
Value box.

7. Click the drop-down box next to "ScrollBars" and select


"2 - frmScrollBarsVertical" as shown in Figure 1. 31.

8. Click the drop-down box next to "WordWrap" and


select "True" as shown in Figure 1. 31.

9. Click the drop-down box next to "MultiLine" and select


"True" as shown in Figure 1. 31.

10. Press "F5" to preview the presentation with the


scrollbar.

Figure 1. 31: Properties

24
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 30 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 30 min]


1. Create a PowerPoint presentation of 8-10 slides. The Topic of presentation will be “Computers
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
Word 2016 For Professionals Dummies
By Dan Gookin

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

Lab 2: Introduction to Microsoft Excel

26
Lab 2: Introduction to Microsoft Excel
1. Introduction
In this lab you will learn the basic working of Microsoft Excel. Like MS Word and MS PowerPoint, MS
Excel is a part of Microsoft Office Suite and there are several features that you may find similar to MS
Word and MS PowerPoint. We will however, concentrate only on those features that are specific to
MS Excel.

MS Excel is an incredibly powerful tool for getting meaning out of vast amounts of data. But it also
works really well for simple calculations and tracking almost any kind of information. Microsoft Excel
can be used to create and manage business transactions that deal with accounting. The task you can
complete with Excel ranges from preparing a simple family budget, preparing a purchase order, create
an elaborate 3-D chart, or managing a complex accounting ledger for a medium size business.

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
3 Quiz 15 min 30 min
5.1 Understanding of 10 min 10 min
Spreadsheet
6.2 Setting-up MS Excel 5 min 5 min
6.3 Walkthrough Tasks 10 min each 90 min
7 Practice tasks 10 min 30 min

3. Quiz [Expected time = 30 min]

4. Objectives of the lab


• Using MS Excel Menu and Toolbar
• Understanding different pointer shapes
• Understanding the gird, rows, columns and cells.
• Sorting the data in rows or columns
• Performing calculations on the data in MS Excel
• Using multiple Spreadsheets
• Copy, Paste and Cut your data
• Saving and printing worksheets
• Using MS Excel Help

27
5. Concept Map

What is a Spreadsheet?
Suppose you would like to maintain personal finance register also known as check register that will
keep track of the expenditures that you have been making during the current semester. Another
scenario can be the budget management of a small house. You may be interested in question such as
how much money has been spent on electricity bills and telephone bills. How much saving has been
made? You may imagine a book that keeps record of all transaction/ expenditures and income. Such a
book can be called a manual or paper spreadsheet. A sample is shown in the figure 1. In this case you
may have to save data that can be numerical or alphanumeric (involving letters or numbers).

Spreadsheet is a tool that is used to organize data,


such as a check register. Spreadsheets have been used
for many, many years in business to keep track of
expenses and other calculations.

Electronic Spreadsheet: Microsoft Excel is an example


of spreadsheet application program that can be used
for storing, organizing and manipulating data. The key
benefit to using a spreadsheet program is that you can
make changes easily, including correcting spelling or
values, adding, deleting and formatting. It consists of a
grid made from columns and rows similar to what you
have seen in your

Mathematics notebooks in school days. This grid


environment makes number manipulation very
easy Figure 1: Example Spread Sheet

As always with computer programs, there is more than one way to go about these things. The
instructions here are intended to be an easy introduction to the use of Excel. This lab manual includes a
subset of Microsoft Excel features

6. Homework Task before Lab


It is assumed that the user is both familiar and comfortable with the following prior to working with
Microsoft Excel:

• Using the mouse and the left-click feature


• Basic navigation through Microsoft Windows
• Basic typing and keyboard commands
• Familiarity with Microsoft Word

6.1 Task
Open MS office suite help by clicking the Help tab in the MS Excel window as shown in Figure 2. 1.

28
Figure 2. 1 : Help

The following window will appear as shown in Figure 2. 2. This is an online MS office help that retrieves
the information you request from the Internet. You are supposed to retrieve information related to
viewing and printing MS Excel documents using MS Excel online help system.

Figure 2. 2: Help Window

7. Procedure and Tools


• Desktop Computer
• Microsoft Windows XP operating system
• Microsoft Excel 2016

Microsoft Excel is an electronic spreadsheet. You can use it to organize your data into rows and
columns. You can also use it to perform mathematical calculations quickly. Before you start working
in Microsoft Excel, you need to open it. You can open Microsoft Excel by clicking on the Start button
and typing excel in search box as shown in Figure 2. 3.
29
Figure 2. 3: Start Menu

A screen similar to Figure 2. 4 will appear.

Columns

Rows

Figure 2. 4: Excel Layout

30
7.1 Excel Layout
Please refer to Figure 2. 4 to observe the layout of MS Excel. On the top you will find a ribbon similar to
MS Word and PowerPoint that we have discussed in previous lab. The different thing you will notice is
the rectangular boxes on the screen divided with the help of rows and columns

Rows are identified by Numbers as shown in the leftmost columns whereas Columns are identified by
Alphabets as shown in the topmost row.

If you want to select a particular cell, you will have to identify its address. The selected cell in the
Figure 2. 4, for example, is A1. A being the first column and 1 being the first row.

7.2 Walkthrough Tasks [Expected time = 20 min]

7.2.1 Home
In this section we will go through step by step through each section of the Insert tab just like we did
on the Home Tab in the previous lab. Below is a Snapshot of the insert tab in excel ribbon (Figure 2. 5).
Later each section is explained individually in detail and practice exercises.

Figure 2. 5: Home Tab Ribbon

Clipboard
This section of Home Tab is covered in Lab 1.

Font
This section of Home Tab is covered in Lab 1.

Alignment
In this section we would cover Merge and Center tab as shown in Figure 2. 6.

Figure 2. 6: Alignment

For performing merge and center, you need to first select the cells that you want to merge. The
selection of cells is shown in Figure 2. 8.

31
Figure 2. 7: Selection of Cells

Once selection of cells is done, click on Merge and center command. When you would click the
command, the cells would be merged as shown in Figure 2. 8.

Figure 2. 8: Merge and Center

Number
In this section you can add various things with the number for example, you can add the currency,
percentage sign, comma, decimal values after the number etc. Figure 2. 9 shows the number section
with different options displayed.
.

Figure 2. 9: Number Section

If you want to add currency to the number, click the drop-down list of dollar sign. When you click the
dollar sign various currency options are displayed e.g., dollar sign, euro sign, pounds sign etc. All these
signs are shown in Figure 2. 10.

Figure 2. 10: Adding Currency

32
You can use a few clicks to adjust the row height and column width according to your desire. Click on
“Format” in the cell section of the ribbon and a menu similar to Figure 2. 11 will appear below.

Figure 2. 11: Cell Format Menu

You can adjust the row height by clicking “Auto fit row height”. This will adjust the height of all the
cells in a row according to the font size of the data you have inserted. We will be doing our tasks on
the following example data
1. Copy and paste this data into a newly created Excel File.

Table 2: Sample data for practice tasks


Product Cost Price Sale Price Shipping Cost
Toothpaste 20 25 10
Shampoo 110 120 20
Soap 20 30 10
Mouthwash 49 50 15

2. Now Left align the Product column while apply right alignment for the rest of the columns
33
3. Merge Cost Price and Sale Price in the new column “Price” and use Sale price value for it.
4. Click on Auto row height and column width to adjust the height and width of the columns of
your data.
5. As the Column Price is a number and can be counted as currency, modify setting of new
column “Cost Price” and add American dollar USD$ ad its currency.
6. In the end you will have something similar to the Figure 2. 12.

Figure 2. 12: Output of the First 6 Steps

7. Note that Cost Price is now merged in two columns B and C instead of one column.
8. Now select the column for Cost Price and select Unmerge in the menu appearing after clicking
the arrow with the merge button.
9. After Unmerging you will notice that cost price has been reduced to one column. Now right
click on the empty column and delete to remove the empty column. As result you will have
something similar to the Figure 2. 13.

Figure 2. 13: Output of steps 8 and 9

Note that Cost price is not placed in the only Column B instead of both B and C as in the previous
figure.

7.2.2 Insert Tab [Expected time = 20 min]


Insert Tab can be used if you want to add graphics or link your document with another document.
Insert tab in ribbon provides different options for inserting useful information to your excel sheet. The
ribbon is shown in Figure 2. 14.

34
Figure 2. 14: Insert Tab in Ribbon

Tables
This section of Home Tab is covered in Lab 1.

Illustrations
This section of Home Tab is covered in Lab 1.

Charts
Charts allow you to present information contained in the worksheet in a graphic format. Excel offers
many types of charts including: Column, Line, Pie, Bar, Area, Scatter and more. To view the charts
available, click the Insert Tab on the Ribbon.

Creating a Chart:
– Select the cells that contain the data you want to use in the chart. In our example we
can select the shipping cost column to be used as chart data
– Click the Insert tab on the Ribbon
– Click the type of Chart you want to create. There are different chart types as show in
Figure 2. 15.

Figure 2. 15: Chart Tool

– Click the Column chart button and then select the 2d chart
– A bar chart will appear showing the shipping cost as chart as shown in Figure 2. 16.
– You can observe the costs at the Y-axis and as there are four items so you can see 4
bars at X-axis
– This chart has four components and you can right click on them separately to see the
advance options available.

35
Shipping Cost
25

20

15

Shipping Cost
10

0
1 2 3 4

Figure 2. 16:Resulting Chart

Figure 2. 17: Modifying chart data

Modifying a Chart:
– Once you have created a chart you can do several things to modify the chart.
– Move the chart
To change the data included in the chart:
▪ Right click the Chart
▪ Click the Select Data button on the Design tab as shown in Figure 2. 17.
36
▪ You can see the data selected in the “Chart data Range” box.
▪ =Sheet1!$C$6:$C$10 tells us that we are using the data from sheet1 and our
data starts from C6 and it goes till C10. The $ signs in the middle tell us that it
is address of the cell and not the data inserted by user.

To reverse which data are displayed in the rows and columns, Figure 2. 18 shows how to achieve this
task.
– Click the Chart
– Click the Switch Row/Column button on the Design tab

Figure 2. 18: Reverse Rows and Columns Data

Chart Tools
The Chart Tools appear on the Ribbon when you click on the chart. The tools are located on three
tabs:
– Design
– Layout
– Format

Design Tab
Within the Design tab you can control the chart type, layout, styles, and location. This tab is shown in
Figure 2. 19.

Figure 2. 19: Design Tab

1. Select the chart that you have drawn and now apply different chart layout to see the
differences.
2. Apply the different colors available in the ribbon such as green or orange.
3. Try moving the chart with the help of the Move chart button in the end and move it to
another sheet of this Excel File.

37
Format Tab
Within the Format tab you can modify shape styles, word styles and size of the chart. Format tab is
shown in Figure 2. 20.

Figure 2. 20: Format Tab

7.2.3 Page Layout


Page layout ribbon is shown in Figure 2. 21. This ribbon contains different options related to page
setup. All these options have been covered in lab of Microsoft Word.

Figure 2. 21: Page Layout Tab

1. Select the chart and apply different format type to see what effect it makes on your chart style and
color.

7.2.4 Formulas [Expected time = 25 min]


A formula is a set of mathematical instructions that can be used in Excel to perform calculations.
Formals are started in the formula box starting with an = sign. A sample formula is shown in Figure 2.
22.

Figure 2. 22: Formula Example

The formula ribbon is shown in Figure 2. 23. This ribbon gives you different options for applying
formulas. The first section represents Function library. Function library contains different formulas
from various categories.

38
Figure 2. 23: Formulas Tab

Figure 2. 24: Data for Sum Formula

Creating Basic Formula

To create a basic formula in Excel we need the data on which we need to apply the formula. Data is
represented in Figure 2. 24.

To create a basic formula, you need to do the following:


– Select the cell for the formula
– Type “=” (the equal sign) and the formula
– The formula is of sum which would sum the values.
– “:” is used to specify the range of the cell on which you want to apply the formula
– Click Enter
Creating a basic formula is shown in Figure 2. 25.

Figure 2. 25: Sum Formula

39
When you click enter you would get the result as shown in Figure 2. 26 the highlighted column
represents the result after applying the formula.

Figure 2. 26: Result of Sum Formula

Calculate with Functions


A function is a built-in formula in Excel. A function has a name and arguments (the mathematical
function) in parentheses.
– Sum: Adds all cells in the argument
– Average: Calculates the average of the cells in the argument
– Min: Finds the minimum value
– Max: Finds the maximum value
– Count: Finds the number of cells that contain a numerical value within a range of the
argument
To calculate a function:
– Click the cell where you want the function applied
– Click the Insert Function button
– Choose the function
– Click OK
The process of calculating through a function is shown in following figures.

Figure 2. 27: Applying sum function


40
Figure 2. 28: Applying sum function

Figure 2. 29: Output of sum function

Function Library
The function library is a large group of functions on the Formula Tab of the Ribbon.
– AutoSum: Easily calculates the sum of a range
– Recently Used: All recently used functions
– Financial: interest, cash flow return rates and additional financial functions – Logical:
And, If, True, False, etc.
– Text: Text based functions
– Date & Time: Functions calculated on date and time
– Math & Trig: Mathematical Functions

The categories of Function library are shown in Figure 2. 30.

41
Figure 2. 30: Function Library

If-else Formula

If-else is an important formula in Microsoft Excel. There are always situations in which you need to
decide what you want to do when a particular stage is reached. Suppose you want to apply 5% of tax
on all those products whose price is greater than 5000 rupees. To do such a task in Microsoft Excel,
you need IF-ELSE formula. Before you apply IF-ELSE formula you need the data again on which you
apply the IF-ELSE formula. To apply the IF formula the data is given in Figure 2. 31.

Figure 2. 31: Sample Data

Now we want to know whether the products are expensive or cheap. To do so we would apply the IF
formula. The condition for expensive is greater than or equal to 50. If the product’s price is greater than
or equal to 50 then it is expensive otherwise it is cheap.

To apply IF formula, you need to do the following:

– Select the cell where you want to apply the formula


– Put = (equal sign) in that cell
– Then write the if formula as shown in Figure 2. 32.

Figure 2. 32: IF formula

When you apply the formula shown in Figure 2. 32, you will get the result shown in Figure 2. 33.

42
Figure 2. 33: IF formula Result

Percentage Formula

There are some situations where you need to find some percent of a particular number, marks, price
or the percentage of salary to incremented annually for employees. For all such tasks you need a
percentage formula. We would apply a percentage formula for finding out how much sales tax to be
applied on the products price. To do so we need the data i.e., prices of products. Figure 2. 34 shows
sample data for products

Figure 2. 34: Data for Percentage Formula

We need to find 2% sales tax on product’s prices. To do so you need to do the following:

– Select the cell where you want to apply the formula


– Put = (equal sign) in that cell
– Apply the percentage formula as shown in Figure 2. 35.

Figure 2. 35: Percentage Formula

When you would apply the formula, you would get the required sales tax as shown in Figure 2. 36.
Sales tax is shown in Highlighted column.

43
Figure 2. 36: Sales tax after percentage formula

7.2.5 Data Tab [Expected time = 25 min]

In Excel you need to play around data to achieve the desired goals. Therefore, the Data tab has very
importance. In this tab you are given with various options that you can apply on the data in the Excel
Sheet. We will not be covering everything from this ribbon shown in Figure 2. 37. We look at Sorting
and filtering and how to get the external data from other sources.

Figure 2. 37: Data Tab

Sort & Filter


Sorting and Filtering allow you to manipulate data in a worksheet based on given set of criteria. You
can sort the data in ascending and descending order. There are two types of sorts in Microsoft Excel
i.e., Basic Sorts and Custom Sorts.

Basic Sort
To execute a basic descending or ascending sort based on one column perform the following steps:
• Highlight the cells that will be sorted
• Click the Sort & Filter button on the Home tab
• Click the Sort Ascending (A-Z) button or Sort Descending (Z-A) button
These steps are shown in Figure 2. 38.

Figure 2. 38: Sort and Filter

44
Custom Sort

To sort on the basis of more than one column:


– Click the Sort & Filter button on the Home tab
– Choose which column you want to sort by first
– Click Add Level
– Choose the next column you want to sort
– Click OK

This process is represented in following figures.

Figure 2. 39:Custom Sort

Figure 2. 40: Custom Sort column selection

45
Get and Transform Data
This section of Data tab gives you the option of importing data from other sources. As you can see in
Figure 2. 41 various sources have been shown from where you can get the data. The data sources are
Access, Web, and Text etc.

Figure 2. 41: Get and Transform Data

Data from File


Suppose you have created some data and that data is stored in some other file. You need that data in
your Excel sheet. To get the data from the file click on “From File” option given in the Get Data
section. When you click the option a dialog box would appear asking you to choose your data location.
This dialog box is shown in Figure 2. 42.

Figure 2. 42: Data from file

Click on New source button. When you click on this button, a wizard would appear which would ask
you to choose the type of data. This wizard is shown in Figure 2. 43.

46
Figure 2. 43: Selecting Data Source Wizard

8. Practice Tasks [Expected time = 30 min]


You are given the sheet below in Table 1. You are supposed to create an Excel spreadsheet and fill in the
data and then complete the tasks given below. The data is given in the table. Copy this data into a newly
created Excel sheet.

Table 1: Sample data for Practice Tasks


S. No S. Name 1st Term (50) 2nd Term (50) Obt. Marks Total Marks %age Grade
1 Huma 20 25 100
2 Awais 22 12 100
3 Ali 33 25 100
4 Musab 21 33 100
5 Musawar 32 22 100
6 Mariam 25 32 100
7 Sumbal 32 34 100
8 Hammad 22 22 100
9 Naveed 26 20 100
10 Ashraf 28 18 100

8.1 Calculate the obtained marks for the two terms


47
8.2 After calculating the marks find the percentage
8.3 Then apply the if formula and calculate the grades according to the MAJU scheme as given in the
following table

Table 2: Grading Scheme for Practice Tasks


Grade Marks
A >= 90
A- >85 && <90
B+ >80 && <=85
B >75 && <=80
B- >71 && <=75
C+ >65 && <=71
C >61 && <=65
C- >56 && <= 60
D+ >52 && <=56
D >50 && <=52
F <50

8.4 Sort the grades in ascending order


8.5 Plot the data into a bar chart that shows the relationship between 1st term, 2nd term and total
obtained marks. A sample is shown below in the Figure 2. 44.

Figure 2. 44: Expected Outcome of Task 8.5

48
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 5: Evaluation of the Lab


Sr. No Task No. Task Description Grade

1 5.1 Homework 20
2 6.1 Understanding Excel Layout 5
3 6.2 Walkthrough Tasks 5
4 7. 1-7.5 Practice Tasks 30
5 Quiz 40

10. Further Reading


Free MS EXCEL tutorial:
ohttp://www.gcflearnfree.org/excel

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

Lab 3: Escape Sequences and Variables arithmetic

50
Lab 3: Escape Sequences and Variables arithmetic

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 15 mins for each assigned task 30 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

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

Will be printed as:


Hello World

However, there 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 printed as:

“Hello” World

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

52
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 student 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;

53
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. Homework 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. 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.

54
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 2014.

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


mins]
6.1.1 Open visual studio 2014.
1) Go to start menu.
2) Click on Search Bar and write “visual studio 2014”.
3) Now select Microsoft Visual Studio as shown in the Figure 3. 1.

Select it

Search Bar

Figure 3. 1: Selecting Microsoft Visual Studio

55
Figure 3. 2a

6.1.3 Creating New Project.


1) After clicking on Visual C++ on Left side, a window will appear as shown in Figure 3. 2a.
2) Now click on empty project as shown in Figure 3.2b.
3) Give name to the project of your choice e.g. “My First Program”
4) Now click on “OK” button on bottom right corner of window

Figure 3. 2b

56
6.1.4 Selection of source folder.
After the step 6.1.3, you will see a screen just like shown in the Figure 3. 3.

1. Right click on the “source Files” option in solution explorer and you will have options like “Add”,
“Class Wizard…” etc., you have to select “Add”.

2. After Selecting “Add” you will see other options like “New Item”, “Existing item” etc., you will
select “New Item”.

Figure 3. 3: Selecting New Item

57
6.1.5 Selection of .cpp file.
From the various options, click on C++ File (.cpp) as shown in the Figure 3. 4.

Figure 3. 4: Selection of .cpp file

6.1.6 Give the name to the file.


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

Figure 3. 5: Writing Name of the file

When you click Add button, a new file would be added to your existing project as shown in the Figure 3. 6.
Now you can write code in the added file.

58
Figure 3. 6: File added in project

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

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 3. 7. Write the code in the intended form as shown.

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

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

Figure 3. 9: Build Activity

60
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 by selecting play option from Debug menu .
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 3. 10.

**********
* Hello *
* World *
Figure 3. 10: 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 3. 11. Write the code in the intended form as shown.

Figure 3. 11: Writing the C++ code

61
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]
Your need to print the formatted output like shown below:

##########################
$$$$*************************$$$$
********\\\WELCOME to CUST*******
$$$$*************************$$$$
##########################

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
Computer
CS1234 | Programming | 4
CS1123 | Cal-I | 4
CS1121 | Algebra | 3
CS1124 | Discrete Maths | 3
|18
Total | 5

62
7.4 Practice Task 4 [Expected Time=10 mins]

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

Name | Ali
Emp_no | Emp_123
Salary | 30000

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:

Allowances | 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
63
b. Subtraction
c. Division
d. Multiplication
e. Square

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.

Result= 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.

64
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

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

Practice Task
T1
T2
T3
T4
T5

65
T6
T7
T8
T9
T10
T11
T12

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

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

66
Appendix A – Escape Sequences

Escape Sequence Represents


\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

ASCII character in octal


notation
\ooo

\xhh ASCII character in hexadecimal notation

Unicode character in hexadecimal notation if this escape


sequence

is used in a wide-character constant or a Unicode string


\xhhhh literal.
For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The
Chinese
character for one is
\x4e00".

67
Name Description Size Range

signed: -128 to 127


Char Character or small integer. 1byte
unsigned: 0 to 255

short int (short) Short Integer. 2bytes signed: -32768 to 32767


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 precision floating point
Double number. 8bytes +/- 1.7e +/- 308 (~15 digits)
Long double precision floating point
long double number. 8bytes +/- 1.7e +/- 308 (~15 digits)

68
Capital University of Science & technology Islamabad
Department of Computer Science, Faculty of
Computing

Lab 4: Control Structures (Selection) and Relational Operators

69
Lab 4: 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.

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
Total Time 170 mins

70
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 student’s marks are greater than 90, then the grade will be shown as “A” and the
remaining

71
parts will not be executed (The else part). If the student’s 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.

72
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 2014.

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


mins]
6.1.1 Open visual studio 2014.
4) Go to start menu.
5) Click on Search Bar and write “visual studio 2014”.
6) Now select Microsoft Visual Studio as shown in the Figure 4. 1.

73
Select it

Search Bar

Figure 4. 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 Figure 4. 2.
3) Select Project from the sub-window.

Figure 4. 2: Opening File Menu

74
6.1.3 Creating New Project.
5) After clicking on Visual C++ on Left side, a window will appear as shown in Figure 4. 3a.
6) Now click on empty project as shown in Figure 4.3b.
7) Give name to the project of your choice e.g. “My First Program”
8) Now click on “OK” button on bottom right corner of window.

Figure 4. 3a: Creating an empty Project

Figure 4. 3b: Naming an empty Project

75
6.1.4 Selection of source folder.
After the step 6.1.3, you will see a screen just like shown in the Figure 4. 4.
3. Right click on the “source Files” option in solution explorer and you will have options like “Add”,
“Class Wizard…” etc., you have to select “Add”.

4. After Selecting “Add” you will see other options like “New Item”, “Existing item” etc, you will select
“New Item”.

Figure 4. 4: Selecting New Item

76
6.1.5 Selection of cpp file.

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

Figure 4. 5: Selecting Source File Folder

6.1.6 Give the name to the file.


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

Figure 4. 6: Writing Name of the file

77
When you click Add button, a new file would be added to your existing project as shown in

Figure 4. 7.
Now you can write code in the added file.

Figure 4. 7: File added in project

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.1.7. now write the following code as shown
in the Figure 4. 8. Write the code in the intended form as shown.

78
Figure 4. 8: Writing the C++ code

• Write the output of the following code

79
6.2.2 Compilation

After writing the code, now you are ready to compile it. For compilation, click on “Local Window Debugger”
option in the menu bar as shown in the Figure 4. 9.

Figure 4. 9: Compilation

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 4. 10.

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

Figure 4. 11: Final output

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

81
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 = 30 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

82
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 \\fs\lectures$\

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.

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

Lab 5: Nested If-else and Switch

84
Lab 5: 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
6.2 Specialized Tasks 30 mins 15 mins
7 Practice tasks As mentioned against each task 70 mins
Total Time 170 mins

85
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 if-
statement. 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.

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:

86
To understand the above statement, revise your concepts from the previous course of ITC. The logical and 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:

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

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

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.

89
4.6 Switch Statement
Remember, 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. However, the switch-statement do not require the evaluation of logical
expressions. The switch statement is used to pick 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 reserved 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.

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

90
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:
“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”;
91
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.

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

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.

93
2) The program will work fine for the uppercase 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”;
}

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

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

95
4.11 Bitwise Operators
The bitwise operators work 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.

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

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

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.

97
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 2014.
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
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";
}
}

98
• 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: 5. 1. Write the code in the intended form as shown on the next page:

Figure: 5. 1

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

100
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: 5. 2.

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

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

Figure: 5. 4: Final output


101
Output of code in Figure: 5. 1 is shown in Figure: 5. 5.

Figure: 5. 5: 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 from user and then finds and prints all the Odd 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

102
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

103
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

104
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
\\fs\lectures$

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

Lab 6: Repetition Structure Loops

106
Lab 6: Repetition Structures - Loops

1. Introduction
In the last two labs, 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 with each task 30 mins
5.1 Evaluation of Design 20 mins 20 mins

107
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

108
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

109
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 1. 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.

110
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
counter-controlled 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:

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

5. Homework 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.

112
6. Procedure & Tools
6.1 Tools

Visual Studio 2014.

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
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: 6. 1. Write the code in the intended form as shown:

Figure: 6. 1

113
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: 6. 2.

Figure: 6. 2

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: 6. 3.

Figure: 6. 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.
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: 6. 4.

114
Figure: 6. 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.

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

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.

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

2. Number = 2 Power 2 4

3. Number= 10 Power 1 10

4. Number =25 Power -1 0.04

5. Number 0 Power 0 1

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

117
Table 6: 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
\\fs\lectures$

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

Lab 7: Nested Loops

119
Lab 7: 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 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 As mentioned with each task 30 mins
Total Time 170 mins

3. Objective of the Experiment


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

120
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++
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<<’, ’;
}

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.
121
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;

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:

}
}

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:

0
0

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

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

123
* ****
* *****

6. Procedure& Tools
6.1 Tools
Visual Studio 2014.

6.2 Setting-up Visual Studio 2014.

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


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

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

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

Figure: 6. 5: Final output of Print Triangle program.

125
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 program that ask the user to type a value and check whether it is prime or not.

126
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
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

127
10. Further Readings
10.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\fs\lectures$\

11. Assignment
The lab instructor will give you unseen task of lab 7 as an assignment which is to be submitted by lab 8.

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

Lab 08: Arrays


Lab 08: Arrays
1. 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

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
As mentioned with assigned
7 Practice tasks task 85 mins
As mentioned with assigned
8 Evaluation Task task 30 mins
Total Time 170 mins
3. 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.

4. Concept Map
4.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++, arrays 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

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

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

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.

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

5.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:
10 8 5 9 14 7 12 10 1 2

Sample Output:
Maximum Number: 14

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

6. Procedure & Tools


6.1. Tools
Visual Studio 2014.

6.2. Setting-up Visual Studio


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

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


6.3.1. Writing Code

In the source file created in the project “StudentAvg” write following C++ code as shown in
Figure 1.

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

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 2: Final output student 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 told by your lab instructor.

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

7.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 divisible by 3 with new 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

Sample Outputs:
Sorted Array
2 4 6 8 10
7.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

7.4. Out comes


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

7.5. Testing
Test Cases for Practice Task-1:
Sample Input-1 Output 1(a) Output 1(b)
12824259327 1446441642581449 144 81
Sample Input-2 Output 2(a) Output 2(b)
28341059321 4649 161002581941 9 81 9

Test Cases for Practice Task-2:


Sample Input Sample Output (a) Sample Output (b)

315191812 4 16 20 18 12 4 12 16 18 20

88888 8 88 8 8 8 8 8 88

581361 6 8 14 6 2 2 6 6 8 14
Test Cases for Practice Task-3:
Sample Input Sample Output (a)
315191812 Ascending order array
Press 1 for ascending and 2 for descending order 19181512 3
2

Test Cases for Practice Task-3:

Practice Tasks Confirmation


T1
T2
T3

8. Evaluation Task (Unseen)


[Expected time =
30mins]
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 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
\\fs\lectures$\
Capital University of Science and Technology
Islamabad Department of Computer Science, Faculty of
Computing

Lab 09: Multi-Dimensional Arrays and Sorting


Lab 09: Multi-Dimensional Arrays and Sorting
1. 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

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 As mentioned with each task 85 mins
As mentioned with assigned
8 Evaluation Task task 30 mins
Total Time 170 mins
3. Objective of the Experiment
a. Introducing multi-dimensional arrays in particular 2D arrays.

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

4.1. Multi-Dimensional Arrays


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

0 1 2 3 4
0
int marks_of_three_students[3][5];
1
Row 2

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:
nd th
cout<<marks_of_three_students[1][3]; Prints value of the element at 2 row and 4 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 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.
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,

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
2 45 87 4 10

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


for(int i=0;i<3; i++) //For Row index
cin>>list[0];

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

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

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

6. Procedure& Tools
6.1. Tools
Visual Studio 2017.

6.2. Setting-up Visual Studio 2017 [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).

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

6.3.1. Writing Code

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

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


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 2: Final output of sum Row-Col 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
=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.

7.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 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.
7.3. Practice Task 2
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 has less than 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.

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

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

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

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 Practice tasks and Testing 35
7.3
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 \\fs\lectures$\
Capital University of Science and Technology
Islamabad Department of Computer Science, Faculty of
Computing

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


Reference
Lab 10: Introduction to Functions and Pass by Value and
Reference

1 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

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 As mentioned with each task 85 mins
As mentioned with each
8 Evaluation Task assigned task 30 mins
Total Time 170 ns
3 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.

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.

4.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 sum(int a, int b)

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”:
int multiplyTwoNums(int num1,int
num2)
{
int result = num1 * num2;

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
4.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.*/
swap(a, b);
Put together above code in a file, compiled and executed and see the results.

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

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.

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.

5.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 is double 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
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.

1. Procedure& Tools
6.1 Tools
Visual Studio 2014.

6.2 Setting-up Visual Studio 2014 [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).

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

6.3.1 Writing Code


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

Figure 10. 1
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


Now run the program by pressing Ctrl+F5 from keyboard or selecting play option from Debug menu. 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 10. 2.

Figure 10. 2: Final Output of Walkthrough Task

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 = 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 is double 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

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

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

7.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
the main body.

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

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

9. Evaluation Task [Estimated Time=30mins]

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

11. Further Readings

11.1 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\fs\lectures$\
Capital University of Science and Technology Islamabad
Department of Computer Science, Faculty of Computing

Lab 11: Functions and Arrays


Lab 11: 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 a
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
As mentioned with each
8 Evaluation Task assigned task 30 mins
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5mins 5 mins
6.3 Specialized Tasks 30mins 30 mins
7 Practice tasks 60 mins 85 mins
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 10, 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) {


.
.
.
}

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

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.2.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 2014.

6.2 Setting-up Visual Studio 2014 [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 as shown in
Figure 11. 1:

Figure 11. 1

6.3.1 Compilation
After writing the code, compile your code according to the guidelines mentioned in Lab-1 (section 6.3.2).
6.3.2 Executing the Program
A sample output after running the program is shown below in
Figure 11. 2:

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


a) Write a C++ program that creates an integer array having 30 elements. Then, implement 6
functions as shown below:
i. 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.

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

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

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

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

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

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

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

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

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

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
\\fs\lectures$\
Capital University of Science and Technology
Islamabad Department of Computer Science, Faculty of
Computing

Lab 12: Manipulating Sequence of Characters using C++ “string”


Data-type
Lab 12: Manipulating Sequence of Characters using
C++ “string” Data-type
1 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:

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

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 As mentioned with each task 85 mins
As mentioned with each
8 Evaluation Task assigned task 30 mins
Total Time 170 mins

3. Objective of the Experiment


• To get basic understanding of string data-type.
• To get familiarize and practice basic string functions.
4. 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>

4.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:

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

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

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

5.2 Practices from home


5.1.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.2.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!

6. Procedure & Tools


6.1 Tools
Visual Studio 2014.

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


Setup Visual Studio and make a project named “WordCounter”. 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 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.

6.3.1 Writing Code


In the source file created in the project “WordCounter” write the C++ code as shown in Figure 12. 1:

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

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 in Figure 12. 2 below:

Figure 12. 2: Final output of word count 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 = 40 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

7.2 Practice Task 2 [Expected time = 45mins]

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

7.3 Out comes


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

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

8. Evaluation Task (Unseen) [Expected Time= 30 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
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


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

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at\\fs\lectures$\

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
Return the character at position X (integer) in the string. Similar to using the
at (X) []
operator
Returns a copy of the substring (i.e. portion of the original string) that starts
substr(X, Y) at
index X and is Y characters long. Both X and Y are integers.
Returns a copy of the substring, starting at index X of the original string and
substr(X) going
to the end

append(str2) Appends str2 (a string or a c-string) to the calling string


Performs a comparison. A negative value return means str1 comes first.
str1.compare(str2) Positive
means str2 comes first. 0 means both strings are same.
Returns the first position at or beyond position X (integer value), where the
str.find(str2, X) 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 N number of characters in the calling string, with value of “str”
replace(X, N, str) string

variable starting at position X (integer value).


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

Lab 13: Pointers


Lab 13: 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 As mentioned with each task 85 mins
As mentioned with each
8 Evaluation Task assigned task 30 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
reserved against this statement and the initial value is stored in some memory location which has some
specific address as shown in Figure 13. 1.
.

Figure 13. 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

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

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.

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

6.2 Setting-up Visual Studio 2014 [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 as shown in Figure 13. 2.

Figure 13. 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 in Figure 13. 3.

Figure 13. 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.

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

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

8. Evaluation Task (Unseen) [Expected time = 30 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
\\fs\lectures$\
Capital University of Science and Technology Islamabad
Department of Computer Science, Faculty of Computing

Lab 14: Structures


Lab 14: Structures
1. 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.

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

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

4. 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 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[]){ . . .}


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.

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.

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

6. Procedure & Tools


6.1 Tools
Visual Studio 2014.

6.2 Setting-up Visual Studio 2014


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

6.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;
6.3.1 Writing Code
In the source file created in the project “EmployeeRecords” write following C++ code as shown in Figure
14. 1 :

Figure 14. 1: Code for Employee Records program


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 in Figure 14. 2.

Figure 14. 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.

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 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
7.2 Practice Task 2
Write a program that reads student’s name followed by their numerical scores. The program should
output the numerical score 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 compnents: studentFName and studentLName of type string,
testScore of type int(b/w 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:
• A function to read the students data into the array.
• A function to the relevant Grade to each student (use your own judgment to assign grades A, C,
D, or F based upon the students’ scores).
• A function find the highest score.
• A function to print the names of the students having the highest score

7.3 Out comes


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

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

8. Evaluation Task (Unseen) [Expected time = 30 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
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
\\fs\lectures$\

You might also like