You are on page 1of 158

Laboratory Manual

CSEE 1111: Introduction to Computing Lab


Name: ___________________________
Reg No: ___________________________
Section: ___________________________

Department of Electrical Engineering


Capital University of Science and Technology
Islamabad, Pakistan
© Copy Rights, Department of Electrical Engineering, CUST Islamabad

All Rights Reserved

Prepared By: Sheikh Zeeshan Ahmed

Department of Electrical Engineering


ii of iv
S.N0 List of Experiments

1 Computer Hardware and Application Software


2 Introduction to Microsoft Word

3 Introduction to Microsoft Excel

4 Introduction to Microsoft Power Point

5 Flow Chart in Microsoft Word & Visio

6 Introduction to C Programming Language

7 Input/Output Operators

8 Relational & Logical Operators

9 Selection Structure-I (Nested If-Else)

10 Selection Structure-II (Switch Statement)

11 Repetition Structure-I Introduction to Loops and


understanding of For-Loop
12 Repetition Structure-II Understanding and
Implementation of While-Loop & Do-While-Loop

Department of Electrical Engineering


iii of iv
Lab Safety Rules

 Be sure that all equipment is properly working before using them for laboratory exercises. Any
defective equipment must be reported immediately to the Lab Engineer or Lab Technical Staff.
 Students should keep a safe distance from the circuit breakers, electric circuits or any moving parts
during the experiment.
 Avoid any part of your body to be connected to the energized circuit and ground.
 Switch off the equipment and disconnect the power supplies from the circuit before leaving the
laboratory.
 Make sure that the last connection to be made in your circuit is the power supply and first thing to
be disconnected is also the power supply.
 Equipment should not be removed, transferred to any location without permission from the
laboratory staff.

Department of Electrical Engineering


iv of iv
Lab 01
1 Computer Hardware and Application Software
Objective:
 Understand the basic building blocks of computer.
 How to search, email, open server, save files and prints on server printer.

Department of Electrical Engineering


1
1.1 Computer Hardware

Computer hardware is the collection of physical parts of a computer system. This includes the
computer case, monitor, keyboard, and mouse. It also includes all the parts inside the computer
case, such as the hard disk drive, motherboard, video card, and many others. Computer hardware
is what you can physically touch.

Examples of Hardware are following:


 Input devices -- keyboard, mouse etc.
 Output devices -- printer, monitor etc.
 Secondary storage devices -- Hard disk, CD, DVD etc.
 Internal components -- CPU, motherboard, RAM etc.

Figure 1-1. Hardware

1.2 CPU
Alternately referred to as a processor, central processor, or microprocessor, the CPU (pronounced
sea-pea-you) is the Central Processing Unit of the computer. A computer's CPU handles all
instructions it receives from hardware and software running on the computer.

Department of Electrical Engineering


2
Figure 1-2. Central Processing Unit
1.3 Components of the CPU
In the CPU, the primary components are the ALU (Arithmetic Logic Unit) that performs
mathematical, logical, and decision operations and the CU (Control Unit) that directs all of the
processors operations.

Figure 1-3. Machine Cycle

1.4 Fan
A hardware device that keeps the overall computer or a computer device cool by circulating air to
or from the computer or component. The picture is an example of a fan on a heat sink.

Department of Electrical Engineering


3
Figure 1-4. Active and Passive Heat Sink

1.5 Motherboard
Alternatively referred to as the mb, mainboard, mboard, mobo, mobd,backplane board, base board,
main circuit board, planar board, system board, or a logic board on Apple computers. The
motherboard is a printed circuit board that is the foundation of a computer, located on the back
side or at the bottom of the computer case. It allocates power and allows communication to the
CPU, RAM, and all other computer hardware components.

Figure 1-5. Motherboard

Department of Electrical Engineering


4
1.6 Modem
A Modem or Broadband Modem is a hardware device that connects a computer or router to a
broadband network. For example, a Cable Modem and DSL Modem are two examples of these
types of Modems.

Figure 1-6. Cable Modem

1.7 NIC
Short for Network Interface Card, the NIC is also referred to as an Ethernet card and network
adapter. It is an expansion card that enables a computer to connect to a network; such as a home
network, or the Internet using an Ethernet cable with an RJ-45 connector.

Figure 1-7. Ethernet PCI Network Card

1.8 RAM
Alternatively referred to as main memory, primary memory, or system memory, Random Access
Memory (RAM) is a hardware device that allows information to be stored and retrieved on a
computer.

Department of Electrical Engineering


5
Figure 1-8. RAM

1.9 Sound Card


Alternatively referred to as an audio output device, sound board, or audio card.

Figure 1-9. Computer Sound Card

1.10 Video card


Alternatively known as a display adapter, graphics card, video adapter, video board, or video
controller, a video card is an IC or internal board that creates a picture on a display.

Department of Electrical Engineering


6
Figure 1-10. Internal Computer Video Expansion Card

Department of Electrical Engineering


7
1.11 HOW TO SEARCH FOR A FILE OR FOLDER FROM THE
WINDOWS 7
Although you can open a separate Search window, one of the easiest ways to search for files and
folders in Windows 7 is to search straight from the Start menu. Fortunately, Windows 7 has made
massive improvements to its search technology.

Windows 7 uses a more advanced search index that continuously monitors every file and even the
words within most of your files. When you search for a file or folder in Windows 7, you are much
more likely to find it than you were with Windows Vista or Windows XP.

Open the Start menu and type a search term in the search field at the bottom.

Figure 1-11. Search

Department of Electrical Engineering


8
Click the See More Results link.

Figure 1-12. Search Result

When you locate the file you wanted, double-click it to open it. If you don’t see what you’re
looking for, choose the Folder and Search Options command from the Organize menu to modify
Search settings. You can alter the locations to search, indicate whether to find partial matches for
search terms, and more.

Department of Electrical Engineering


9
1.12 How to write an Email

Figure 1-13. Email

1.13 Access of CUST Portal

Figure 1-14. CUST Portal

Department of Electrical Engineering


10
1.14 Student Services

Figure 1-15. Student Portal

1.15 Access of Lectures

Figure 1-16. Access of Lectures

Department of Electrical Engineering


11
Figure 1-17. Lectures Folder

Department of Electrical Engineering


12
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


13
Department of Electrical Engineering
14
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


15
Lab 02
2 Introduction to Microsoft Word

Objective:

 How to write documents in word and the use of editing options available in word.

Department of Electrical Engineering


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

