Vous êtes sur la page 1sur 77

Iqra University IU

Islamabad Campus

Lab Manual

(Intro. To Computer Science)

(BS (CS) & BSTN)

Student Name: ________________________

Student ID: ___________________________

Department of Computing and Technology

IQRA University Islamabad Campus

Fall 2010
Intro To CS IQRA University

Contents
Contents..................................................................................................................... 3
Lab 01: Create a Bibliography....................................................................................4
Lab: 02: Create a Table of Contents...........................................................................8
MARK ENTRIES BY USING BUILT-IN HEADING STYLES...........................................8
Lab 03: Mail Merge Application.................................................................................12
USE MAIL MERGE IN WORD TO CREATE A DOCUMENT OR E-MAIL MESSAGE
ADDRESSED TO ACCOUNTS OR BUSINESS CONTACTS.......................................12
USE MAIL MERGE IN PUBLISHER WITH A PUBLICATION TARGETED TOWARD
ACCOUNTS OR BUSINESS CONTACTS.................................................................13
USE MAIL MERGE IN WORD OR PUBLISHER THROUGH A MARKETING CAMPAIGN
........................................................................................................................... 14
PRINT MAILING LABELS USING ACCOUNT, BUSINESS CONTACT, OR BUSINESS
LEAD RECORDS.................................................................................................. 14
PRINT ENVELOPES USING ACCOUNT, BUSINESS CONTACT, OR BUSINESS LEAD
RECORDS...........................................................................................................15
Lab: 04 (A): Pivot Tables in Excel 2007 ....................................................................22
Lab: 04 (B): Pivot Tables in Excel 2007.....................................................................30
The reason why the scores from our Pivot Table are so strange is because Excel
2007 is using the wrong formula. It's using a Sum total when we want it to use an
Average.................................................................................................................... 30
Lab 06: Programming, Debugging, Microsoft Visual C++.........................................34
Lab 07: Variables, Arithmetic Operators, Decision Control Structures......................41
Lab: 07: Variables, Arithmetic Operators, Decision Control Structures.....................41
Lab 08: Decision Control Statements.......................................................................50
Lab: 07: Variables, Arithmetic Operators, Decision Control Structures.....................50
Lab 09: for loop, while loop......................................................................................55
Lab: 09: for loop, while loop.....................................................................................56
The while loop:.........................................................................................................58
Lab 10: Do-While, Continue, Switch, Break...............................................................63
Lab: 10: Do-While, Continue, Switch, Break..............................................................65

Lab 01: Create a Bibliography


Intro To CS IQRA University

Lab 11: Functions..................................................................................................... 66


Lab: 11: Functions.................................................................................................... 70
Lab 12: Functions (Call By Reference and By Value)................................................71
Lab: 12: Functions (Call by Reference and by Value)...............................................73
Lab 13: Arrays.......................................................................................................... 74
Declaration of Array...........................................................................................74
Initialization of Array..........................................................................................74
Accessing elements of Array..............................................................................74
Printing arrays....................................................................................................74
Copying arrays................................................................................................... 74
Scanning array elements using cin....................................................................74
Dealing with characters using arrays.................................................................74
Lab: 13: Arrays.........................................................................................................77

Lab 01: Create a Bibliography


A bibliography is a list of sources, usually placed at the end of a document that you consulted or
cited in creating the document. In Microsoft Word 2010, you can automatically generate a
bibliography based on the source information that you provide for the document.
Each time that you create a new source, the source information is saved on your computer, so
that you can find and use any source you have created.
You can choose the bibliography style that you want, and you can add new bibliography styles.
Objectives of this Lab:
• Add a new citation and source to a document
• Find a source
• Edit a citation placeholder
• Create a bibliography

Add a New Citation and source to a document

When you add a new citation to a document, you also create a new source that will appear in the
bibliography.

Lab 01: Create a Bibliography


Intro To CS IQRA University

1. On the References tab, in the Citations & Bibliography group, click the arrow next
to Style.

2. Click the style that you want to use for the citation and source
3. For example, social sciences documents usually use the MLA or APA styles for citations
and sources
4. Click at the end of the sentence or phrase that you want to cite.
5. On the References tab, in the Citations & Bibliography group, click Insert Citation.

6. Do one of the following:


• To add the source information, click Add New Source.
• To add a placeholder, so that you can create a citation and fill in the source
information later, click Add New Placeholder. A question mark appears next to
placeholder sources in Source Manager.
7. Begin to fill in the source information by clicking the arrow next to Type of source.
For example, your source might be a book, a report, or a Web site.
8. Fill in the bibliography information for the source.
To add more information about a source, click the Show All Bibliography Fields check box.

• If you choose a GOST or ISO 690 style for your sources and a citation is not unique,
append an alphabetic character to the year. For example, a citation would appear as
[Pasteur, 1848a].
• If you choose ISO 690-Numerical Reference and your citations still don't appear
consecutively, you must click the ISO 690 style again, and then press ENTER to
correctly order the citations.

Find a Source:

The list of sources that you consult or cite can become quite long. At times you might search for
a source that you cited in another document by using the Manage Sources command.

Lab 01: Create a Bibliography


Intro To CS IQRA University

1. On the References tab, in the Citations & Bibliography group, click Manage Sources.

If you open a new document that does not yet contain citations, all of the sources that you used in
previous documents appear under Master List.
If you open a document that includes citations, the sources for those citations appear
under Current List. All the sources that you have cited, either in previous documents or in the
current document, appear under Master List.
2. To find a specific source, do one of the following:
• In the sorting box, sort by author, title, citation tag name, or year, and then search
the resulting list for the source that you want to find.
• In the Search box, type the title or author for the source that you want to find.
The list dynamically narrows to match your search term.
NOTE You can click the Browse button in Source Manager to select another master list from
which you can import new sources into your document. For example, you might connect to a file
on a shared server, on a research colleague's computer or server, or on a Web site that is hosted
by a university or research institution.
Edit a Citation Placeholder

Occasionally, you may want to create a placeholder citation, and then wait until later to fill in the
complete bibliography source information. Any changes that you make to a source are
automatically reflected in the bibliography, if you have already created one. A question mark
appears next to placeholder sources in Source Manager.
1. On the References tab, in the Citations & Bibliography group, click Manage Sources.

2. Under Current List, click the placeholder that you want to edit.
NOTE Placeholder sources are alphabetized in Source Manager, along with all other sources,
based on the placeholder tag name. Placeholder tag names are numbers by default, but you can
customize the placeholder tag name with whatever tag you want.
3. Click Edit.
4. Begin to fill in the source information by clicking the arrow next to Type of source.
For example, your source might be a book, a report, or a Web site.

Lab 01: Create a Bibliography


Intro To CS IQRA University

5. Fill in the bibliography information for the source. Use the Edit button to fill in fields
instead of having to type names in the appropriate format.
To add more information about a source, click the Show All Bibliography Fields check box.
Create a Bibliography