2.2 Homework before Lab

2.2.1 MS Office Installation


Copy the MS office setup from the \\fs\lectures$\ITCLAB$.Try to install it at home. Open MS
word from the start menu and try to do the following task.

Figure 2-1. MS Word Help System

1. Click on the blue Question Mark to go to Microsoft Office Help. The Office Help is really
good. After opening the help try to search the shortcut key for following tasks in MS Word
2007.

 Create a new document of the same type as the current or most recent
document
 Open a document
 Close a document
 Save a document

2.3 Procedure & Tools


2.3.1 Tools

 Desktop Computer
 Microsoft Windows operating system, XP or any latest Edition
 Microsoft Word 2007

Department of Electrical Engineering


17
2.4 Setting-up Microsoft Word 2007

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

Figure 2-2. Start Menu to Start MS Word

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.

2.5 Templates
Templates are a collection of styles and formatting settings, and they can save you a ton of time
when creating a new document. You can find templates for almost any type of document, from
flyers to resumes, and birthday cards to banners. You can also create your own templates to save
yourself from having to remake documents from scratch.

Go to File menu and click ‘New’. Select Sample templates to use the built-in templates.

Department of Electrical Engineering


18
Figure 2-3. MS Word Open New Document

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

Figure 2-4. Executive Report

Department of Electrical Engineering


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

Figure 2-5. Insert Cover Page

Cover Page is the title page of the document. Word 2007 provides a number of preformed cover
pages to give your document a professional look.

2.7 Cover page Exercise: Creating a Cover Page

Click the Insert tab to make it the active tab.

Figure 2-6. Insert Tab

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.

Department of Electrical Engineering


20
Figure 2-7. Built-in Cover Page

1. 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.
2. A Cover page will be added to your document.

2.8 Style Group

Figure 2-8. Styles

The fourth group on the Home ribbon is the Style group. 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

Department of Electrical Engineering


21
heading (you don’t even need to select all the text), and then click Heading 1 in the gallery of
styles.

2.9 Tables

Word provides tables option for placing data in a more formal way.
 Click on table in insert tab.
 To add Rows and Columns, select top to bottom for rows & left to right for columns
 Click to apply when happy with the selection.
 Click on the box to enter text.
 Observe the new tab opened "Table Tools". You can use this tool to apply further
formatting to your created table.

Figure 2-9. Insert Table

2.10 Illustrations
Using Illustrations you can add pictures of all types and styles to your document. Followed is detail
Description on how to add illustrations.

Department of Electrical Engineering


22
Figure 2-10. Illustrations

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

2.12 Insert Caption


Right click on the image and select ‘Insert Caption’.

Figure 2-11. Insert Caption

Write the caption of the figure and click ‘OK’

Department of Electrical Engineering


23
Figure 2-12. Caption

2.13 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 2-13. Insert Table of Content

Department of Electrical Engineering


24
Activity 01:-

How to add Table of Contents


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

Figure 2-14. Table of Content

Department of Electrical Engineering


25
Figure 2-15. Insert Table of Content

Figure 2-16. Table of Content Setting

Department of Electrical Engineering


26
2.14 Table of Figures
Activity 02:-
How to add Table of Figures
1. Apply caption to your figures.
2. Move the insertion point to the place where you want the Table of figures to appear.
3. Click the References tab on the Ribbon and go to Captions section.
4. Click on ‘Insert table of figures’.
5. Choose your desired style and click ‘OK’.

Figure 2-17. Insert Table of Figures

Figure 2-18. Table of Figures

Department of Electrical Engineering


27
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


28
Department of Electrical Engineering
29
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


30
Lab 03
3 Introduction to Microsoft Excel

Objective:

 How to write documents in excel and the use of editing options available in excel.

Department of Electrical Engineering


31
3.1 Walkthrough task for MS Excel:

3.1.1 The Interface:


The first figure shows the typical Excel sheet with the important parts of the programs interface
labeled. Please become familiar with these.

Figure 3-1. Excel Layout

Department of Electrical Engineering


32
Activity 01:-
We will be doing our tasks on the following example data

Table 3-1. Data

Name ITP English Total Percentage


Ali 75 77 152 76
Bilal 63 70 133 66.5
Sara 74 66 140 70
Aleena 62 75 137 68.5

1. Copy and paste this data into a newly created Excel File.
2. Now left align the Name column while apply right alignment for the rest of the
columns.
3. Now, use the data of ITP and English to calculate the total marks. To do this use
‘function’, the built in formula in Excel.

Figure 3-2. Excel Layout

4. By using sum calculate the sum of marks of a student.

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 the
percentage of a student’s marks.

Department of Electrical Engineering


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

Figure 3-3. Percentage Formula

When you would apply the formula you would get the required percentage as shown in figure
30. Percentage is shown in Highlighted column.

Figure 3-4. Percentage Formula

Department of Electrical Engineering


34
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


35
Department of Electrical Engineering
36
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


37
Lab 04
4 Introduction to Microsoft Power Point

Objective:

 How to write documents in power point and the use of editing options available in
power point.

Department of Electrical Engineering


38
4.1 Home Ribbon

Figure 4-1. Home Ribbon

4.2 Slides
4.2.1 New Slide:
1. Click on home ribbon
2. Click on new slide button
3. New slide will be shown in your presentation

4.3 Layout:
Different slide layouts are used to manage the arrangement of content on the side.
Click the layout you want. The layout appears in the slide pane of the PowerPoint window.

Department of Electrical Engineering


39
Figure 4-2. Layout

1. Make two of the slides as tile slide, third and fourth one as size and content layout and last
one should be blank.
2. Write your name and registration number on first title slide.
3. On second slide write topic as "Computers".
4. Search text from internet and add some points about computers in the successive two slides
and last slide should be having pictures of computers.

Department of Electrical Engineering


40
Figure 4-3. Output of Sample Slides

4.4 Themes
4.4.1 Applying theme to your slides:
 A theme is a set of colors, fonts, and special effects. Themes provide attractive backgrounds
for your PowerPoint slides.
 To apply a theme to all of the slides in your presentation:
 Choose the Design tab.
 Click the More buttons in the Themes group.
 Click the design as shown in arrow 3 of figure 18 you want.

Department of Electrical Engineering


41
Figure 4-4. Applying Themes

4.4.2 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 arrow 1 of figure 18.
3. Click the More buttons in the Themes group as shown in arrow 2 of figure 18.
4. Right-click the theme you want to apply. A menu appears.
5. Click Apply to Selected Slides

Change fonts to Arial, colors to origin and add Metro effects in Design Tab.

4.5 Background:
You can add a dramatic effect to your theme by applying a background.
1. Choose the Design tab.
2. Click the Background Styles button.
3. Click the background you want.

Department of Electrical Engineering


42
Figure 4-5. Apply Background Styles

Figure 4-6. New Slide with Custom Design

Department of Electrical Engineering


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

Figure 4-7. Output of Custom Design Slides

Figure 4-8. Animations Tab

4.5.1 Preview:
Preview: This button previews the animated slides being set by using slide transitions of the
presentation.

4.5.2 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

4.5.3 Custom Animation:


You can animate the objects on your PowerPoint slides. PowerPoint provides four types of
animations as shown in Figure 4-8.

Department of Electrical Engineering


44
Figure 4-9. 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.

4.5.4 To choose an effect:


1. Select the object you want to animate.
2. Choose the Animations tab.
3. Click the Custom Animation button. The Custom Animation pane appears.
4. Click the Add Effect button. A menu appears.
5. Choose the type of effect you want. A submenu appears.
6. Click the effect you want. PowerPoint applies the effect.

Department of Electrical Engineering


45
4.5.5 To modify an effect:
1. Click the down arrow next to the Start field on the Custom Animations pane and then select
the start method you want.
2. Click the down arrow next to the Property field on the Custom Animations pane and the
select the property you want. The Property field might be labelled Direction, Size, or some
other property.
3. Click the down arrow next to the Speed field on the Custom Animations pane and then
select the speed you want to apply to your animation.
A. Apply animation 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 4-10. Applying Animation

To preview the animation, click the Play button on the Custom Animations pane.
Explore all of them yourself and animate your text and slides. Slide show should display
presentation in effective manner with animations on each slide.

Department of Electrical Engineering


46
4.6 Transition Sound
This button allows you to add some sound during slid transitions of your presentation. You can
select various sounds from this option.

 In the pane that contains the Outline and Slides tabs, click the Slides tab.
 Select slide thumbnail of the slide that you want to add a sound to.
 On the Transitions tab, in the Timing group, click the arrow next to Sound, and then do
one of the following:
1. To add a sound from the list, select the sound that you want.
2. To add a sound not found on the list, select Other Sound, locate the sound file that
you want to add, and then click OK.

Figure 4-11. Transition Sound


Department of Electrical Engineering
47
Select transition sound for the presentation that must not be annoying for the audience.

4.7 Transition Speed


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

Figure 4-12. Managing Slide Transitions

1. All slides should advance one by one at mouse click or keyboard keys.

4.7.1 Apply To all


This button applies all settings being chosen on all slides in the presentation.

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

Department of Electrical Engineering


48
Activity 01:-

Prepare 50 slides on topic “Computer”. Your slides must have following


effects:-

 Proper Layout
 Theme
 Background
 Animation
 Transition Sound
 Transition Speed
 Tables
And all other effects which you learn in this lab.

Department of Electrical Engineering


49
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


50
Department of Electrical Engineering
51
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed and all
entered on the lab on the lab report. designed but most stages stages of the
report. of the procedure are procedure are entered
entered on the lab report. on the lab report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled.
All questions are
answered correctly.
Data Analysis Data are presented Data are presented in Data are presented in Data are presented in
(10) in very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but organized and
(10) spelling or grammatical contains some cohesive and contains
errors. grammatical errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


52
Lab 05
5 Flow Chart in MS Word & Visio

Objective:

 Design of flow charts in MS Word.


 Design of flow charts in MS Visio.

Department of Electrical Engineering


53
5.1 Flow charts in word:

All the tools needed to make flowcharts in MS Word 2013 lie with the Drawing Tools. But first
do these three preliminary steps:

5.1.1 Maximize your page area

Collapse the Ribbon by clicking the little upward arrow (or Click Ctrl+F1) on the extreme right so
only the tab names show.

5.1.2 Display the Grid

Click the View tab and click the Gridlines checkbox. The grid helps you align and size the
flowchart symbols precisely as you can snap them to the gridlines. You can also customize the
gridlines (Page Layout — Arrange — Align — Grid Settings).

Figure 5-1. Display the Grid

Department of Electrical Engineering


54
Use the Drawing Canvas. Inserting any shape or “drawing” in a Word document automatically
creates a drawing canvas. You will have to resize the canvas to frame your entire flowchart. It is
especially useful when using different shapes (as in a flowchart). Also, you can customize the
drawing canvas itself to create attractive backdrops for your flowchart.

Figure 5-2. Drawing Canvas

Now, let’s start the meticulous job of inserting our shapes and connecting them all together. It
always helps if you map it out on paper first, and then use Word to give it the finished look. A
rough sketch helps you understand the page layout on Word to begin with. The process is simple
but putting some planning into using this “planning tool” is a timesaver. All the required symbols
can be found on the Insert tab – Shapes. Click the dropdown for Shapes.

Department of Electrical Engineering


55
Figure 5-3. Shapes

1. The symbols are neatly organized under the Flowchart group.


2. Select the shape. For instance, the symbol for “Start”.
3. Click in the canvas area, keep the left button pressed while dragging the mouse to add
the shape. You can also double click on any shape to automatically add it to the Canvas.
Move and resize

Department of Electrical Engineering


56
Figure 5-4. Drawing Canvas Example

4. Add text by clicking the shape and typing in the label.


5. Connect two symbol-shapes with the help of arrows or connectors. Unlike simple
arrows, connectors stay connected to the shapes. The two basic types of connectors
available under the Shapes dropdown are elbow and curved.Note: Connectors work as
intended only between shapes placed on the drawing canvas .For instance, you can
manually move the connectors to any connection points (represented by tiny blue dots
on the shapes). The connection points anchor the connectors in place and you can move
the shapes without dislodging the connectors. This gives you a lot of flexibility when
modifying your flowchart by moving things around.

Figure 5-5. Lines

Department of Electrical Engineering


57
6. Add a Yes or No to the connectors branching out of Decisions shapes by inserting Text
Boxes alongside the connector arrows. You can also use the rotation handle to rotate
the text box.

5.2 Tips to Align Shapes

There are several ways to do it.