You can create a bibliography at any point after you insert one or more sources in a document. If
you don't have all of the information that you need about a source to create a complete citation,
you can use a placeholder citation, and then complete the source information later.
NOTE Placeholder citations do not appear in the bibliography.
1. Click where you want to insert a bibliography, usually at the end of the document.
2. On the References tab, in the Citations & Bibliography group, click Bibliography.

3. Click a predesigned bibliography format to insert the bibliography into the document.

Lab 01: Create a Bibliography


Intro To CS IQRA University

Lab: 02: Create a Table of Contents

You create a table of contents by applying heading styles — for example, Heading 1, Heading 2,
and Heading 3 — to the text that you want to include in the table of contents. Microsoft Word
searches for those headings and then inserts the table of contents into your document.
When you create a table of contents this way, you can automatically update it if you make
changes in your document.
Microsoft Word 2010 provides a gallery of automatic table of contents styles. Mark the table of
contents entries, and then click the table of contents style that you want from the gallery of
options.
You can also create a custom table of contents with the options you choose and any custom
styles that you've applied by using the Table of Contents dialog box.
This article explains how to add a table of contents. It does not cover tables of authorities or
tables of figures.

Objectives of this lab:


• Mark entries for a table of contents
• Create a table of contents from the gallery
• Create a custom table of contents
• Update the table of contents
• Delete a table of contents

Mark entries for a table of contents:

The easiest way to create a table of contents is to use the built-in heading styles. You can also
create a table of contents that is based on the custom styles that you have applied. Or you can
assign the table of contents levels to individual text entries.

MARK ENTRIES BY USING BUILT-IN HEADING STYLES


1. Select the text that you want to appear in the table of contents.
2. On the Home tab, in the Styles group, click the style that you want.

Lab: 02: Create Table of Contents


Intro To CS IQRA University

For example, if you selected text that you want to style as a main heading, click the style
called Heading 1 in the Quick Style gallery.

• If you don't see the style that you want, click the arrow to expand the Quick Style gallery.
• If the style that you want does not appear in the Quick Style gallery, press
CTRL+SHIFT+S to open the Apply Styles task pane. Under Style Name, click the style
that you want.

Create a table of contents from the gallery:


After you mark the entries for your table of contents, you are ready to build it.
1. Click where you want to insert the table of contents, usually at the beginning of a
document.
2. On the References tab, in the Table of Contents group, click Table of Contents, and
then click the table of contents style that you want.

NOTE If you want to specify more options — for example, how many heading levels to
show — click Insert Table of Contents to open the Table of Contentsdialog box. To find out
more about the different options, see Format the table of contents.

Create a custom table of contents:

1. On the References tab, in the Table of Contents group, click Table of Contents, and
then click Insert Table of Contents.

2. In the Table of Contents dialog box, do any of the following:


• To change how many heading levels are displayed in the table of contents, enter
the number that you want in the box next to Show levels, under General.
• To change the overall look of your table of contents, click a different format in
the Formats list. You can see what your choice looks like in the Print
Preview and Web Preview areas.
• To change the type of line that appears between the entry text and the page
number, click an option in the Tab leader list.

Lab: 02: Create Table of Contents


Intro To CS IQRA University

• To change the way heading levels are displayed in the table of contents,
click Modify. In the Style dialog box, click the level that you want to change, and
then click Modify. In the Modify Style dialog box, you can change the font, the
size, and the amount of indentation.
3. To use custom styles in the table of contents, click Options, and then do the following:
1. Under Available styles, find the style that you applied to the headings in your document.
2. Under TOC level, next to the style name, type a number from 1 to 9 to indicate the level
that you want the heading style to represent.
NOTE If you want to use only custom styles, delete the TOC level numbers for the built-in
styles, such as Heading 1.
3. Repeat step 1 and step 2 for each heading style that you want to include in the table of
contents.
4. Click OK.
4. Choose a table of contents to fit the document type:
• Printed document If you are creating a document that readers will read on a printed
page, create a table of contents in which each entry lists both the heading and the page
number where the heading appears. Readers can turn to the page that they want.
• Online document For a document that readers will read online in Word, you can
format the entries in the table of contents as hyperlinks, so that readers can go to a heading
by clicking its entry in the table of contents.

Update the table of contents:


If you added or removed headings or other table of contents entries in your document, you can
quickly update the table of contents.
1. On the References tab, in the Table of Contents group, click Update Table.

2. Click Update page numbers only or Update entire table.

Delete a table of contents:


1. On the References tab, in the Table of Contents group, click Table of Contents.

Lab: 02: Create Table of Contents


Intro To CS IQRA University

2. Click Remove Table of Contents.

Lab: 02: Create Table of Contents


Intro To CS IQRA University

Lab 03: Mail Merge Application

You can use the mail merge feature in Microsoft Office Word 2007 or Office Publisher 2007 to
create personalized letters or e-mail messages, as well as mailing labels and envelopes from the
data in your Account or Business Contact records.
Objectives of This Lab:
• Use mail merge in Word to create a document or e-mail message addressed to
Accounts or Business Contacts
• Use mail merge in Publisher with a publication targeted toward Accounts or
Business Contacts
• Use mail merge in Word or Publisher* through a Marketing Campaign
• Print mailing labels using Account, Business Contact, or Business Lead records
• Print envelopes using Account, Business Contact, or Business Lead records

USE MAIL MERGE IN WORD TO CREATE A DOCUMENT OR E-MAIL MESSAGE


ADDRESSED TO ACCOUNTS OR BUSINESS CONTACTS

For help with using mail merge in Word 2007, see Use mail merge to create and print letters and
other documents and Use mail merge to send personalized e-mail messages to your e-mail
address list.
In Word 2007, either create a new document, or open an existing one.
To create a new mail merge document, click the Mailings tab. On the Ribbon, in the Start Mail
Merge group, click Start Mail Merge, and then select the type of document you want to create.
1. In an existing document, click the Mailings tab.
2. On the Ribbon, in the Start Mail Merge group, click Select Recipients, and then
click Select from Outlook Contacts.
3. In the Select Contacts dialog box, select the Business Contact Manager folder you want
to use, and then click OK.
4. In the Mail Merge Recipients list, click the options that you want to use to refine the
recipient list.
To remove a recipient from the list, clear the check box of the recipient, and then click OK.
5. To insert fields from your records in Business Contact Manager for Outlook into the
document, on the Ribbon, in the Write & Insert Fields group, click either Address
Block, Greeting Line, or Insert Merge Field.
You can only insert fields that are included by default in your Business Contact Manager
records. You cannot insert user-defined fields and business Contact fields for use in mail merge
documents

Lab: 03: Mail Merge Application


Intro To CS IQRA University