1. The recommended way is to do it right the first time. Use the gridlines and draw them with
uniform widths when you are placing them on the canvas.
2. Click on individual shapes and drag them to the new locations. If you have many shapes,
this can be very time consuming. The gridlines help you snap them in place.
3. Select all the shapes you want to align. On the Format tab, click the Align dropdown menu.
Select Align Selected Objects and use the alignment tool to align the shapes automatically.

5.3 Tips to Align a Flowchart

After the flowchart has been laid out, you can neatly align the diagram according to the page.

1. Group all the shapes and connectors. Select all the shapes and connectors. On the Format
tab, click the Group dropdown and select Group.
2. From the Align dropdown check if the Align to Margin item is selected. Then, click Align
Center and/or Align Middle.
3. Optionally, resize the canvas by dragging the corner or edges.

Department of Electrical Engineering


58
5.4 Designing a “Stunning” Flowchart

Figure 5-6. Stunning Flowchart

The colorful flowchart you see above is nothing but a more formatted flowchart. Formatting a
flowchart should be the final stage after you have inserted, connected, and labelled all the boxes.
It is better to do it in bulk rather than putting the flourishes on individual boxes as you go along.
So, select multiple shapes and format them together.

I will leave it to your creative eye, and just point you to the basic tools you can access from the
Format tab on the Ribbon or the more detailed options available on the side panel. Open the side
panel by right-clicking on a shape and selecting Format Shape.

Department of Electrical Engineering


59
Figure 5-7. Format Shape

You have many options available to design the shapes and the connectors:

 Shape Styles: A quick way to add color or gradient fills to the shapes.
 Shape Fills: Use your choice of solid colors or gradients. Don’t use too many color
schemes.
 Shape Outlines: Set the visual properties of the bounding lines. Also, use it to make the
connector arrows thicker or thinner.
 Effects: Give the shapes depth with 3-Dimensions, Shadows etc.

As you can see, there are many options to add a variety of finishing touches to the barebones
flowchart. It is painstaking, but do fuss over it if you want a thoroughly professional look.

Department of Electrical Engineering


60
5.5 Flow Charts in Visio:
Visio customization and settings are similar to Word since both software are developed by Microsoft
under the Office domain.

5.5.1 Getting Started:


After opening Visio, click the basic diagram button

Figure 5-8. Main Window Visio

The biggest difference between Word and Visio is that Visio is designed to make flowcharts and
drawings where as word is a text editing software. This makes it very easy to maneuver and make
changes in Visio according to one’s requirements.

After selecting “Basic Diagram”, a new window appears where all the shapes are neatly arranged on the
left side under the tab of “Basic Shapes”.

Department of Electrical Engineering


61
Figure 5-9. Work Space

Display the Grid by using the same method as used in Word. Drop all the shapes in the Work Space.

Figure 5-10. Dropping Shapes

Department of Electrical Engineering


62
Now connect the shapes together using the “Connector” tool in the upper portion of the “Home” tab.

Figure 5-11. Connecting the Shapes

Colors can be added to shapes and formatted as same as in word by using format or simply by “Styles
Option”. Right click the shape you want to edit in the Work Space and select “Styles” to open a variety of
editing options.

Figure 5-12. Adding Colors and Editing


Department of Electrical Engineering
63
Activity 01:
Draw the flow chart in MS Word and Visio.

Figure 5-13. Flow Chart I

Flow Chart I

Department of Electrical Engineering


64
Activity 02:
Draw the flow chart in MS Word and Visio.

Figure 5-15.

Figure 5-14. Flow Chart II

. Flow Chart II
Department of Electrical Engineering
65
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


66
Department of Electrical Engineering
67
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


68
Lab 06
6 Introduction to C Programming Language

After this lab student will have understanding about


 Compiler, assembler, linker and interpreter.
 Steps involve in the program execution.
 Algorithm and pseudo codes writing.
 Flowcharting of algorithms in Microsoft Visio.
 Problem solving techniques.
 To get the basic understanding of c language and development environment
 Understanding the structure of c program
 Making hello world project to understand the program compilation and execution steps
 Understanding data types of c language
 Understanding syntax of variable declaration and their scope
 Input, output statements and format specifiers
 Arithmetic operators
 Escape sequences
 Types of operators
 Operator precedence
 Commenting code

Department of Electrical Engineering


69
6.1 Setting up Integrated Development Environment (IDE):
Go to start menu-->All Programs-->Micro Soft Visual Studio 2010 and then click on
Micro Soft Visual Studio 2010.

6.2 Perform the following steps to setup the IDE for C programming.
 Create a new project by clicking File->New->Project.
 From Installed Template choose other language
 Choose language Visual C++
 In Visual C++ choose tab Win32
 Choose project type Win32 Console Application and then click OK

See the image below,

Figure 6-1. New Project

Department of Electrical Engineering


70
From the dialog box click on Next button

Figure 6-2. Win32 Application Wizard

Next screen is of Application Setting. You need to make sure


 Application type is set a Console Application

 In Additional options uncheck the Precompiled Header.

Department of Electrical Engineering


71
Figure 6-3. Application Setting

After clicking Finish you will find a project has been created with below structure. Open solution
explorer to see the structure

Figure 6-4. Project

To start programming, right click on Source Files and add a new item. You need
to make sure below two points,
 Select C++ File to add

Department of Electrical Engineering


72
 But in name change extension to .C, default is .CPP. To work with C language program
source file name should be with extension “.C”. In this case I am giving source file name
as Sample1.C

Figure 6-5. Create .cpp File

Now open Sample1.c

6.3 C - Program Structure

A C program basically has the following form:

 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

Department of Electrical Engineering


73
The following program is written in the C programming language.

#include <stdio.h>

int main()
{
/* My first program */
printf("Hello, World! \n");

return 0;
}

6.3.1 Preprocessor Commands:


These commands tell the compiler to do preprocessing before doing actual
compilation. Like #include <stdio.h> is a preprocessor command which tells a C
compiler to include stdio.h file before going to actual compilation.

6.3.2 Functions:
Functions are main building blocks of any C Program. Every C Program will have one
or more functions and there is one mandatory function which is called main() function.
This function is prefixed with keyword int which means this function returns an integer
value when it exits. This integer value is returned using return statement.

6.3.3 Variables:
Variables are used to hold numbers, strings and complex data for manipulation. You will
learn in detail about variables in next topics

6.3.4 Statements & Expressions :


Expressions combine variables and constants to create new values. Statements are
expressions, assignments, function calls, or control flow statements which make up C
programs.

6.3.5 Comments:
Comments are used to give additional useful information inside a C Program. All the
comments will be put inside /*...*/ as given in the example above. A comment can span
through multiple lines.

Note the followings

 C is a case sensitive programming language. It means in C printf and Printf will have
different meanings.
Department of Electrical Engineering
74
Activity 01:-
Type the following program in C Editor and execute it. Mention the Error.
void main(void)
{
printf(“Hello World”);
}

Activity 02:-
Add the following line at the beginning of the above program. Recompile
the program. What is the output?
#include<stdio.h>

Activity 03:-
Make the following changes to the program. What Errors are observed?
i. Write Void instead of void

ii. write void main (void);

iii. Remove the semi colon ‘;’.

iv. Erase any one of brace ‘{’ or ‘}’.

Department of Electrical Engineering


75
6.4 Data types in C language
In C, variable (data) should be declared before it can be used in program. Data types
are the keywords, which are used for assigning a type to a variable.

1. Primitive Data Types


o Integer types
o Floating Type
o Character types
2. User defined data types

We will discus later about user defined data types

6.5 Variables:
A variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable that
you are going to use and its type.

The Programming language C has two main variable types

 Local Variables
 Global Variables

We will discus later about local and global variables

6.6 Syntax for declaration of a variable


data_type variable_name;

For example, if you want to declare a variable of type integer then the syntax will be

int number;

6.7 Input:
Any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set
of built-in functions to read given input and feed it to the program as per requirement.

Department of Electrical Engineering


76
6.8 Output:
In any programming language output means to display some data on screen, printer or in
any file. C programming language provides a set of built-in functions to output required
data.
Here we will discuss only one input function and one output function just to understand the
meaning of input and output.

6.8.1 printf() function


This is one of the most frequently used functions in C for output.

6.8.2 scanf() function


This is the function which can be used to to read an input from the command line.

6.9 Format Specifiers:


Format Specifiers tell the printf() statement where to put the text and how to display the text.
The various format specifiers are:

%d => integer
%c => character
%f => float etc.

6.10 Escape Sequences


Escape Sequence causes the program to escape from the normal interpretation of a
string, so that the next character is recognized as having a special meaning. The back
slash “\” character is called the “Escape Character”. The escape sequence includes
the following:
\n => new line
\t => tab
\b => back space
\r => carriage return
\” => double quotations
\\ => back slash etc.

6.11 Operators
There are various types of operators that may be placed in three categories:

Arithmetic + - * / %
Assignment = += -= *= /= %=
Relational < > <= >= == !=
Logical && , || , !
Department of Electrical Engineering
77
Activity 04:-
Write five statements by using printf function to print the asterisk pattern:
*****
*****
*****
*****
*****

Solution:

For first line of asterisks, write the following line

printf("*****");

Copy and paste the line five times and then compile the code.

Activity 05:-
Write program that print the following shape on console:

*************
* *
* *
* *
*************

Activity 06:-
Write a C program to declare two integer and one float variables then initialize them to 10,
15, and 12.6 then prints these values on the screen.
Solution:

Department of Electrical Engineering


78
Activity 07:-
Declare integer type variable s “age” , “phNo” and assign 20 and 0333 value to the
variables respectively. Then print the the value on console.
Your output should be in the following format

Your age is= 20 and your contact no is 333

You are allow only one printf() function in your program.

Department of Electrical Engineering


79
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


80
Department of Electrical Engineering
81
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


82
Lab 07
7 Input/Output Operators

Objective:

 Understand the use of input/output statements with different data types.


 Understand different types of operators and operator precedence.

Department of Electrical Engineering


83
7.1 Format Specifiers:
d -- Displays a decimal (base 10) integer

l -- used with other specifiers to indicate a "long"

e -- Displays a floating point value in exponential notation

f -- Displays a floating point value

g -- Displays a number in either "e" or "f" format

c -- Displays a single character

s -- Displays a string of characters

7.2 Consider the following program


/* A programto add 2 integers. Comment statement in C/C++ (0) */
#include < stdio.h > /* I/O standard library in C (1) */
int main () /* must be first statement in C/C++ program (2) */
{
/* start of body of program */
int integer1;

int integer2;

int sum = 0; /* variable declarations (3) */

printf ( "Initialization of 2 integers\n" ); /*sample of


printf (4) */

integer1 = 80; /*sample of assignment statement (5) */

integer2 = 90;

sum = integer1 + integer2;

/*sample of assignment st. and numerical example (6) */


printf ( "sum=%d\n\n" , sum ); /* sample printf statement (7)
*/

/* sample of escape character \n */


/* and format %d of integer datatype */
return 0; /* return statement..remove it if type of main is
void (8) */

} /* End of program boundary (9) */


Above program is actually demonstration input statement and “+” arithmetic operator.

Department of Electrical Engineering


84
Output of the above program will be

Figure 7-1. Output

7.3 Write down a program which initialize 3 integers, G1,G2,G3, then


calculate average as real (float). Print your name as string using a simple
printf statement, then grades G1,G2,G3 in different line with nice
heading, and finally, print the average.
/* solution of the above problem */
#include <stdio.h>
int main ( )
{ /* Start of program body */
int G1;
int G2;
int G3;
float Av;
printf( " My name is Yahia \n" );
G1 = 90;
G2 = 85;
G3 = 80;
Av = (G1 + G2 + G3 ) / 3; /* why we put 3.0 and not 3 ?*/
printf("math: %d\n, physics: %d\n, Computer skill:%d\n",
G1,G2,G3);
printf("Average: %.3f\n", Av);
return o;
} /* End of program body */

Figure 7-2. Output


Department of Electrical Engineering
85
7.4 How to input data from keyboard?
To read input data from keyword, use: scanf statement.
General format:

scanf("format type",address of list of variables to be read);

Format type can be: %d,%c,%f or others, as we learned before for printf statement.

Address of list of variables to be read:


must start with: & sign.

7.4.1 Example:
scanf( "%d ",&v1);

7.4.1.1 Consider the following code


// A program to get integer from user and print on console
#include < stdio.h > // I/O standard library in C
int main () //must be first statement in C/C++ program
{
int number;
printf("please enter your registeration number :");

scanf("%d", &number);

printf("your registeration number is= %d\n",number);

} /* End of program boundary (9) */

Figure 7-3. Output

Department of Electrical Engineering


86
7.4.2 Example:

7.4.2.1 Consider the following code