6. To see what the document will look like, on the Ribbon, in the Preview Results group,
click Preview Results.
7. On the Ribbon, in the Finish group, click Finish & Merge, and select how you want to
produce the document.
TIP If you are using these letters or messages to market your products or services, you may
want to create a Marketing Campaign so you can track the results of your document,
To create a Marketing Campaign from your merged document, in Word, on theMailings tab, in
the Marketing group, click Create Campaign. A Marketing Campaign form opens in Outlook.
For more information about completing the Marketing Campaign form, see Marketing Campaign
form General View in Business Contact Manager.
You can also use the E-Mail Marketing Service to send and track targeted e-mail messages to
your Accounts or Business Contacts, as well as other distribution lists.
NOTE If you use the E-Mail Marketing Service, you cannot use mail merge in Publisher to
create your e-mail message. For more information about the E-Mail Marketing Service,
see Using the E-Mail Marketing Service in Business Contact Manager.

USE MAIL MERGE IN PUBLISHER WITH A PUBLICATION TARGETED TOWARD


ACCOUNTS OR BUSINESS CONTACTS

For help with using mail merge in Publisher 2007, see Create a mail merge in the Publisher 2007
Help.
1. In Publisher 2007, either create a new publication or open an existing one.
2. On the Tools menu, point to Mailings and Catalogs, and then click Mail Merge.
3. Follow the steps in the Mail Merge Task Pane.
a. Step 1: Create recipient list
a. Click Select from Outlook Contacts, and then click Next.
b. Select the Business Contact Manager folder you want to use.
c. In the Mail Merge Recipients dialog box, sort or filter the list to select
the names you want to use.
b. Step 2: Prepare your publication
a. In the Mail Merge task pane, drag the Account or Business Contact fields
to their new location in the publication.
b. Click Preview recipient to see what the publication looks like for each
recipient.
a. Step 3: Create merged publications
a. Select how to create your merged publications.
b. Select what to do with your new recipient list.

Lab: 03: Mail Merge Application


Intro To CS IQRA University

c. Select whether to track this through Business Contact Manager for


Outlook, which will open a new Marketing Campaign form.

USE MAIL MERGE IN WORD OR PUBLISHER THROUGH A MARKETING


CAMPAIGN

1. On the Business Contact Manager menu, click Marketing Campaign, and then
click New.
2. Create a new Marketing Campaign, selecting as a Marketing Campaign type
either Direct Mail or E-mail, so that you can use mail merge in Word or Publisher*.
3. Under Who will see it?, select an existing list of names or create a new list.
TIP You can modify this list by clicking Review and Filter.
4. Under How will they get it?, select either Word Mail Merge or Publisher Mail Merge.
5. Under What will they get?, browse for an existing file in either in Word or Publisher*. If
you want to change the file, click Edit.
6. In the Ready to launch box, click the Launch button.
7. Your file opens in Word or Publisher with the Mail Merge Task Pane also open. Your
document has been completed.
8. To continue, see the following instructions for previewing and printing in Word 2007.

PRINT MAILING LABELS USING ACCOUNT, BUSINESS CONTACT, OR BUSINESS


LEAD RECORDS

For help with printing labels in Word 2007, see Create and print labels for a mass mailing.
1. Start Word 2007.
A blank document opens by default.
2. Click the Mailings tab.
3. In the Ribbon, in the Start Mail Merge group, click Start Mail Merge.
4. Click Labels.
5. In the Label Options dialog box, select the options that you want, and then click OK.
6. In the Ribbon, in the Start Mail Merge group, click Select Recipients.
7. Click Select from Outlook Contacts.
8. In the Select Contacts dialog box, click the Business Contact Manager folder that you
want to use, and then click OK.
9. In the Mail Merge Recipients list, all the names are selected by default. Click to clear
the check box of the names that you do not want to print, and then click OK.

Lab: 03: Mail Merge Application


Intro To CS IQRA University

10. Click the initial label in the Word document.


11. On the Mailings tab, in the Write & Insert Fields group, click Address Block.
12. In the Insert Address Block dialog box, click the options that you want, and then
click OK.
13. On the Mailings tab, in the Write & Insert Fields group, click Update Labels.
The content of the first label is replicated to all the other labels.
14. If you want to preview the labels, in the Preview Results group, click Preview Results.
15. To print the labels, in the Finish group, click Finish & Merge, and then click Print
Documents.
PRINT ENVELOPES USING ACCOUNT, BUSINESS CONTACT, OR BUSINESS LEAD
RECORDS
For help with printing envelopes in Word 2007, see Create and print envelopes for a mass
mailing.
1. Start Word 2007.
A blank document opens by default.
2. Click the Mailings tab.
3. In the Ribbon, in the Start Mail Merge group, click Start Mail Merge.
4. Click Envelopes.
5. In the Envelope Options dialog box, select the options that you want, and then click OK.
6. In the Ribbon, in the Start Mail Merge group, click Select Recipients.
7. Click Select from Outlook Contacts.
8. In the Select Contacts dialog box, click the Business Contact Manager folder that you
want to use, and then click OK.
9. In the Mail Merge Recipients list, all the names are selected by default. Click to clear
the check box of the names that you do not want to print, and then click OK.
10. Click the section where the recipient's addresses will be listed.
11. On the Mailings tab, in the Write & Insert Fields group, click Address Block.
12. In the Insert Address Block dialog box, click the options that you want, and then
click OK.
13. In the Ribbon, in the Preview Results group, click Preview Results.
14. In the Ribbon, in the Finish group, click Finish & Merge, and then click Print
Documents.

Lab: 03: Mail Merge Application


Intro To CS IQRA University

Lab 01: Introduction to Microsoft Excel 2007

Objectives of this Lab:

• To Cover Some Basics of The Excel 2007


• Introduction Of Excel Formulas
• IF Statement

Starts excel:
1. Open the task pane: Menubar > View > Taskpane
2. Click Task pane drop‐down arrow; view task pane windows
Workbook: A collection of related worksheets contained within a single file.
3. Open the file: first‐gradebook.xls
4. Save the file as first‐gradebookSolution.xls.

The Active Cell, Formula Bar & Worksheet Tabs:

1. Click in cell B3, the cell containing Ackerman’s grade on the first test. Cell
B3 is now the active cell (surrounded by a heavy border). You can see the cell name
the three in the name box and the formula is displayed in the formula box.
2. Click in cell B4 (or press the down arrow) to make it the active cell; check
the name box and the formula box to see the contents of B4.
3. Click cell E3, Ackerman’s semester average. Active cell displays the computed
grade, but formula bar displays the formula.
4. Click the Anthro264 tab to view a different worksheet within the same
workbook
5. Click the Anthro 341 have to view this worksheet; Click the Anthro 128 tab
return to the original worksheet.

Widen Columns to see all data


1. Putting your cursor in the column headings, select all the active columns in the
worksheet.
2. While the columns are still selected, move your cursor to any line between
the two columns. Your cursor will become a double headed arrow. Double‐click on
the line and the columns will all automatically adjust to the correct width.

Sort gradebook alphabetically by last name:


1. Select the range A1: A25
2. Go to the ribbon > Home tab >Editing > Sort and filter > Sort A to Z.
3. Excel will ask you if you want to expand the selection. Click yes.
4. Ackerman and Benneman will still be first and second, but the rest of the grades
will be sorted by last name of the student.