// A program that get 2 numbers from user and print their sum
#include < stdio.h > // I/O standard library in C
int main () //must be first statement in C/C++ program
{
int number1;
int number2;
int sum = 0;
printf ("Enter num 1 = " );

scanf ( "%d" , &number1 );

printf ("Enter num 2 = ");

scanf ( "%d", &number2 );

sum = number1 + number2;

printf ( "sum = %d\n", sum );

} /* End of program boundary (9) */

Output of the above program will be

Figure 7-4. Output

Department of Electrical Engineering


87
Activity 01:-
Write a program that get two numbers from user and print its sum on console

Solution:

Step 1:

Declare three integer variables num1 and num2 and result in main function

Get input from user using scanf function fpr num1

Get input from user using scanf function for num2

Step 2:

Calculate sum of num1 and num2 and store in result variable

Print result using printf statement

Test input:

Enter num1: 12

Enter num2: 4

Result = 16

Activity 02:-
Write a program that gets two integer numbers from user. Your program should
perform subtraction multiplication and division on both number and display result on
console.

Department of Electrical Engineering


88
Activity 03:-
Write a C program that evaluate the following expression and print the output on
console:

𝒂 𝒅+𝒆
∗𝒄+
𝒃 𝒇

Get the values of a, b, c, d, e, f from user.

Activity 04:-
Write program for the following flow chart

Figure 7-5. Flow Chart

Department of Electrical Engineering


89
Activity 05:-
Write code from the following algorithm. This algorithm in swapping value two
number by getting input from user and print on console.

Get two numbers num1 and num2 from user

Store num1 in temp variable

Store num2 in num1

Store temp in num2

Display num1 and num2

Department of Electrical Engineering


90
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


91
Department of Electrical Engineering
92
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


93
Lab 08
8 Relational & Logical Operators

Objective:

 To get basic understanding of Relational & logical operators


 One way selection
 Two way selection
 Compound Statement
 To get basic understanding of nested-if conditions
 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.

Department of Electrical Engineering


94
8.1 Introduction
This lab will introduce you the concepts of how to use the Control Structures (selections) such as:
if, if-else, 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.

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

8.3 Two Way Selections


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)
printf(”Passed”);
else
printf(“failed”);

You can use as many if-statements after the else part, for example, consider the following code:

if (marks>90)
printf(“Grade is A”);

else if (marks>85)
printf(“Grade is B”);

Department of Electrical Engineering


95
else
print(“Fail”);

The above statement will output the grade “A” for all students scoring more than 90 marks.
However, the grade of the students will be B who have scored more than 85 marks and less than
90, similarly, the remaining students will get F grade. The statement will be executed in a way that
first statement will be checked, if the students marks are greater than 90, then the grade will be
shown as “A” and the remaining parts will not be executed (The else part). If the students marks
are less than 90, then the first statement would be evaluated as false, and the control will be passed
to the else if (marks >85) statement.

8.4 Compound Statement


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)
printf(”Grade is A”);
printf(”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 ….

Department of Electrical Engineering


96
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)
{
printf(”Grade is A”);
printf(”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.

Department of Electrical Engineering


97
8.5 Relational Operators

Table 8-1. Relational Operators

Operator Description Example

Checks if the value of two operands is equal


== (A == B) is not true.
or 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.

Department of Electrical Engineering


98
Activity 01:-
Write a C program to find whether the number is positive or negative.

Figure 8-1. Flow Chart

Department of Electrical Engineering


99
Activity 02:-
Write a program that get two numbers from user and check the following conditions

if both numbers are equal then print both are equal

if num1 is greater then num2 then print num1 is greater then num2

if num2 is greater then num1 then print num2 is greater then num1

Department of Electrical Engineering


100
Activity 03:-
Write a C program to find grade based on percentage using else if statement.

Figure 8-2. Grade Flow Chart

Department of Electrical Engineering


101
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


102
Department of Electrical Engineering
103
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


104
Lab 09
9 Selection Structure-I (Nested If-Else)

Objective:

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

Department of Electrical Engineering


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

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

9.2 Logical-and (&)


The same problem (discussed in section 4.1) can be solved with using logical-and operator (&)
between both conditions. For example, consider the following code:

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

printf(”Congratulations! You are eligible for the scholarship” );

Department of Electrical Engineering


106
}

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.

9.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
(nested-if or logical-and)

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


Consider the followings two codes:

9.3.1.1 Code A:
if (percentage>=70 )

if (age <16)

printf(”Congratulations! You are eligible for the scholarship” );

9.3.1.2 Code B:
if (percentage>=70 && age <16)

printf(”Congratulations! You are eligible for the scholarship” );

Department of Electrical Engineering


107
}

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.

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

Consider the following code:

if (percentage>=70 )

if (age <16)

printf(”Congratulations! You are eligible for the scholarship” );

printf(”Your percentage is more than 70” );

However, you probably, will not like to write the above code in the following way.

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

printf(”Congratulations! You are eligible for the scholarship” );

if (percentage>=70)

Department of Electrical Engineering


108
{

printf(”Your percentage is more than 70” );

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


Consider the following code.

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

printf(”Congratulations! You are eligible for the scholarship” );

else

printf(”Sorry, you did not get the scholarship” );

You will not like to write it in the following way:

if (percentage>=70 )

if (age <16)

printf(”Congratulations! You are eligible for the scholarship” );

Department of Electrical Engineering


109
else {

printf(”Sorry, you did not get the scholarship” );

else

printf(”Sorry, you did not get the scholarship” );

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

printf(”Congratulations! You are eligible for the scholarship” );

The “printf” 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.
Department of Electrical Engineering
110
9.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))

printf(”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 printf-
statement will not be executed. Similarly, we have written the previously discussed example by
incorporating logical-not (!)

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

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

Department of Electrical Engineering


111
Activity 01:-
Write a C program to find the biggest of three numbers using switch statements.

Figure 9-1. Flow Chart

Activity 02:-
Write a C program to find whether the given input is a vowel or not using logical
operators.

Department of Electrical Engineering


112
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


113
Department of Electrical Engineering
114
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


115
Lab 10
10 Selection Structure-II (Switch Statement)

Objective:

 To get basic understanding of switch statements


 To practice how to use switch statement in a C program.

Department of Electrical Engineering


116
10.1 Switch Statement
Remember, in your previous lab, you have studied a control structure, selection, using if-
statement. However, there is another way selection or branching statement in c known as switch
statement. The if-statement can be used to evaluate logical-expressions (remember logical-
operators that you studied in the Lab 4). However, the switch-statement do not require the
evaluation of logical expressions. The switch statement is used to 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 value n:

statements

break;

default:

statements….
break;

Department of Electrical Engineering


117
Where switch, case, break, and default are the reserve words and have particular meanings which
you will learn in this lab. Please note that the break statement is an optional statement. This means
you can use this statement or not depending upon the situation. You will learn the effect of
including and excluding a break statement in the next section.

The expression sometimes, is referred to, selector. First the expression in the switch statement is
evaluated. Subsequently, the corresponding case is executed. It is not mandatory that the
expression is an identifier. It can be a identifier or an expression. However, the value of the
expression should be integral only.

10.2 The break statement


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

Enter 1 to purchase products

Enter 2 to sale products

Enter 3 to see the profit statement =

In such a menu driven statement, using switch statement is encouraged. This will make your code
more readable. You can program this problem using the following code:

int option;

printf(" Enter 1 to purchase products”);

printf(" Enter 2 to sale products”);

printf(” Enter 3 to see the profit statement =”);

scanf ("%d",&option);

switch (option)

case 1:

Department of Electrical Engineering


118
printf(”You selected the option to purchase products”);

break;

case 2:

printf("You selected the option to sale products”);

break;

case 3:

printf("You selected the option to see the profit statement”);

break;

default:

printf("You have selected the wrong value”);

break;

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

Department of Electrical Engineering


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

printf("Enter 1 to purchase products”);

printf(" Enter 2 to sale products”);

printf(" Enter 3 to see the profit statement =”);

scanf ("%d", &option);

switch (option)

case 1:

printf("You selected the option to purchase products”);

case 2:

printf("You selected the option to sale products”);

case 3:

printf("You selected the option to see the profit statement”);

default:

printf"(”You have selected the wrong value”);

Department of Electrical Engineering


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

int option;

printf(" Enter 1 to purchase products”);

printf(" Enter 2 to sale products”);

printf(" Enter 3 to see the profit statement =”);

scanf ("%d", &option);

switch (option)

case 1:

printf("You selected the option to purchase products”);

Department of Electrical Engineering


121
case 2:

printf("You selected the option to sale products”);

break;

case 3:

printf("You selected the option to see the profit statement”);

default:

printf("You have selected the wrong value”);

In this switch statement, we have written a break statement after the statement associated
with case 2.

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

You selected the option to purchase products

You selected the option to sale products

The user will not get the output You selected the option to see the profit statement
because there is a break after second case.

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

You selected the option to sale products

Department of Electrical Engineering


122
The statement printf 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.

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

printf("Enter character E to change Rupee into equivalent value in Euro”);

printf("Enter character D to change Rupee into equivalent value in dollar”);

printf("Enter the character R to change Rupee into equivalent value in Riyal”);

scanf("%d", &option);

switch(option)

case ‘E’:

printf("You selected the conversion from Rupee to Euro”);

break;

case ‘D’:

Department of Electrical Engineering


123
printf("You selected the conversion from Rupee to Dollar”);

break;

case ‘R’:

printf("You selected the conversion from Rupee to Riyal”);

break;

default:

printf("Wrong input”);

There are two important points to be noted here:

1) For the character value, you need to enclose it in a singe quotation mark.
2) The program will work fine for the upper case characters only. If user enter “d” in
lowercase rather than upper case, then the program will output “printf"”Wrong input”;”.
To tackle both uppercase and lowercase character, you can write the following code:

switch(option)

case ‘E’:

case ‘e’:

printf("You selected the conversion from Rupee to Euro”);

break;

case ‘D’:

case ‘d’:

printf("You selected the conversion from Rupee to Dollar”);

Department of Electrical Engineering


124
break;

case ‘R’:

case ‘r’:

printf("You selected the conversion from Rupee to Riyal”);

break;

default:

printf("Wrong input”);

For the better understanding of this program, remember, the discussion on the break statement in
the previous section.

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

printf" “Enter your marks”;

scanf("%d",&marks);

switch(marks>=50)

case 1:

printf("Congratulations, you have qualified the examination”);

break;

case 0:

Department of Electrical Engineering


125
printf("Sorry, you have not qualified the examination ”);

break;

In this case, the expression will be evaluated as logical-true or logical-false. If the marks
are greater than or equal to 50, then the statement “ printf"”Congratulations, you have
qualified the examination”; will be executed, otherwise, the statement “ printf"”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;

printf" “Enter your marks”;

scanf("%d",&marks);

switch(marks>=50)

case true:

printf("Congratulations, you have qualified the examination”);

break;

case false:

printf("Congratulations, you have qualified the examination”);

break;

Department of Electrical Engineering


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

int value;

scanf("%d",&value);

switch (value%10)

case 0:

printf("The unit place digit is Zero”);

break;

case 1:

printf("The unit place digit is One”);

break;

case 2:

printf("The unit place digit is Two”);

break;

case 3:

printf("The unit place digit is Three”);

break;

case 4:

printf("The unit place digit is Four”);

Department of Electrical Engineering


127
break;

case 5:

printf("The unit place digit is Five”);

break;

case 6:

printf("The unit place digit is Six”);

break;

case 7:

printf("The unit place digit is Seven”);

break;

case 8:

printf"”The unit place digit is Eight”;

break;

case 9:

printf("The unit place digit is Nine”);

break;

Department of Electrical Engineering


128
Activity 01:-
Write a program to get character input from user and display whether the given
input is vowel or not.

Activity 02:-
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.

Activity 03:-
Write a program which will read two numbers and would display the following menu to the
user:

Press 1 to find the numbers are divisible by 2

Press 2 to add the two numbers

Press 3 to subtract the two numbers

Press 4 to multiply the two numbers

Press 5 to divide the two numbers

Press 6 to find whether the numbers are odd or even

Note: All the above operations would be applied on both the numbers that user reads.

Department of Electrical Engineering


129
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


130
Department of Electrical Engineering
131
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


132
Lab 11
11 Repetition Structure-I Introduction to Loops and
understanding of For-Loop

Objective:

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

Department of Electrical Engineering


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

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” 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 Printf(” 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:

for(int i=1;i<=10;i++)

printf(”Welcome to Cp Course\n”);

Department of Electrical Engineering


134
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++)

printf(”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

11.1.1 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 while-loop. First we will discuss for-loop followed by the other pre-condition loop :
while-loop.

11.1.1.1 For-Loop
Consider the code written in the previous section

for(int i=1;i<=20;i++)

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

Department of Electrical Engineering


135
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 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++)

Printf(” Welcome to Cp Course\n”);

Printf(”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;)

{ printf(” Welcome to Cp Course\n”);

Printf(”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:

Department of Electrical Engineering


136
int i=20;

for(;i>=1;)

printf(” Welcome to Cp Course\n”);

printf(”Hello class”;

i--;

We have used decrement instead of increment. This means we have counted the loop from
20 towards However, please note, we have also changed the condition as well. Now we
are starting loop from 20 and need to execute statements until the i remains greater of
equal to 1.

d) If we start a loop from 20 and do not change the condition, then guess what will
happen.

int i=20;

for(;i<=20;)

{ printf(” Welcome to Cp Course\n”);

Printf(”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

Department of Electrical Engineering


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

Activity 01:-
Write a program to print “Hello word” ten times using for loop.

Activity 02:-
Write a program that get a number num from user and print the “Hello word”
num times.

Activity 03:-
Write a program that get a number num from user and print the integers from
0 to num using for loop.

Activity 04:-
Write a program that get a number num from user and print the even integers
from 0 to num using for loop.

Activity 05:-
Write a program that calculates the sum of integers from 0 to num using for
loop. Num should be entered by the user.

Activity 06:-
Write a program that print table of 2 from 1 to 20 by using For loop.

Department of Electrical Engineering


138
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


139
Department of Electrical Engineering
140
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


141
Lab 12
12 Repetition Structure-II Understanding and
implementation of While-Loop & Do-While-Loop

Objective:

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

Department of Electrical Engineering


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

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

Printf(” Welcome to Cp Course\n”);

To achieve this, you know that you can write 10 statements in the following manner:

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

Printf(” Welcome to Cp Course\n”);

Printf(”Hello class”);

Department of Electrical Engineering


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

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

int marks;

int sum=0;

const int sentinel=-1; /// the marks of a student can not be negative.

Printf(”Enter the marks of the student”);

Scanf(“%d”,&marks);

while(marks!=sentinel)

sum=sum+marks;

Scanf(“%d”,&marks);

Printf(”The total marks of this students are %d”, sum);

Department of Electrical Engineering


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

Activity 01:-
Write a program to print “Hello word” ten times using while loop.

Activity 02:-
Write a program that get a number num from user and print the “Hello
word” num times.

Activity 03:-
Write a program that get a number num from user and print the integers
from 0 to num using while loop.

Activity 04:-
Write a program that get a number num from user and print the even
integers from 0 to num using while loop.

Activity 05:-
Write a program that calculates the sum of integers from 0 to num using while
loop. Num should be entered by the user.

Activity 06:-
Write a program that print table of 2 from 1 to 20 by using While loop.

Department of Electrical Engineering


145
Activity 07:-
Write the output of the following programs.

Activity 7.1:-

#include <stdio.h>
main()
{
int count=1;
while (count <=4)
{
printf("%d ", count);
count++;
}
}

Activity 7.2:-

#include <stdio.h>
main()
{
int var=1;
while (var <=2)
{
printf("%d ", var);
}
}

Department of Electrical Engineering


146
Activity 7.3:-

#include <stdio.h>
int main()
{
int var =6;
while (var >=5)
{
printf("%d", var);
var++;
}
return 0;
}

Activity 7.4:-

#include <stdio.h>
int main()
{
int var =5;
while (var <=10)
{
printf("%d", var);
var--;
}
return 0;
}

Department of Electrical Engineering


147
Activity 7.5:-
#include <stdio.h>

main()
{
int i = 10;

while ( i > 0 )
{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}
}

Department of Electrical Engineering


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

Activity 08:-
Write a program to print “Hello word” ten times using do while loop.

Activity 09:-
Write a program that get a number num from user and print the “Hello
word” num times.

Activity 10:-
Write a program that get a number num from user and print the integers
from 0 to num using do while loop.

Activity 11:-
Write a program that get a number num from user and print the even
integers from 0 to num using do while loop.

Activity 12:-
Write a program that calculates the sum of integers from 0 to num using while
loop. Num should be entered by the user.
Department of Electrical Engineering
149
Activity 13:-
Write a program that print table of 2 from 1 to 20 by using Do-While loop.

Activity 14:-
Write the output of the following programs.

Activity 14.1:-
#include <stdio.h>

main()
{
int i = 10;

do{
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
}

Department of Electrical Engineering


150
Activity 14.2:-
#include <stdio.h>

main()
{
int i = 10;

do{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}while ( i > 0 );
}

Department of Electrical Engineering


151
Lab Exercise and Summary

Summary should cover Introduction, Procedure, Data Analysis and Evaluation.

Department of Electrical Engineering


152
Department of Electrical Engineering
153
LABORATORY SKILLS RUBRIC (Cognitive)

Total Marks: 40
Criteria Level 1 Level 2 Level 3 Level 4
Score
(Max. Marks) 0% ≤ S < 50% 50% ≤ S < 70% 70% ≤ S < 90% 90% ≤ S ≤ 100%
Introduction Very little Introduction is brief Introduction is nearly Introduction complete
(5) background with some minor complete, missing some and well-written;
information mistakes minor points provides all necessary
provided or background principles
information is for the experiment
incorrect
Procedure Many stages of the Many stages of the The procedure could be The procedure is well
(5) procedure are not procedure are entered more efficiently designed designed and all stages
entered on the lab on the lab report. but most stages of the of the procedure are
report. procedure are entered on entered on the lab
the lab report. report.
Data Record Data is brief and Data provides some Data is almost complete Data is complete and
(10) missing significant significant information but has some minor relevant. Tables with
pieces of and has few critical mistakes. units are provided.
information. mistakes. Graphs are labeled. All
questions are answered
correctly.
Data Analysis Data are presented in Data are presented in Data are presented in Data are presented in
(10) very unclear ways (charts, tables, ways (charts, tables, ways (charts, tables,
manner. Error graphs) that are not graphs) that can be graphs) that best
analysis is not clear enough. Error understood and facilitate
included. analysis is included. interpreted. Error understanding and
analysis is included. interpretation. Error
analysis is included.
Report Report contains Report is somewhat Report is well organized Report is well
Quality many errors. organized with some and cohesive but contains organized and
(10) spelling or grammatical some grammatical errors. cohesive and contains
errors. no grammatical errors.
Presentation seems
polished.

Marks Obtained

Department of Electrical Engineering


154

You might also like