Lab: 04: Microsoft Excel Basics


Intro To CS IQRA University

Color Worksheet Tabs:


1. Click worksheet tab (of sheet to be colored).
2. Menubar > Format > Sheet > Tab Color to display a color palette.
3. Select desired color and click OK.
4. You can also right‐click the worksheet tab to display a context‐sensitive menu,
including color choices.

Total by selecting and adding cells:


1. Click in cell F3 (Ackerman’s test total).
2. We could enter each grade as a number, but this will not allow us to
automatically calculate any changes in the grade sheet.
3. What we want to do is enter each grade as a reference to the cell that contains
that grade.
4. All formula must begin with an =, so type an =
5. Now click on B3, press the + and click on C3, add another +, Click on D3, add
another + and finally click on E3

6. Hit enter and Ackerman’s grade will show a total of 331.

Total using autoSum:

1. Click in cell F4 (Ackerman’s test total)

2. Go to the ribbon >Home >Editing > Click AutoSum

3. The formula will appear: =SUM(B4:E4)


4. Check your formula. If you get a different cell range, you can click and drag
over the desired cells.
5. Press the enter key.
6. Benneman’s grade will show a total of 331.

Completing the Calculations Using the AutoFill option:

1. Click in cell F4. You will notice a small black square in the lower right corner
of the selected square.
2. If you put your cursor over it, your cursor becomes a crosshair. While your
cursor is a crosshair, click and drag from cell F4 down to cell F25.
3. All of the student’s test totals should fill in automatically.
4. Click in cell F13. You will see the formula: =SUM(B13:E13)
5. Click in cell F20. You will see the formula: =SUM(B20:E20)
6. These formulas are all based on our original formula in cell F4. As we dragged
the formula down, the cell references also moved down.

Lab: 04: Microsoft Excel Basics


Intro To CS IQRA University

Calculate the test average using autoSum with the Average function:
1. Click in cell G3 (test average), then click
the down arrow next to the autoSum button.
2. Select Average. Excel will automatically select the cell range B3:F3

3. We do not want cell E3 selected. E3 is the test total. Click and drag to adjust
the cell range to B3:E3

4. Press the Enter key. You will get a test average of 82.75.
Completing the Calculations Using the AutoFill option:
1. Click in cell G4. You will notice a small black square in the lower right corner
of the selected square. If you put your cursor over it, your cursor becomes a crosshair.
While your cursor is a crosshair, click and drag from cell G4 down to cell G25.
2. All of the student’s test averages will fill in automatically.

3. Notice that they appear as a number with decimal places. To remove the
decimal places, click the Decrease Decimals button (in the Numbers section on the
Home tab of the ribbon) twice.
Repeat the same Average autoSum calculations on row 27, Class Average:
1. Click in cell B27. Go to the autoSum button drop‐down arrow and select the
Average function
2. The formula should read: =Average(B3:B26)

3. Adjust your range as necessary.


4. Then click and drag using AutoFill to complete the Class Average calculations
(drag across through cell F27).
5. Decrease the decimal places.
Resize columns:
1. Your data may not be visible in B27. Instead it you may see a series of # . .
This means the column is too narrow, and you need to resize it.
2. In fact, we should probably resize all of the columns so that their headers are all
visible.
3. Click in the headers row to select the all of the columns A – H.

4. Move your mouse pointer onto the column's edge; the pointer becomes a double
headed arrow.

5. Double click and the column will automatically resize to the correct width.

Experiment (What If?):

Lab: 04: Microsoft Excel Basics


Intro To CS IQRA University
1. Click in cell C4 (Benneman’s grade on test 2) Enter a corrected value of 86;
2. Observe effects of this change: Benneman’s average has now changed and
the class average has changed as well.

Calculate the highest grade using autoSum’s Max function:


1. Click in the cell B28. Go to the autoSum button drop‐down arrow and select
the Max function
2. Be sure to a just your cell range to include only cells B3:B25
3. Do not include the Test Average (cell B27)

4. Press enter to complete the calculation.


5. Drag across using the AutoFill function through cell F28.

Calculate the lowest grade using autoSum’s Min function:


1. Click in the cell B29. Go to the autoSum button drop‐down arrow and select
the Min function
2. Be sure to a just your cell range to include only cells B3:B25
3. Do not include the Test Average (cell B27) or Highest Grade (cell B28)

4. Press enter to complete the calculation.


5. Drag across using the AutoFill function through cell F29.

Calculate Pass/Fail:
Excel can automatically calculate grades or other binary decision‐making based on
input. This requires the use of the If function. To use a function, first click in the cell
or you want the function to be. Then,
Click the Insert Function button next to the formula box.
This will open the function dialog box.
1. Click in cell H3.

2. Click the Insert Function button


3. This will open the Insert Function Dialog Box.

Lab: 04: Microsoft Excel Basics


Intro To CS IQRA University
4. Select the If function and click OK.
5. The formula that we want to enter is =IF(G3>=68,"Pass","Fail") What this says is if the number in cell
G3 is greater than or equal to 68, then pass; otherwise fail.

6. In the Function Arguments dialog box, click on


the grid next to Logical_test.
7. In the next dialog box, click in cell G3, which
will enter the cell reference into the Function Argument
8. In the Function Arguments box, type the rest of the
formula: G3>=68

9. Press Enter key


10. Value_if_true is Pass
11. Value_if_false is Fail

12. Click OK. You should get the result that Ackerman passed
13. Use the AutoFill function to drag the formula down through cell G25. Only two people Failed the
course.

Ways to access help in Excel 2007:

1. Click Key F1. This will open the “help window” (which strongly resembles the help task pane).

2. Click the blue ? in the upper right corner.


This will also open the “help window”
Lab: 04: Microsoft Excel Basics
Intro To CS IQRA University

Lab: 04: Microsoft Excel Basics


Intro To CS IQRA University

Lab: 04 (A): Pivot Tables in Excel 2007

A Pivot Table is way to present information in a report format. The idea is that you can click
drop down lists and change the data that is being displayed. For example, choose just one student
from a drop down list and view only his or her scores. Pivot tables are a lot easier to grasp when
you see them in action. Here's the one we're going to create in this section:

Look at Row 4. This shows that the student is Elisa. If we click Elisa's drop down arrow, we'll
see this:

Now we have another student to select (we'll only use two students, for this tutorial). We could
untick Lisa, and tick Mary instead. Then her scores would display.

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

The Subject and Month cells also have drop down lists. So we could view only January's scores,
and just for Art and English, for example.
So this is a Pivot Table - a report that we can manipulate by selecting items from drop down lists.
Let's make a start.

The first thing you need for a Pivot Table is some data to go in it.

The Pivot Table Data in an Excel 2007 Spreadsheet (New window)

Highlight the data that will be going in to your Pivot Table. On the Excel 2007 menu bar,
click Insert. From the Insert menu, locate the Tables Panel:

On the Tables panel click Pivot Tables. The Create Pivot Tables dialogue box appears:

In the dialogue box above, the data that we highlighted is in the Table/Range textbox. You can
select different cells by clicking the icon to the right of the Table/Range textbox. You can also
specify an external data source, such as a text file, for the data in your Pivot Table.

We've selected a New Worksheet as the place where the Pivot Table will be placed. Click OK.

When you click OK, Excel 2007 presents you with a rather complex layout. The area on the right
should look something like this one below:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

It helps to have a look again at what we're trying to create. Here's the completed Pivot Table
again:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

Now take a look at the Pivot Table Field List image again, the one above the completed pivot
table. It has tick boxes for Month, Subject, Student, and Score. These are column headings from
the original spreadsheet data. We've put the Month in cell A7 on our Pivot Table, Subject is in
cell B6, Student is in cell B4, and Score is the Average scores in cells C8 to G10. You'll see how
it works, though.

The idea is that you tick a box in the Pivot Table Field List, and then drag it to the four areas
below. Excel 2007 will take care of the rest.

So, tick all four boxes in the field list:

Excel will create a basic (and messy) Pivot Table for you. But we're going to put our 4 fields into
the 4 areas below. Here's the 4 areas we can drag to:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

For the Report Filter, we want the name of a Student. For the Column Labels, we want the
Subject, and for the Row Labels, we'll just have the Month. The Values will be the Average
scores.

If you look at the Field areas after you have ticked all four boxes, however, you may see
something like this:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

Month, Subject and Student have all been grouped under Row Labels. You can drag and drop
these, though.

So click on Student in the Row Labels box. Hold down your left mouse button, and then drag it
in to the Report Filter box. If you don't fancy dragging and dropping, simply click the Student
item with your left button. From the menu that appears, select Move to Report Filter:

Your Field areas will then look like this:

Move Subject from Row Labels to the Column Labels area:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

Your Field areas will then look like this:

The Pivot Table on your spreadsheet will look a lot different, too. It should be looking like this:

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

Our Pivot Table is coming along, but the scores are all wrong, and it needs tidying up a bit. We'll
continue this tutorial in the next part.

Lab: 04: Pivot table in Excel 2007 (Part A)


Intro To CS IQRA University

Lab: 04 (B): Pivot Tables in Excel 2007

The reason why the scores from our Pivot Table are so strange is because Excel 2007 is using the
wrong formula. It's using a Sum total when we want it to use an Average.

Here's the Pivot Table so far:

The numbers have all been added up. But we want averages, instead. To change the formula,
click on Sum of Score under the Values field area:

You'll see the following menu:

Lab: 05: Pivot Table in Excel 2007 (Part B)


Intro To CS IQRA University

Select, Field Settings to see the following dialogue box:

Change the Formula from Sum to Average, and then click OK. Your Average formula won't be
formatted to any decimal places. So highlight you data. On the Home menu in Excel 2007, locate
the Number panel. Format your Averages so that it has no decimal places. Your Pivot Table will
then look like this:

Lab: 05: Pivot Table in Excel 2007 (Part B)


Intro To CS IQRA University

Almost there!

Look at cells A3, B3 and A4 above. These all have the not very descriptive names of Average of
Score, Column Labels, and Row Labels. You can click inside of these cells and type your own
headings, in exactly the same way as you would to enter text in a normal cell.

In the new version of the Pivot Table below, we have renamed these cells. We've also centred the
data.

Only one thing left to do - spruce up the table by adding a bit of colour.

Click anywhere on your Pivot Table to highlight it. Now look at the menu bar at the top of Excel
2007. You'll notice a Design menu. Click on this to see the various design options.

The Pivot Table Style Options panel is interesting.

Select Banded Rows and see what happens. Now click Banded Columns.

Next to this panel, there are lots of Pivot Table Styles to chose from. Select one that catches your
eye. Here's our finished Pivot Table again, only with a different Style:

Lab: 05: Pivot Table in Excel 2007 (Part B)


Intro To CS IQRA University

And here's the original:

There's a lot more you can do with Pivot Tables, but we hope that this introduction has whetted
your appetite!

Lab: 05: Pivot Table in Excel 2007 (Part B)


Intro To CS IQRA University

Lab 06: Programming, Debugging, Microsoft Visual C++


Introduction:

The aim of this lab is to create a new project in Microsoft Visual C++ and debug the very first
program in this environment.

Objectives of this Lab:

• To learn about Microsoft Visual C++

• Making a project

• Adding source files to the Project created.

• Writing First program in Visual C++

• Debugging

How to create a small program in Visual C++ 6.0:

Step 1:

First of all click on Start Menu  All Programs  Microsoft Visual Studio 6.0  Visual C++
6.0

This would launch the following window

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Step 2:

Go to File Menu and click the following window click New ..

This would launch the following window. Remember this step is very important you have to be
careful. Visual C++ 6.0 is a very powerful software so you need to be clear on what you want to
do. Click on the Windows Console Application and then click on the project name write
“20090145_Lab3”. Change the roll number according to your own rollnumber. Then click OK.

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Step 3:

After clicking the OK in the step 2, you will see the following window. Let the empty project
option selected and click on Finish. After that you will see another window click OK

Click on finish and the following window will appear.

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Step 4:

Now go to File Menu again and click “New…” you will see the following window. Select the
option C/ C++ header file and write the name of the file as 2009145Lab3.c {Change the
registration number according to your registration number}

Remember that your compiler will behave according to the extension of the file so make sure to
name the file as .c file not any other name.

Click on the OK button and you will be given a white open space to write the program.

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Step 5:

Write the following program in the window.

#include <iostream.h>

int main()

Cout<<"My first program of C is so easy \n";

return 0;

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Step 6:

Now go to Build Menu and click “Compile” ,and after that again go to Build and click on
“Execute”. You will see “My first program of C is so easy” on a new black screen.

Debugging:

Debugging is the name given to the process of removing bugs (errors) from computer programs.

What a Debugger Can Do?

• Step through the program one statement at a time, either "over" or "into" functions.
• Run the program up to a certain point (either to the cursor or to a "breakpoint") and then
stop.
• Show the values (or contents) of variables at each point during the execution of the
program.
In this lab we will use step over only to execute your code line by line.
#include<iostream.h>

int main()

Cout<<"First statement executed using step\n";

Cout<<"Second statement executed using step\n";

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Cout<<"Third statement executed using step\n";

return 0;

First compile the above program and then Execute it, all the three statements will be printed on
the screen. Now again compile the file and execute one statement at a time by clicking on Debug
→Step Over (or F10). You will see that on the output screen (black screen) the statements will
appear one by one.

Lab: 06: Programming, Debugging, Microsoft Visual C++


Intro To CS IQRA University

Lab 07: Variables, Arithmetic Operators, Decision Control


Structures

Objectives of this lab:

• How to create a new project

• How to make a new source file in the project

• How to use comments in a program

• How create variables of different data types

• How to use arithmetic operators in a program

We are going to start from the previous lab to refresh your mind.

Step 1:

First of all click on Start Menu  All Programs  Microsoft Visual Studio 6.0  Visual C++ 6.0

This would launch the following window

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Step 2:

Go to File Menu and click the following window click New ..

This would launch the following window. Remember this step is very important you have to be
careful. Visual C++ 6.0 is a very powerful software so you need to be clear on what you want to
do. Click on the Windows Console Application and then click on the project name write
“20090145_Lab2”. Change the roll number according to your own rollnumber. Then click OK.

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Step 3:

After clicking the OK in the step 2. You will see the following window. Let the empty project
option selected and click on Finish. After that you will see another window click OK

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Step 4:

Now go to File Menu again and click “New…” you will see the following window. Select the
option C/ C++ header file and write the name of the file as 2009145Lab3.c {Change the
registration number according to your registration number}

Remember that your compiler will behave according to the extension of the file so make sure to
name the file as .c file not any other name.

Click on the OK button and you will be given a white open space to write the program.

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Step 5:

Write the following program in the window.


#include <isotream.h>

int main()

Cout<<"My first program of C is so easy \n";

return 0;

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Write following line of code and see the effect of comments.


#include <iostream.h>

int main()

//declaring integer and character vairables

int a; char ch;

/*Initializing the

variables

*/

a=10; ch=’b’;

cout<<“The value of ch is: \n”<<ch;

cout<<“The value of a is: \n”<<a;

return 0;

In this example you saw various ways of declaring variables of various data types and how to
write comments in C programs. Also, notice the use of “\n” at the end of the cout statements. It
simply adds a carriage return which ends the current line.

Write the following program in the editor and see the effect of the program and compare your
result with the following output.

#include <iostream.h>

int main()
{
int a = 72;
char b = 'A';
cout<<"a equals \n"<<a;
cout<<"a equals \n"<<a;
cout<<"b equals \n"<<b;
cout<<"b equals \n"<<b;
return 0;
}

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Output:

a equals 72
a equals H
b equals 65
b equals A
The reason why this works is because a character constant is just an integer from 0 to 255.

Introduction of “cin” statement in your program:


#include <iostream.h>

int main()

int a,b;

cout<<“Enter value of a: “;

cin>>a;

cout<<“Enter value of b: “;

cin>>b;

cout<<“The value of a is: \n”<<a;

cout“The value of b is: \n”<<b;

cout<<“Enter new value for both separated by a space: \n”<<;

cin>>a;

cout<<” “;

cin>>b;

cout<<”New values are:\n”;

cout<<a<<” “<<b;

return 0;

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Introduction of Arithmetic operators in your program:

After writing this program you will see that how one can add two numbers and following the
same way we can use subtraction, multiplication and division operators.
#include <iostream.h>

int main()

int a,b;

int sum;

cout<<“Enter value of a: \n“;

cin>>a;

cout<<“Enter value of b: \n“;

cin>>b;

sum=a+b;

cout<<“sum is: \t”;

cout<<sum<<”\n”;

return 0;

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Lab 08: Decision Control Statements


Objectives of this lab:

• Comparison/Relational Operators
• Logical Operators
• If Statement
• If - else statement
• Else - if Statement

Starting from a very simple form of if statement

Example: Write a program in which it takes a number from keyboard as an input and if the
number is greater than 100 it prints “The number is greater than hundred”.

Code:

#include <iostream.h>

int main()

int number ;

cout<<“Enter an integer\n”;

cin>>number;

if ( number >100 )

cout<<“The number is greater than 100\n”;

return 0;

Try below example and see the effect of if-else statement


#include <stdio.h>

int main()

int a,b ;

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

cout<<“Enter first number\n”;

cin>>a;

cout<<“Enter second number\n”;

cin>>b;

if ( a >=b )

// this condition can also be written as if(a>b || a==b)

Cout<<a<<”\t”<<b<<”\t”<<a-b;

else

cout<<b<<”t”<<a<<”\t”<<b-a;

return 0;

Now trying example of Nested if statement


#include<stdio.h>

int main()

int number ;

cout<<“Enter an integer\n”;

cin>>number;

if ( number <100 )

Cout<<“Yes the number is less than 100”<<endl;

if ( number <50)

Cout<<“ and number is also less than 50”<<endl;

else

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Cout<<“ but the number is not less than 50”<<endl;

else

cout<<“No the number is not less than 100”<<endl;

Try this example for if-else-if statement

Write a program which takes marks as input and shows the out put as follows:

Marks Output

Greater than or equal to 75 Passed: Grade A


Greater than or equal to 60 Passed: Grade B
Greater than or equal to 45 Passed: Grade C
Less than 45 Failed
#include <iostream.h>

int main()

int marks;

cout<<“Enter an marks\n”;

cin<<marks<<endl;

if (marks >= 75)

cout<<"Passed: Grade A\n";


else if (marks >= 60)
cout<<"Passed: Grade B\n";
else if (marks >= 45)
cout<<"Passed: Grade C\n"<<endl;
else
cout<<"Failed"<<endl;

return 0;
}

Try the below problem and show the result.


Write a program which takes marks as input and then shows output as follows:
Marks Output

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

87 – 100 Grade A
80 - 87 Grade B+
72 – 80 Grade B
67 – 72 Grade C+
60 - 67 Grade C
below 60 Failed

Take Home:

1. Write a program, which takes age as input from user and prints appropriate message
depending upon the following conditions:

•If age less then 6 then prints, “What a nice child!”


• If age is between 6 and 9 then prints, “That’s a good age!”
•If age is between 9 and less than 20 then prints, “Ah! In the prime of life”
•If age between 20 and less than 30 then prints, “Watch out, the younger ones
are gaining on you.”
•More than 30 then it prints, “Well, have fun, and don’t look back.”

2. Write a program which takes 3 numbers as input e.g. a = 30, b = 54 and c = 6 and print
output as follows:

Sample output:

Min number entered is 6

Max number entered is 54

(These are the values of variables which are taken from keyboard).

3. Write a C program that take a number N as input and display on the screen whether N is odd
or even. (Hint: if N is divided by 2 and its remainder is 0 then it is even, use % as remainder
operator)

Sample output:

Enter a number: 8

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

8 is even

OR

Enter a number: 9

9 is Odd

Lab: 07: Variables, Arithmetic Operators, Decision Control Structures


Intro To CS IQRA University

Lab 09: for loop, while loop


Objectives of this lab:

• To understand the basics of for loop

• Concept of while loop

Starting from a very simple and basic example:

Example 1: The following code will print hello ten times

#include <iostream.h>

int main()

int count;

for (count =1; count <=10; count=count+1)

cout<<"Hello\n";

return 0;

Try the example below and shows the output.

Example 2: Calculate simple table of 2 using a for loop

#include <iostream.h>

int main()

int count;

for (count =1; count <=10; count=count+1)

Count=2*count;

cout<<count<<endl;

Lab: 09: for loop, while loop


Intro To CS IQRA University

return 0;

Following examples shows some variations of the for loop

int main()

for(int i=0, j=10 ; i<10 ; i++, j-- )

Cout<<"\n”<<i<<j;

return 0;

Expression 1 could be written before the body of for loop.

Example 3:
int i = 0;

for( ; i < 10; i++)

cout<<“\n”<< i;

Expression 3 could be written in the body of the for loop.

Example 4:

int i = 0;

for( ; i < 10; ){

Lab: 09: for loop, while loop


Intro To CS IQRA University

cout<<“\n”<<i;

i++;

We can also omit expression 2 so this will be an infinite loop.

Example 6:
int i = 0;

for( ; ; ){

cout<<“\n”<< i;

i++;

This code will run indefinite times starting from 0.

We can use logical operators in expression 2.

Example 7:

#include<iostream.h>

int main(){

int i=0,j=10;

for(;i<10 && j >4;){

cout<<"\n"<<i<<j;

i++;

j--;

return 0;

Lab: 09: for loop, while loop


Intro To CS IQRA University

The while loop:


Try example below and shows the output:

Example 1: Print Numbers from 1 to 10 using a while loop

#include <iostream.h>

int main()

int counter = 1;

while (counter <= 10) // condition

cout<<“Counter now reads \n”<<counter;

counter++; // Same as counter=counter + 1 (increment)

return 0;

Our 2nd example is based on a while-loop that keeps on running until a certain condition is
reached (a certain value is entered by the user).

Example 2: Printing the numbers you entered using a while loop

#include <iostream.h>

int main()

Lab: 09: for loop, while loop


Intro To CS IQRA University

int flag; //flag is just an integer variable

cout<<“Enter any number: ( -1 to quit) \n”;

cin>>flag;

cout<<“Entering the while loop now...\n”;

while(flag != -1) {

cout<<“Enter any number: ( -1 to quit)\n ”;

cin>>flag;

cout<<“You entered \n”<<flag;

Cout<<“Out of loop now \n”;

return 0;

Take Home

1. Write a program to generate a list of first 100 odd numbers using while, do while and for
loops.

2. Write a function which takes as input a number, total multiplicands and user option to get even
or odd multiplicands and print table of that number.

Example:

Lab: 09: for loop, while loop


Intro To CS IQRA University

Input: Number=3, Total Multiples 15, Multiples types: Even

Output:

3 * 2 = 6

3 * 4 = 12

3 * 6 = 18

3 * 8 = 24

……………………….

……………………….

3 * 14 = 42

3. Write a program to find the sum of digits of the number entered by the user also print it in
reverse order.For example, user enters 1234, the sum should be 10 and the program should print
4321. (HINT: use modulus operator)

4. Write a program to ask the user his/her CGPA and print his/her grade accordingly. If grade is
C or better give good remarks otherwise leave an advice. (User is a FAST graduate)

5. Write a program which has the following output screen. (use loops to control output of the
program)

Lab: 09: for loop, while loop


Intro To CS IQRA University

6. Write a program to provide following functionality of a calculator using switch case


statement.
• Addition of two integers
• Subtraction of two integers
• Multiplication of two integers
• Division of two integers
• Addition of two Floating Point Numbers
• Subtraction of two Floating Point Numbers
• Multiplication of two Floating Point Numbers
• Division of two Floating Point Numbers
• Sine
• Cosine
• Tangent
• Square root
• Square
• Cube
User should be able to select his desired operation from the Menu given to him. The
program should only terminate when user selects exit operation from the MENU.

For sine, cosine, Tangent and Square root you can use functions available in math.h
library.

7. Write a program that takes as input any number of seconds (as int) and then converts
it in hours, minutes and seconds. For example, if you enter 7802 the program should
print:
2 hrs 10 mins 2 secs

(Hint: Use integer division and modulus operators)

8. The power series representation of sin(x) and cos(x) is

Lab: 09: for loop, while loop


Intro To CS IQRA University

This is an easy way to evaluate sin(x) or cos(x), by increasing the number of terms the accuracy
of the result is increased.
Requirements
You are required to implement a program which takes as input:

• The value of x (can be either in radians or degrees, if it is in degrees it should be converted


to radians first)

• The value to calculate sin(x) / cos(x) / or both

• The number of terms to evaluate

In the end the program should produce the following output:

• The value calculated by your program

• The “actual” value using the library functions sin and cos found in the header file <math.h>
(use the Deitel book as reference to see how this can be accomplished)

• The error in your value as compared to the actual value (calculated value – original value)

The formula for conversion from degrees to radians is given below:

X= (Angle in Degress) * π
180
Note that π (pi) is a constant value and should be taken as:
3.1415926535897932384626433832795

Lab: 09: for loop, while loop


Intro To CS IQRA University

Lab 10: Do-While, Continue, Switch, Break


Objectives of this Lab:

• To understand the usage of Do-While loop

• Concept of switch statement, continue and break statement

Starting from the very basic program

#include <stdio.h>

#include <conio.h>

int main( )

int x = 0; // Create a local variable 'x'

do

x=x+1; // Increment the variable 'x' by 1

} while (x < 3);

return 0;

Try some more programs like the one above and show the result.

Switch Statement:

Just look at the following example and examine the output:

#include <iostream.h>

int main() {

int a;

Lab: 10: Do-While, Continue, Switch, Break


Intro To CS IQRA University

cout<<"Pick a number from 1 to 4:\n";

cin>>a;

switch (a) {

case 1:

cout<<"You chose number 1\n";

case 2:

cout<<"You chose number 2\n";

case 3:

cout<<"You chose number 3\n";

case 4:

cout<<"You chose number 4\n”;

default:

cout<<"That's not 1,2,3 or 4!\n";

return 0;

The Break Statement:

Try the following example and think on the output

#include <iostream.h>

int main() {

int a;

cout<<"Pick a number from 1 to 4:\n";

cin>>a;

switch (a) {

Lab: 10: Do-While, Continue, Switch, Break


Intro To CS IQRA University

case 1:

cout<<"You chose number 1\n";

break;

case 2:

cout<<"You chose number 2\n";

break;

case 3:

cout<<"You chose number 3\n";

break;

case 4:

cout<<"You chose number 4\n";

break;

default:

cout<<"That's not 1,2,3 or 4!\n"; }

return 0; }

Continue Statement:

This does the opposite of break. Try the example below and compare it with the one above.

int index=0;
for(index=1;index<=10;index++)
{
if(index==4||index==5)
continue;
cout<<index;
}
cout<<"\nLoop terminated” ;

Lab: 10: Do-While, Continue, Switch, Break


Intro To CS IQRA University

Lab 11: Functions

Objectives of this lab:

• To understand the Concept of functions

Let’s do an example which calls a function which prints ten asterisks (*) in line. (**********)

#include<iostream.h>

void asteriks(); // prototype declaration

void main(){

asteriks(); // Function calling

void asteriks(){ // Function definition

int i=0;

for(;i<10;i++)

cout<<"*";

Lets go one step ahead, function asterisks (int a) with a single argument.

#include<iostream.h>

void asteriks(int n); // prototype declaration

void main(){

asteriks(7); // Function calling

void asteriks(int num){ // Function definition

int i=0;

Lab: 11: Functions


Intro To CS IQRA University

for(;i<num;i++)

cout<<"*";

Now an example of a function with two parameters

Here is an example of a function which calculates the sum of two numbers passed as arguments
to the function and returns the sum to the calling function.

int add(int no1,int no2 ){

int sum = no1+no2;

return sum;

Lets do another example of making a program using functions which will tell us whether the
input number is even or odd.

#include <iostream.h>

int is_even(int n); // (Prototype declaration)

void main()

int number, test;

cout<<"Enter a number to test even or odd";

cin>>number;

test = is_even(number); // (Function calling)

if(test==0)

cout<<"\nThe number is odd";

else

cout<<"\nThe number is even";

Lab: 11: Functions


Intro To CS IQRA University

int is_even(int n){ //Function definition

int remainder;

remainder= n%2;

if(remainder==1)

return 0;

else

return 1;

One more way to write the same example is

#include <iostream.h>

int is_even(int n){ //Function definition

int remainder;

remainder= n%2;

if(remainder==1)

return 0;

else

return 1;

void main()

int number, test;

cout<<"Enter a number to test even or odd\n";

Lab: 11: Functions


Intro To CS IQRA University

cin>>number;

test = is_even(number); //(Function calling)

if(test==0)

cout<<"\nThe number is odd";

else

cout<<"\nThe number is even";

Another way to write the same program

#include <iostream.h>

int is_even(int n); // (Prototype declaration)

void main()

int number;

cout<<"Enter a number to test even or odd\n";

cin>>number;

if(is_even(number)) //Function call within if condition

cout<<"\nThe number is even";

else

cout<<"\nThe number is odd";

int is_even(int n){ //Function definition

int remainder;

remainder= n%2;

Lab: 11: Functions


Intro To CS IQRA University

if(remainder==1)

return 0;

else

return 1;

Compile and run this program.

#include <iostream.h>

float avg(float no1, float no2, float no3); //(Prototype declaration)

void main()

float n1,n2,n3,result;

cout<<"Enter three number to find avg");

cin>>n1>>n2>>n3;

result=avg(n1,n2,n3); // (Function calling)

cout<<"\nThe average is \n”<<result;

float avg(float a, float b, float c){

cout<<"\nEntering the function\n";

float average= (a+b+c)/3;

return average;

Lab: 11: Functions


Intro To CS IQRA University

Lab 12: Functions (Call By Reference and By Value)


Objectives of this lab:

• Passing value to a function by reference

• Passing value to a function by value

Call by Value:

Example 1:

void func( int );

int main( ) {

int i = 8;

func( i );

cout<<“ the value of i is ”<< i;

return 0;

void func( int i) {

i = i + 10;

Example 2:

void interchange(int,int);

int

main()
{
int

x=50,

y=70;
interchange(x,y);
cout<<“ x= ”<<x<<” y= ”<<y;

Lab: 12: Functions (Call by Reference and by Value)


Intro To CS IQRA University

return 0;

void interchange(int,int)

{
int z1;
z1=x1;
x1=y1;
y1=z1;
cout<<“x1 is = “<<x1<<”y1 is “<<y1;
}

Call by Reference:

Example 3:

#include <iostream.h>

void interchange(int&,int&);

int main()

int x=50, y=70;

cout<<“ x= ”<<x<<” y= ”<<y;

interchange(x,y);

cout<<“ x= ”<<x<<” y= ”<<y;

return 0;

void interchange(int &x1,int &y1)

int z1;

Lab: 12: Functions (Call by Reference and by Value)


Intro To CS IQRA University

z1=x1;

x1=y1;

y1=z1;

//cout<<" *x= ”<< *x1<<” *y= "<<*y1;

Here the function is called by reference. In other words address is passed by using symbol “&”
and the value is accessed by using symbol “*”.

The main difference between them can be seen by analyzing the output of program1 and
program2.

Lab: 12: Functions (Call by Reference and by Value)


Intro To CS IQRA University

Lab 13: Arrays

Objectives of this lab:

Declaration of Array
Initialization of Array
Accessing elements of Array
Printing arrays
Copying arrays
Scanning array elements using cin
Dealing with characters using arrays

Let's start by looking at the following code where a single variable is used to store a person's age.

Code

#include <stdio.h>

int main()

int age;

age=23;

cout<<endl<< age;

return 0;

1) Declaration of Array

Here's is the code snippet to create an array and one way to initialize an array:

#include <iostream.h>

int main()

Lab: 13: Arrays


Intro To CS IQRA University

int age[4]; //declaration of Array

age[0]=23;//initialization of Array elements

age[1]=34;

age[2]=65;

age[3]=74;

return 0;

2) Initialization of Array

It is like a variable, an array can be initialized. To initialize an array, we provide initializing


values which are enclosed within curly braces in the declaration and placed following an
equals sign after the array name. Here is an example of initializing an integer array.

int age[4]={23,34,65,74};

3) Printing arrays
#include <iostream.h>

int main()

int age[4];

age[0]=23;

age[1]=34;

age[2]=65;

age[3]=74;

cout<< age<<endl;

return 0;

Lab: 13: Arrays


Intro To CS IQRA University

How about printing out each of the values separately? Try this:

#include <iostream.h>

int main()

int age[4];

age[0]=23;

age[1]=34;

age[2]=65;

age[3]=74;

cout<<age[0]<<endl;

cout<<age[1]<<endl;

cout<<age[2]<<endl;

cout<<age[3]<<endl;

return 0;

Lines (10) through line (13) produce the output we are expecting.

Thus there is no single statement in the language that says "print an entire array to the screen".
Each element in the array must be printed to the screen individually.

4) Copying arrays

Suppose that after filling our 4 element array with values, we need to copy that array to another
array of 4 int ? Try this:

#include <iostream.h>

int main()

int age[4];

int same_age[4];

Lab: 13: Arrays


Intro To CS IQRA University

int i=0;

age[0]=23;

age[1]=34;

age[2]=65;

age[3]=74;

for (;i<4;i++)

same_age[i]=age[i];

for (i=0;i<4;i++)

cout<<same_age[i]<<endl;

return 0;

5) Scanning array elements using cin


int a[5];

cin>>a[0]; // this will scan the value for the very first location of the array.

cout<<a[0]<<endl;

You can also scan the entire elements of the array using a loop.

6) Dealing with characters using arrays

You can also store characters and other type data (float etc.) in the arrays. Just declare it as
we’ve done in the case with int. There is no difference in dealing with characters except
you’ve to enclose the value in a single quote.

Char ar[3];

ar[0]=’a’ ; ar[1]=’b’ …..

Lab: 13: Arrays

Vous aimerez peut-être aussi