Lab Manual PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 103

Introduction to Computing and Programming Lab

Faculty

CS101L
(Manual)

Faculty of Computer Sciences and Engineering (FCS&E)


Ghulam Ishaq Khan Institute of Engineering Sciences and Technology
FCS&E, GIK Institute Topi, Pakistan Page 1 of 103
Topi, Swabi, Pakistan.
Introduction to Computing and Programming Lab

Table of Contents

Lab#1:GIKI Web Services, Number Systems and Flow Charts .................................................................. 12


Lab#2: Introduction to C/C++ Basics .......................................................................................................... 20
Lab#3: Variables, Inputs/Outputs and Arithmetic Operators .................................................................. 25
Lab#4: Decision Control Statements.......................................................................................................... 33
Lab#5: While Loop and Nested While Loop .............................................................................................. 41
Lab#6: For Loop .......................................................................................................................................... 48
Lab#7: Switch and Case Statements .......................................................................................................... 54
Lab#8: Functions Part 1 .............................................................................................................................. 61
Lab#9: Functions Part 2 .............................................................................................................................. 69
Lab#10: Arrays ............................................................................................................................................ 76
Lab#11: Pointers ......................................................................................................................................... 83
Lab#12: High Performance Computing ...................................................................................................... 92
Lab#13: Open Ended Lab.......................................................................................................................... 101
References ................................................................................................................................................ 102
Rubrics For Lab Evaluation ....................................................................................................................... 103
Grading Criteria ........................................................................................................................................ 103
CLO-PLO Mapping..................................................................................................................................... 103

FCS&E, GIK Institute Topi, Pakistan Page 2 of 103


Lab#1: GIKI Web Services and Number Systems

There are three parts of this lab: (i) to cover the basics of web services provided by the GIKI, (ii) to revise
the basics of number systems and (iii) to understand the basics of flow charts. The web services include
email service and the course website. Using GIKI email service you can send/receive emails, search for
contacts within GIKI, and set your calendar etc. The course website is the source of lecture notes, slides,
and handouts for the courses. In this way it acts as the interface between the students and instructors.
These basics will also help you in the course CS101.

Learning Objectives
 Computer settings for web access in GIKI
 To learn using GIKI email
 via the web interface (Internet Explorer or Fire fox)
 via an Email Client (Outlook Express)
 To learn about FCSE course website
 making an account
 accessing course and lab resources
 To learn number systems

Outcomes:
 Students should be able to make a GIKI email account
 Students should be able access and use course website
 Students should know the basic number systems

FCS&E, GIK Institute Topi, Pakistan Page 3 of 103


Part-I Web Services

Using Internet via Internet Explorer


Internet is available on all computers of the PC-LAB for almost 15 hrs per day (See PC-Lab working hours
at the entrance of the Lab). You can also use Internet at your room in the Hostel (if you find problem
with your room Network/Internet please contact Netronix or Hardware Workshop located in FCSE). To
use Internet please click on the Internet Explorer Icon on your desktop. The homepage will be displayed
(as shown in the following figure). If you see an error message as shown in the figure below, you need to
configure your internet explorer using the following steps.

Click on Tools and then on Internet Option. You will see a screen like this

Click Tools (upper right corner)


Click Internet Options
Click Connections tab (please follow figure on the next page)
Click LAN Settings
Check Use a proxy server...
Type 192.168.100.13 in the Address box (If this is not working then change it to 192.168.100.14)
Type 8080 in Port box
Check Bypass proxy...
Click OK
Now click refresh on the browser. If you still have a problem, then consult the lab staff.

FCS&E, GIK Institute Topi, Pakistan Page 4 of 103


Using GIKI email service
GIKI email is the primary source of communications on the campus. You can also use your email to
contact people outside the Institute. Your email addresses have already been created and are ready to
use. Your email identity (id) is your registration number preceded by an alphabet “u”, for example,
u2012XXX. Sample email address for 2012001 looks like [email protected].

To use this email you need a password that is available at the PC Lab desk with the laboratory assistants.
He will provide you your email password. You cannot collect the password for your friend. One must
have come to collect his/her own password from the Lab assistants.
In order to access your email you need to

log into windows


click on the Internet Explorer icon on your PC’s desktop
type mail.giki.edu.pk or 192.168.100.5 (address bar at the top)

You will see a screen as shown in the following figure.

FCS&E, GIK Institute Topi, Pakistan Page 5 of 103


Type unique username (for example “u2012001”, please use your own registration number instead
of 2012001) and password provided to you and click on login button. You will see a screen like this.

FCS&E, GIK Institute Topi, Pakistan Page 6 of 103


Your first task is to change your password. For this purpose follow the following steps.

Click the Preferences


Click Change Password

FCS&E, GIK Institute Topi, Pakistan Page 7 of 103


After changing the password please make sure to remember the new password. If you forget the
password, you need to contact the CPU Room in FCSE. Now your email address has been configured
and ready for use. You can explore the other options and learn them as an exercise.

FCSE Course Website


To facilitate the students enrolled in FCSE courses, a separate local website is maintained for students to
access the course material, participate in academic discussions, download relevant course lectures,
submit assignments and read up to date news and announcements about various courses. The FCSE
website can be accessed using internet explorer with the address http://192.168.1.21. In order to use
this facility, you have to make a separate account than that of email account. Once you login to course
website using your account details, you can access your registered courses.

To make an account on course website, please follow the steps:


Open Internet Explorer
Write 192.168.1.21 in address bar
Click login (Top left) (you will see the following screens)

FCS&E, GIK Institute Topi, Pakistan Page 8 of 103


Now click on new account (right side), you will see the following

Fill the form( use your own GIKI email address)


Click create my new account

FCS&E, GIK Institute Topi, Pakistan Page 9 of 103


Open the following page again, type your Username and Password
Click Login

You will see the following page

FCS&E, GIK Institute Topi, Pakistan Page 10 of 103


Downloading files form course website
Login to course website
Click your desired course (weekly schedule for that course will be displayed)
Click the current week (you will find some files)
Click on the file you need and save it to your computer

Uploading assignments to course website


Login to course website
Click your desired course (weekly schedule for that course will be displayed)
Click the current week
You will find a symbol like , click on it and you will be directed to a new page
Upload your file (assignment)
Click save

FCSE Software Server


GIKI has a collection of useful software on a specific computer (Software Server) that can be used by
students. You can access the software server at 192.168.100.4. To access the file server, follow these
steps
Click start button at the task bar
Click run
Enter the address (192.168.100.4) and press enter key
In resources folder you can get all the software. Please note that don’t install any software directly from
software server. First copy it to your local PC and then install it from your PC.

Search engine
Search engine is basically a website which stores information about different other websites, so search
engine will help you to access a website of yours own interest without knowing the address of that
specific website. Google is a powerful search engine. It searches for the web pages which contains the
information which you have provided in the search option. Sometime the information provided by the
search engine is irrelevant. Try to search with your search option enclosed in double quotes (“”) and
without it.

FCS&E, GIK Institute Topi, Pakistan Page 11 of 103


Part-II Number Systems

Digital computers are the machines, which respond to numbers only. All the data and instructions must,
therefore, be represented in a numeral format. There are different number systems e.g., decimal
number systems and binary number systems. The binary system has been found to be the most natural
and efficient system for modern digital computers. The following four number systems are commonly
used in modern computers.

The Decimal Number System: (Base 10 )


The Decimal Number System consists of 10 digits form 0 to 9 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).

The Binary Number System: (Base 2)


The Binary Number System consists of only two digits 0 and 1.

The Octal Number System: (Base 8)


The Octal Number System consists of 8 digits (0, 1, 2, 3, 4, 5, 6, 7).

The Hexadecimal Number System: (Base 16)


The Hexadecimal Number System consists of 16 digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).
The alphabets A, B, C, D, E and F are used to represent decimal numbers 10, 11, 12, 13, 14 and 15.

Number Systems Chart


Decimal Binary Octal Hexadecimal
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
16 10000 20 10

Number Conversion
We, in general, use decimal number system in our daily life. However, binary number system is suitable
for use in digital computers. Other number systems are used for programming/coding and data storage

FCS&E, GIK Institute Topi, Pakistan Page 12 of 103


purposes. Thus inter-conversion of numbers from one number system into other number system
becomes important for computation and data processing in digital computers.

Decimal to Binary Conversion


To convert a decimal integer into its binary equivalent, repeatedly divided the decimal number by 2,
noting down the remainder taken in reverse order to form the binary equivalent.
Example-1.1
Find the binary equivalent of decimal number 50.
Solution
2 50
2 25 0
2 12 1
2 6 0
2 3 0
1 1

Hence (50)10 = (110010)2

Binary to Decimal Conversion


To covert a binary number into its decimal equivalent, add the decimal equivalent of each occupied by
all the 1’s in the binary number.
Example-1.2
Covert binary number (10110)2 into decimal number
Solution
(10110) 2 = 1 * 24 + 0 * 23 + 1 * 22 + 1 * 21 + 0 * 20
= 1 * 16 + 0 * 8 + 1 * 4 + 1 * 2 + 0 * 1
= 16 + 0 + 4 + 2 + 0
= (22)10

Octal to Decimal Conversion


Example-1.3
Convert octal number (3057)8 into its equivalent decimal number
Solution
(3057)8 = 3 * 83 + 0 * 82 + 5 * 81 + 7 * 80
= 3 * 512 + 0 * 64 + 5 * 8 + 7 * 1
= 1536 + 0 + 40 + 7
= (1583)10

Decimal to Octal Conversion


Example-1.4
Convert decimal number (1583)10 into its Octal equivalent.
1583/8 = 197 with a remainder of 7
197/8 = 24 with a remainder of 5
24/8 = 3 with a remainder of 0
3/8 = 0 with a remainder of 3
Hence (1583)10 = (3057)8

Hexadecimal to Decimal Conversion

FCS&E, GIK Institute Topi, Pakistan Page 13 of 103


Example-1.5
Convert the Hexadecimal number (3F8A)16
(3F8A)16 = 3 * 163 + 15 * 162 + 8 * 161 + 10 * 160
= 3 * 4096 + 15 * 256 + 8 * 16 + 10 * 1
= 12288 + 3840 + 128 + 10
= (16266)10

Decimal to Hexadecimal Conversion


Example-1.6
Convert the decimal number (694)10 into its hexadecimal number.

694/16 = 43 with a remainder of 6


43/16 = 2 with a remainder of 11
2/16 = 0 with a remainder of 2

Hence (694)10 = (2B6)H

Binary to Octal Conversion


 Highest symbol is 7
 7 in Binary is 111
 Therefore, the largest Binary grouping in octal consists of 3 bits.
 Conversion is achieved by breaking Binary into groups of 3 bits, starting from the Right side, and
finding the Octal equivalent
Examples-1.7
a) (101110010100)B = (_________)o b) (1101110111101)2 = (______)8

101 | 110 | 010 | 100 001 | 101 | 110 | 111 | 101



5 6 2 4 1 5 6 7 5
Hence (101110010100)B = (5624)o and (1101110111101)2 = (15675)8
Note: In example b, we add two zeros to the left so that the grouping is 3 bits. This does not affect the
original number.

Octal to Binary Conversion


Here we reverse the process shown for Binary to Octal conversion.
Example-1.8
(45)O = (__________)B

4 =100
5 = 101 Hence (45)O= (100101)B

Binary to Hexadecimal
 Highest symbol is F (15)
 15 in Binary is 1111

FCS&E, GIK Institute Topi, Pakistan Page 14 of 103


 Therefore, the largest Binary grouping is Hexadecimal consists of 4 bits.
 Conversion is achieved by breaking Binary into groups of bits, starting from the Right side, and
finding the Hexadecimal equivalent.
Example-1.9
a) (101110111110)2 = (_____ )16 b) (10010100010)B=(_______)H

1011 | 1011 |1110 0100 | 1010 | 0010


 
(11) (11) (14) ( 4) (10) (2)
B B E 4 A 2
Hence (101110111110)2 = (BBE)16 and (10010100010)B = (4A2)H

Hexadecimal to Binary Conversion


Here we reverse the process shown for Binary to Hexadecimal conversion.
Example-1.10
(B1A)16 = (________)2

B = 1011
1 = 0001 Hence (B1A)16 (1011 0001 1010)2
A = 1010

FCS&E, GIK Institute Topi, Pakistan Page 15 of 103


Part-III Flow Charts

A flowchart (also spelled flow-chart and flow chart) is a schematic representation of a process. They are
commonly used in business/economic presentations to help the audience visualize the content better,
or to find flaws in the process. Examples include instructions for a bicycle's assembly, an attorney
outlining a case's timeline, diagram of an automobile plant's work flow, the decisions to be taken on a
tax form etc. Generally the start point, end points, inputs, outputs, possible paths and the decisions that
lead to these possible paths are included. Flow-charts can be created by hand or manually in most office
software, but lately specialized diagram drawing software has emerged that can also be used for the
purpose, such as Visio, OpenOffice.org Draw and Dia.

Guidelines for Drawing a Flowchart


Flowcharts are usually drawn using some standard symbols. However, some special symbols can also be
developed when required. Some standard symbols required for flowcharting many computer programs
are shown below:

FCS&E, GIK Institute Topi, Pakistan Page 16 of 103


Graphic Symbols
Within a flowchart, graphic symbols are used to specify arithmetic operations and relational conditions.
The following are commonly-used arithmetic and relational symbols:

+ plus, add
- minus, subtract
* multiply
/ divide
± plus or minus
= equal to
> greater than
< less than
≥ greater than or equal to
≤ less than or equal to
≠ not equal
YES or Y
NO or N
TRUE or T
FALSE or FF

Few Examples on Flowcharting


Now we shall present few examples on flowcharting for proper understanding of this technique.
Example 1.11
Draw a flowchart to find the sum of first 50 natural numbers.

FCS&E, GIK Institute Topi, Pakistan Page 17 of 103


Example 1.12
Draw a flowchart for computing factorial N (N!) Where N! = 1 x 2 x 3 x …… N

Algorithm
An algorithm is a finite set of well-defined instructions for accomplishing some task The concept of an
algorithm is often illustrated by the example of a recipe, although many algorithms are much more
complex; algorithms often have steps that repeat (iterate) or require decisions (such as logic or
comparison) until the task is completed. If an algorithm is flawed or not appropriate to the problem it
will not solve the problem even if we use it efficiently.. For example, performing the potato salad
algorithm will fail if there we try to use it to prepare apple salad even if all the motions of preparing the
salad are performed.

Example: 1.13
Problem: Write an algorithm to find the sum of two numbers
Solution:
1. Input first number
2. Store the number in a
3. Input the second number
4. Store the second number in b
5. Calculate the sum using a + b
6. Store the sum in c
7. Print the sum stored in c

FCS&E, GIK Institute Topi, Pakistan Page 18 of 103


Example: 1.14 (Non Computer)
1. Brush the teeth
2. Wash the face
3. Comb the hair
4. Smile in mirror
5. Go to CS101 Class

TASKS:
Tasks related to the lab will be provided by the lab instructor.

FCS&E, GIK Institute Topi, Pakistan Page 19 of 103


Lab#2: Introduction to C/C++ Basics

The aims of this lab are to introduce C/C++ language and to write the first basic computer program.

Learning Objectives:
 Introduction of C/C++ Programming Environment (Dev C++)
 Writing first program "Welcome to C++"
 Compiling and running basic program

Outcomes:
 Student should be able to gain basic C++ knowledge
 Student should be able to write simple C++ programs

FCS&E, GIK Institute Topi, Pakistan Page 20 of 103


C++ is case sensitive
C++ is case sensitive, that is, it recognizes a lower case letter and it's upper case equivalent as being
different. For example, Hello and hello are different. Most C++ programs are in lower case letters. You
will usually find upper case letters used in preprocessor definitions (which will be discussed later) or
inside quotes as parts of character strings.

C++ Programming Environment


To program in a language, we need a special software called an Integrated Development Environment
(IDE). An IDE consists of (i) an editor to edit source code, (ii) a compiler/linker to convert your code to
executable machine code and (iii) a debugger to find errors in a program. Additionally, it may have a
help system and other useful features.

C++ IDEs for Windows: Turbo C++, Dev Cpp , Net Beans, Eclipse & Microsoft Visual Studio
C++ IDE for Android: Cppdroid, C4droid, Quoda
C++ IDE for Iphone: XCode, Cppcode

DEV CPP IDE


How to start
1. Desktop  devcpp.exe
2. OR
3. My Computer  C
4. Dev-Cpp devcpp.exe

Steps for code writing and executing


1. After opening you will find the following screen

FCS&E, GIK Institute Topi, Pakistan Page 21 of 103


2. Open new file (Ctrl+N) as

3. Write your code in the text area as shown in the following screenshot

FCS&E, GIK Institute Topi, Pakistan Page 22 of 103


4. Compile your code (press “Ctrl + F9”)

5. If your compilation is successful, you will see the following screen

FCS&E, GIK Institute Topi, Pakistan Page 23 of 103


6. If you compile your code successfully, run the code (“Ctrl + F10”), otherwise remove the errors
and then compile the code again

7. After successfully running the code, you will notice the following output screen

FCS&E, GIK Institute Topi, Pakistan Page 24 of 103


Explanation of the code
Line 1: #include <iostream.h>
As part of compilation, the C++ compiler runs a program called the C++ preprocessor. The
preprocessor is able to add and remove code from your source file. In this case, the directive #include
tells the preprocessor to include code from the file iostream, which contains declarations for functions
that the program needs to use. iostream is a standard i/o library that contains declarations e.g.,
declaration for cout.
Line 2: void main()
This statement declares the main function. A C program can contain many functions but must always
have one main function. A function is a self-contained module of code that can accomplish some task.
Functions are examined in a later tutorial. The "void" specifies the return type of main. In this case,
nothing is returned to the operating system.
Line 3: {
This opening bracket denotes the start of the program.
Line 4: cout<<"Welcome to C++ ";
cout is a function from a standard C++ library that is used to print strings to the standard output,
normally your screen. The compiler links code from these standard libraries to the code you have
written to produce the final executable.
Line 5: }
This closing bracket denotes the end of the program.

Constant Escape Sequences


The following escape sequences can be used to print out special characters.
Escape Sequence Description
\' Single quote
\" Double quote
\\ Backslash
\0 Null character
\a Audible bell
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\xnnn Hexadecimal number (nnn)

Replace the line cout<<"Welcome to C++ "; in your program with cout<< "This\nis\na\ntest\n\nShe
said, \"How are you?\"\n";
Which would display:
This
is
a
test
She said, "How are you?"

TASKS: Tasks related to the lab will be provided by the lab instructor.

FCS&E, GIK Institute Topi, Pakistan Page 25 of 103


Lab#3: Variables, Inputs/Outputs and Arithmetic Operators

The aims of this lab are to cover some basics of C++ programming e.g., Variables, Types, Arithmetic
Operators and Decision Control Structures.

Learning Objectives:
 To learn and to use
 Variables
 Variable Types
 Declaring Variables
 Arithmetic Operators
 Comments
 input/output in C++
 cin
 cout

Outcomes:
 Students should be able to know C++ variables their types and arithmetic operators.
 Students should be able to use cin and cout methods in the programs.

FCS&E, GIK Institute Topi, Pakistan Page 26 of 103


Variables, Types and Operators
A variable is a place to store a piece of information. Just as you might store a friend's phone number in
your own memory, you can store this information in a computer's memory. Variables are your way of
accessing your computer's memory.
C++ imposes fairly strict rules on how you can name your variables:
 variable names must begin with a letter
 variable names are "case-sensitive" (i.e., the variable "myNumber" is different from the variable
"MYNUMBER" which is different from the variable "mYnUmBeR")
 variable names can't have spaces
 variable names can't have special characters (typographic symbols)
What can you name your variables? In general, variable names can be composed of letters, numbers,
and underscores (_).
Keywords: C++ reserves certain names which have special meaning to the language, and you are not
allowed to use any of these keywords as variables names. Some examples of C++ keywords are int, for,
else, and class. You can, however, use keywords in the middle of a variable name, such as "foreign" or
"classical".

Variable Types
A variable type is a description of the kind of information a variable will store. Following are some of the
Types that a variable can have:
Data Type Keyword Used Example Declarations
Integer (Whole Numbers) Int 21 int a; int b=21;
Floating Point (Decimal Numbers) Float 1.56 float a; float b=1.56;
Character (Characters) Char A char a; char a=’A’;

Declaring Variables
Declaring a variable in C++ is simple. Let's say you want to declare a variable of type int called myAge.
That is to say, the variable myAge will store an integer. In C/C++, this is written:
intmyAge;
All this does is tell the computer that you plan to use an integer, and that the integer's name is myAge.
In some languages, variables are initialized to 0 - that is, a variable's initial value will be 0. This is not true
of C++! Sometimes your variables will be initialized to 0, but sometimes they will be initialized with
garbage. As you might anticipate, this can cause some nasty bugs. Hence, it is always a good idea to
initialize your variables with some value. If you don't know what a variable's initial value should be,
initialize it to 0.

Example 3.1
Let’s write a program that stores your age in a variable and outputs “My age is 21". The first line of the
main function initializes myAge by assigning it a value immediately. compile and run the following code.

FCS&E, GIK Institute Topi, Pakistan Page 27 of 103


int main()
{
intmyAge = 21;
cout<<"My age is “
<<myAge<<“years”;
system(“pause”);
return 0;
}

C++ Comments
A comment is text that the compiler ignores but that is useful
for programmers. Comments are normally used to annotate
int main()
code for future reference. The compiler treats them as white
space. You can use comments in testing to make certain lines {
of code inactive. //declaring integer and character
A C++ comment is written in one of the following ways: vairables
 The /* (slash, asterisk) characters, followed by any int a; char ch;
sequence of characters (including new lines), followed /*Initializing the
by the */ characters. This syntax is the same as ANSI C. variables
 The // (two slashes) characters, followed by any
*/
sequence of characters. A new line not immediately
preceded by a backslash terminates this form of a=10; ch=’b’;
comment. Therefore, it is commonly called a single- /*Printing the
line comment. variables
The comment characters (/*, */, and //) have no special */
meaning within a character constant, string literal, or cout<<“The value of ch is ”
comment. <<ch<<endl;
cout<<“The value
Example 3.2
of a is ”<<a<<endl;
system(“pause”);
return 0;
}

Output
The value of ch is b
The value of a is 10
Notice the use of “endl” at the end of the cout statements. It simply adds a carriage return which ends
the current line.

FCS&E, GIK Institute Topi, Pakistan Page 28 of 103


Output and Input in
cout and cin

cout (Output Statement)


Gives you the power to print output onto the screen, and is relatively simple to use. The number of
arguments required varies, but the first argument you pass should be a STRING - think of a string as a
sequence of characters for now. Recall that a string must be surrounded by double quote marks.

Example 3.3

int main()
{
int a = 5;
intc = ’t’;
cout<< “Value of a is ” << a<<endl;
cout<< “and value of c is ” << c <<endl;
/*
You can also print the above in only one statement
*/
cout<< “Value of a is ” << a << “and value of c is ” << c <<endl;
system(“pause”);
return 0;
}

To print out the value of some variable, you need to embed a format specifier in your text string and
pass extra arguments to thecoutfunction. An example:
cout<< “My Age is ” <<MyAge<< “Years”;
This statement prints out the value of MyAge. Note that the value of MyAge is passed to the cout
function.
Output
Value of a is 5
and value of c is t
Value of a is 5 and value of c is t

FCS&E, GIK Institute Topi, Pakistan Page 29 of 103


cin (Input statement)
Allows you to input numbers and strings, as well as characters
Here is an example:
int a;
cout<< “Enter a number and press Enter”;
cin>> a;
Back to the example: cin takes only one argument i.e. variable name.

Inputting Multiple Values


If you have multiple format specifiers within the string argument of cin, you can input multiple values.
All you need to do is to separate each format specifier with a “>>”a string that separates variables.. As a
default, cin stops reading in a value when space, tab or Enter is pressed.
Consider
cin>>roll_number>>MyAge;
(Assume that roll_number and MyAge have been declared beforehand!). If I entered: 1 2 and pressed
Enter, 1 would get assigned to roll_number, and 2 would get assigned to MyAge. But if I entered 1, 2 and
pressed Enter, roll_number would equal 1, but MyAge won't get assigned 2 because cin was not
expecting a comma in the input string.
Now let us look at a way to get input from the user and store it in variables. Consider the following
program:

Example 3.4

int main()
{
inta,b;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
cout<< “The value of a is: ”<< a <<endl;
cout<<“The value of b is: ”<< b <<endl;
cout<< “Enter new value for both separated by a space: \n”;
cin>>a >> b;
cout<< “New values are: ”<< a << “ ”<< b <<endl;

system(“pause”);
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 30 of 103


Output
Enter value of a:
4
Enter value of b:
7
The value of a is: 4
The value of b is: 7
Enter new value for both separated by a space:
25
New values are: 2 5

Arithmetic Operators
Arithmetic operators are commonly used in a variety of programming languages. In C, there are five of
them, and they all take two OPERANDS. Recall that an operand is an expression that is required for an
operator to work. For example, for 8 + 4, 8 and 4 are considered as the operands.

Operator Name Symbol


Multiplication *
Division /
Modulus %
Addition +
Subtraction -

What's With the % ?


Multiplication, addition and subtraction are the simplest to use. Division is also easy, but watch out for
the truncation of an int divided by an int! Now, the one that confuses novices is the modulus operator,
sometimes known as the remainder operator.
To keep things simple, a%b returns the REMAINDER that occurs after performing a/b. For this operator,
a andb MUST be integers!
For example, 6%3 returns 0 because 3goes into 6 EXACTLY. Similarly, 4%4, 8%2 and 16%8 all return 0.
So why does 3%4 return 3? Picture it this way: you have 3 holes to fill, but you can only fill 4 holes at a
time. You can't fill a group of 4 holes, therefore the 3 holes you had are still empty. Similar story for 7%4
because you can fill in one group of 4 but still have 3 holes remaining.

FCS&E, GIK Institute Topi, Pakistan Page 31 of 103


Example 3.5

int main()
{
inta,b;
int sum;
cout<<“Enter value of a: \n“;
cin>>a;
cout<<“Enter value of b: \n“;
cin>>b;
sum=a+b;
cout<<“Sum: ”<<sum<<endl;
return 0;
}

Output
Enter value of a:
3
Enter value of b:
6
Sum: 9

TASKS:
Tasks related to the lab will be provided by the lab instructor.

FCS&E, GIK Institute Topi, Pakistan Page 32 of 103


Lab#4: Decision Control Statements

The aims of this lab are to cover Decision Control Structures of C++.

Learning Objectives:
 Comparison/Relational Operators
 Logical Operators
 If Statement
 If - else statement
 else - if Statement

Outcomes:
 Students should be able to use all types of C++ operators
 Students should be able to use if, if-else and else-if statements

FCS&E, GIK Institute Topi, Pakistan Page 33 of 103


Comparison/Relational Operators
Operator name Syntax

Less than or equal to a <= b

Less than or equal to a <= b


Greater than a>b
Greater than or equal to a >= b
Not equal to a != b
Equal to a == b

Logical Operators
Operator name Syntax

Logical negation (NOT) !a


Logical AND a && b
Logical OR a || b

Decision Control Structures


Till now we have used sequence control structure in the programs, in which the various steps are
executed sequentially i.e. in the same order in which they appear in the program.
In C programming the instructions are executed sequentially, by default. At times, we need a set of
instructions to be executed Depending upon different conditions to be satisfied.
In such cases we have to use decision control instructions. This can be achieved in C using;

1. The if statement
2. The if-else statement
3. The else - if statement

1. The C/C++ “if” Statement


The if statement controls conditional branching. The body of an if statement is executed if the value of
the expression/condition specified in the if statement is true. The syntax of the if statement is as
follows:
Syntax:
if(expression)
{
Block of statement;
}

FCS&E, GIK Institute Topi, Pakistan Page 34 of 103


Example: 4.1
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”.

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int number ;
cout<< “Enter an integer\n”;
cin>> number;
if ( number >100 )
cout<<“The number is greater than 100”;
getch();
return 0;
}

Note we did not use curly brackets ‘, -’for body of if if () because it did not include multiple statements
(block of statements). If it includes multiple statements then it would have been something like this.

if (number<100)
{
cout<< “The number is greater than 100\n”;
cout<< “No doubt that the number is greater than 100”;
}

2. The C/C++ if-else Statement


if - else statement is similar to if with the addition of else statement. If the condition is false in if then its
body will be skipped and the else statement’s body will be executed.
Syntax:
if(expression)
{
Block of statement;
}
else
{
Block of statement;
}

FCS&E, GIK Institute Topi, Pakistan Page 35 of 103


Example: 4.2
Write a program in which it takes two numbers from keyboard as input and subtract larger number from
smaller.

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
int a,b ;

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 <<"-" <<b <<"=" <<a-b;
else
cout <<b <<"-" <<a << "=" <<b-a;

getch();
return 0;
}

Nested if-else statement


Nested if is basically if inside if.
Example: 4.3
Write a program which take a number from keyboard and checks the number whether that number is
less than 100 or not if that number is less than 100 than check that is it less than 50 or not.

FCS&E, GIK Institute Topi, Pakistan Page 36 of 103


#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int number ;
cout << “Enter an integer\n”;
cin >>number;
if ( number <100 )
{
cout<< “Yes the number is less than 100”;
if ( number <50)
{
cout<< “ and number is also less than 50”;
}
else
{
cout<< “ but the number is not less than 50”;
}
}
else
cout<< “No the number is not less than 100”;
getch();
return 0;
}

The above program checks if the number is less than 100. This check is done in the first if statement.
If the result is true the program enters the second if statement which is also called the nested if
statement. Here another check is performed. The number is checked if it less than 50 or not. If the
number is less than 50 it is conveyed to the user. The rest is pretty self-explanatory.

3. The C/C++ else-if Statement

Sometimes we wish to make a multi-way decision based on several conditions. The most general way of
doing this is by using the else if variant on the if statement. This works by cascading several
comparisons. As soon as one of these gives a true result, the following statement or block is executed,
and no further comparisons are performed.

FCS&E, GIK Institute Topi, Pakistan Page 37 of 103


Syntax:

if(expression)
{
Block of statement;
}
else if(exprerssion)
{
Block of statement;
}
else if(exprerssion)
{
Block of statement;
}
. . // you can add as many else-if statements as
many you need
. .
. .

else
{
Block of statement;
}

Example: 4.4
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

FCS&E, GIK Institute Topi, Pakistan Page 38 of 103


#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int marks;

cout<< “Enter an marks\n”;


cin >> marks ;

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";
else
cout<< "Failed\n";

getch();
return 0;
}

In this example, all comparisons test a single variable called marks. In other cases, each test may involve
a different variable or some combination of tests. The same pattern can be used with more or fewer
else if's, and the final lone else may be left out. It is up to the programmer to devise the correct
structure for each programming problem.

Example: 4.5
Write a program which takes marks as input and then shows output as follows:
Marks Output
87 – 100 Grade A
80 - 87 Grade B+
72 – 80 Grade B
67 – 72 Grade C+
60 - 67 Grade C
below 60 Failed

FCS&E, GIK Institute Topi, Pakistan Page 39 of 103


#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int marks;

cout << “Enter an marks\n”;


cin >> marks;

if (marks >= 87 && marks <=100 )


cout << "Grade A\n";
else if (marks >= 80 && marks < 87)
cout << "Grade B+\n";
else if (marks >= 72 && marks< 80)
cout<< "Grade B\n";
else if (marks >= 67 && marks < 72)
cout << "Grade C+\n";
else if (marks >= 60 && marks< 67)
cout << "Grade C\n";
else
cout << "Failed\n";

getch();
return 0;
}

In above example logical operator && is used and because of this && operator condition will only be
satisfied if both the conditions in a single if are true. If any of the condition is false because of &&
operator the whole condition will be treated as false.

TASKS:
Tasks related to the lab will be provided by the lab instructor.

FCS&E, GIK Institute Topi, Pakistan Page 40 of 103


Lab#5: While Loop and Nested While Loop

The aims of this lab are to cover some other basics of C programming Loop Structure in detail.

Learning Objectives:
 While Loop
 Nested While Loop
 Do While loop

Outcomes:
 Students should be able to use while, nested while and do while loop loops.

FCS&E, GIK Institute Topi, Pakistan Page 41 of 103


Loop
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of
code is one of the most basic but useful tasks in programming -- many programs or websites that
produce extremely complex output are really only executing a single task many times. Now, think about
what this means: a loop lets you write a very simple statement to produce a significantly greater result
simply by repetition.

1. The while loop


The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an If
statement, if the test condition is true: the statements get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements get
executed again. This cycle repeats until the test condition evaluates to false.
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
condition. The while consists of a block of code and a condition. The condition is first evaluated and if
the condition is true the code within the block is then executed. This repeats until the condition
becomes false

Syntax
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}

The expression can be any combination of Boolean statements that are legal. Even, (while x ==5 || v ==
7) which says execute the code while x equals five or while v equals 7.

Flow Chart of While Loop

FCS&E, GIK Institute Topi, Pakistan Page 42 of 103


Example 5.1:
Write a program using while loop who print the values from 10 to 1

#include <iostream>
using namespace std;

int main()
{
int i = 10;

while ( i > 0 )
{
cout<<i;
cout<<”\n”;
i = i -1;
}
system(“pause”);
return 0;
}
}

This will produce following output:


10
9
8
7
6
5
4
3
2
1
Our next example is very simple. It uses a while loop to count from 1 to 10. It does so by incrementing a
variable named counter by 1 in each iteration or cycle. Incrementing a variable means to add something
to it, so that its value is increased.

FCS&E, GIK Institute Topi, Pakistan Page 43 of 103


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

#include <iostream>
using namespace std;
int main()
{
int counter = 1;
while (counter <= 10)
{
cout<<counter;
cout<<”\n”;
counter++;
}
system(“pause”);
return 0;
}

Our 3rd 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). That certain value is called the 'sentinel value', 'signal value' or
'flag value'.
Our program asks the user for an integer value, if that value is not -1, it keeps on running through the
next cycle/iteration.
Example 5.3: Printing the numbers you entered using a while loop

#include <iostream>
using namespace std;
int main()
{
int flag; //flag is just an integer variable
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“Entering the while loop now...\n”;
while (flag != -1) {
cout<<“Enter any number: ( -1 to quit) ”;
cin>>flag;
cout<<“You entered \n”<<flag;
}
cout<<“Out of loop now”;
system(“pause”);
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 44 of 103


2. Nested While
Example 6.4: Write a program who prints asterick sign (*) in such a way using nested while loops
**************
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*

#include <iostream>
using namespace std;
int main()
{
int i = 15, j; // variables for counter…
while(i>0) // outer loop, execute this first...
{
j=i-1; // the initial value of j is i - 1
while(j>0) // then, execute inner loop with loop index j,
{
cout<<"*"; // display *
j = j - 1; // decrement j by 1 until j>10, i.e j = 9
}
cout<<"\n"; // go to new line, new row
i = i - 1; // decrement i by 1, repeat until i > 0 that is i = 1
}
system(“pause”);
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 45 of 103


Example 5.5

// a program to show the nested while loops


#include <iostream>
using namespace std;
int main()
{
// variables for counter…
int i = 1, j;
// outer loop, execute this first...
// for every i iteration, execute the inner loop
while(i <= 9)
{
// display i
cout<<i;
// then, execute inner loop with loop index j,
// the initial value of j is i - 1
j = i-1;
while( j>0 )
{
cout<<"==”<< j; // display ==j
// decrement j by 1 until j>0, i.e j = 1
j = j - 1;
}
cout<<"\n"; // go to new line
// increment i by 1, repeat until i<=9, i.e i = 9
i = i + 1;
}
system(“pause”);
return 0;
}

Output

FCS&E, GIK Institute Topi, Pakistan Page 46 of 103


The do-while loop
Its format is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled. For example, the following example program echoes any
number you enter until you enter 0.

Example 5.6

#include <iostream>
using namespace std;

int main ()
{
long n;
do
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n"; } while (n != 0);
return 0;
}

Output:
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0

TASKS:
Tasks related to the lab will be provided by the lab instructor.

FCS&E, GIK Institute Topi, Pakistan Page 47 of 103


Lab#6: For Loop

The aims of this lab are to cover "For Loop" in detail.

Learning Objectives:
 Use of For Loop
 Use of Nested For Loop
 Comparison between For loop, While loop and Do While loop

Outcomes:
 Students should be able to use For loop, Nested For Loop and differentiate them.

FCS&E, GIK Institute Topi, Pakistan Page 48 of 103


For Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
 The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.
 After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
Flow Diagram:

FCS&E, GIK Institute Topi, Pakistan Page 49 of 103


output:
Example 6.1: value of a: 10
#include <iostream> value of a: 11
using namespace std; value of a: 12
value of a: 13
int main () value of a: 14
{ value of a: 15
// for loop execution value of a: 16
for( int a = 10; a < 20; a = a + 1 ) value of a: 17
{ value of a: 18
cout<< "value of a: " << a <<endl; value of a: 19
}

return 0;
system(“pause”);
}
Example 6.2: Output
#include<iostream>
using namespace std; Loop counter value is 5.
int main() Loop counter value is 10.
{ Loop counter value is 15.
int x; Loop counter value is 20.
for ( x=5; x <= 50; x = x+5 ) Loop counter value is 25.
{ // x = x + 5 could also be written x += 5 Loop counter value is 30.
cout<< "Loop counter value is " << x << ".\n"; Loop counter value is 35.
} Loop counter value is 40.
system ("pause"); Loop counter value is 45.
return 0; Loop counter value is 50.
}

Can you modify the above program that counts from 50 to 5 with decrements of 5?

Nested For Loop:


We have seen the advantages of using various methods of iteration, or looping.Now let's take a look at
what happens when we combine looping procedures.
The placing of one loop inside the body of another loop is called nesting. When you "nest" twoloops,
the outer loop takes control of the number of complete repetitions of the inner loop. While all types of
loops may be nested, the most commonly nested loops are for loops.

FCS&E, GIK Institute Topi, Pakistan Page 50 of 103


Example 6.3:
// Rectangle comprised of x's
for (rows = 0; rows < 4; rows++)
{
for (col = 0; col < 12; col++)
{
cout<<'x' ;
}
cout<< "\n";
}

Output of the program is displayed as follows:


xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx

Example 6.4:
// The following program checks if the number entered is a prime number or not
//Use of for loop and if-else statement
#include<iostream>
using namespace std;

int main()
{
longn,j;
cout<<"\n\n Enter the Number to test if it is a prime number ";
cin>>n;
for(j=2;j<=n/2;j++)
{
if(n%j==0)
{ cout<<"\n\n\t It is not a prime nuber as it is divisible by"<<j<<endl;
break;}
else
{ cout<<endl<< n << " is a Prime number "<<endl;
break; }
}
system("pause");
}

FCS&E, GIK Institute Topi, Pakistan Page 51 of 103


Example 6.5:
//missing init statement in For loop
#include<iostream>
using namespace std;
int main()
{
int i = 0;
for( ; i < 10; i++)
cout<<"\n"<< i;
system("pause");
return 0;
}

Note: for (;;) works as an infinite loop.

Which Loop should I use?


 while: the loop must repeat until a certain "condition" is met. If the "condition" is FALSE at the
beginning of the loop, the loop is never executed. The "condition" may be determined by the
user at the keyboard. The "condition" may be a numeric or an alphanumeric entry. This is a
good, solid looping process with applications to numerous situations.
 do-while: operates under the same concept as the while loop except that the do-while will
always execute the body of the loop at least one time. (Do-while is an exit-condition loop -- the
condition is checked at the end of the loop.) This looping process is a good choice when you are
asking a question, whose answer will determine if the loop is repeated.
 for: the loop is repeated a "specific" number of times, determined by the program or the user.
The loop "counts" the number of times the body will be executed. This loop is a good choice
when the number of repetitions is known, or can be supplied by the user.

FCS&E, GIK Institute Topi, Pakistan Page 52 of 103


The following program fragments print the numbers 1 - 20. Compare the different looping procedures.
Remember, there are always MANY possible ways to prepare code!

Common Error: If you wish the body of a for loop to be executed,


Example 6.6: DO NOT put a semicolon after the for's parentheses. Doing so will
do-while: cause the for statement to execute only the counting portion of
intctr = 1; the loop, creating the illusion of a timing loop. The body of the
do loop will never be executed.
{ Semicolons are required inside the parentheses of the for loop.
cout<<ctr++ <<"\n"; } The for loop is the only statement that requires such semicolon
while (ctr<= 20); placement.
for: ____________________________
intctr;
for(ctr=1;ctr<=20; ctr++)
{
cout<<ctr<<"\n";}
while:
intctr = 1;
while (ctr< = 20)
{
cout<<ctr++ <<"\n";
}

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 53 of 103


Lab#7: Switch and Case Statements

The aims of this lab are to cover "Switch" and "Case" in detail.

Learning Objectives:
 Introduction to Switch and Case Statement
 General Syntax of Switch and Case Statements
 Use of Break Statement
 Use of Continue Statement

Outcomes:
 Students should be able to use Switch statement, Case statement, Break statement and
Continue Statement.

FCS&E, GIK Institute Topi, Pakistan Page 54 of 103


Introduction:
Switch statement is C/C++ language is used for selection control. The difference between if/else and
switch selection statements is that the second one is used for making a selection from multiple
statements.
There are times when you'll find yourself writing a huge if block that consists of many else if statements.
The switch statement can help simplify things a little. It allows you to test the value returned by a single
expression and then execute the relevant bit of code.
You can have as many cases as you want, including a default case which is evaluated if all the cases fail.
Let's look at the general form...
switch (expression) {
case expression1:
/* one or more statements */
case expression2:
/* one or more statements */
/* ...more cases if necessary */
default:
/* do this if all other cases fail */
}
expression is any legal C++ expression, and the statements are any legal C++ statements or block of
statements. switch evaluates expression and compares the result to each of the case values. Note,
however, that the evaluation is only for equality; relational operators may not be used here, nor can
Boolean operations.
Flow Chart of Switch

Just look at the following example and examine the output:

FCS&E, GIK Institute Topi, Pakistan Page 55 of 103


Example 7.1:

#include <iostream>
using namespace std;

int main() {
int a;
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";
}
system(“pause”);
return 0;
}
(Suppose I entered 2...)
Pick a number from 1 to 4:
2
You chose number 2
You chose number 3
You chose number 4
That's not 1,2,3 or 4!
You'll notice that the program will select the correct case but will also run through all the cases below it
(including the default) until the switch block's closing bracket is reached.
To prevent this from happening, we'll need to insert another statement into our cases...

The break Statement


The break statement terminates the execution of the nearest enclosing do, for, switch, or while
statement in which it appears. Control passes to the statement that follows the terminated statement.

FCS&E, GIK Institute Topi, Pakistan Page 56 of 103


Example 7.2
#include <iostream>
using namespace std;

int main() {
int a;

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


cin>>a;

switch (a) {
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";
}
system(“pause”);
return 0;
}

On first inspection you'll find that it's virtually identical to the last example, except I've inserted a break
statement at the end of each case to "break" out of the switch block.
Now it should work as expected:
Pick a number from 1 to 4:
2
You chose number 2

FCS&E, GIK Institute Topi, Pakistan Page 57 of 103


Example 7.3
#include<iostream>
using namespace std;
int main()
{
char grade;
cout<<"Enter your grade: ";
cin>>grade;
switch(grade)
{
case'A':
cout <<"Your average must be between 90 - 100"
<<endl;
break;
case'B':
cout <<"Your average must be between 80 - 89"
<<endl;
break;
case'C':
cout<<"Your average must be between 70 - 79"
<< endl;
break;
case'D':
cout<<"Your average must be between 60 - 69"
<<endl;
break;
default:
cout<<"Your average must be below 60" << endl;
}
system("pause");
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 58 of 103


An example of break statement with loops:

Example 7.4:
#include <iostream>
using namespace std;
int main()
{
char c;
int store;
for(;;) {
cout<<"\nPress any key, Q to quit:";

cin>>c;
if(c == 'Q')
break;
else{
store = (int) c; // Convert character to corresponding ASCII value
cout<<store<<endl;
}
}
system("pause");
return 0;
} // Loop exits only when 'Q' is pressed

NOTE: It is almost always a good idea to have a default case in switch statements. If you have no other
need for the default, use it to test for the supposedly impossible case, and print out an error message;
this can be a tremendous aid in debugging.

Continue
This does the opposite of break; Instead of terminating the loop, it immediately loops again, skipping the
rest of the code. So let’s print the integers from 1 to 10, but this time we'll leave out printing 4 and 5.
You probably won't use continue very often but it's useful on the odd occasion.
Note: Before doing your lab exercises run the examples.

FCS&E, GIK Institute Topi, Pakistan Page 59 of 103


Example 7.5:
#include<iostream>
using namespace std;
int main()
{
int index=0;
for (index=1 ;index <= 10;index++ )
{
if (index== 4 || index==5)
continue;
cout<<index;
}
cout<<"\nLoop terminated”;
system(“pause”);
return 0;
}

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 60 of 103


Lab#8: Functions Part 1

The aim of this lab is to introduce basics of Functions which is the most important aspect of C/C++
languages. In the next lab some other topics related to Functions will be covered.

Learning Objectivese:
 Function Introduction
 To Use Function Syntax, Examples

Outcomes:
 Students should be able to use Functions.

FCS&E, GIK Institute Topi, Pakistan Page 61 of 103


Functions
Functions let you chop up a long program into named sections so that the sections can be reused
throughout the program. Function has a name identifier, accepts parameters and returns a result. C++
functions can accept an unlimited number of parameters. In general, C++ does not care in what order
you put your functions in the program, so long as the function name is known to the compiler before it
is called.
We have been consistently using library functions in the programs such as getch() and clrscr(). We just
simply use these functions without knowing what’s inside these functions. We just call them from our
program with some parameters inside the brackets and it does the work for us. We don’t know its
implementation. When we actually call these functions, the code inside these functions executes and at
the end it transfers the control back to the program from where the function was called.
In this lab we would learn how to make our own functions which can perform certain tasks. Function is
differentiated from a simple variable, by the parenthesis just after the name as main(). It just indicates
to the compiler that it’s a function.
The most common function that you have encountered is main() which you have been implementing
throughout the lab. main() is the function whose name identifier is main with no parameters passed to
it. Anything inside brackets are the parameters passed to the function. In case of multiple parameters,
each of them are separated with a comma(,) in between. Parameters are written as the comma
separated list within brackets just after the name of function. In main() function there are no
parameters passed to it as the brackets after the name is empty. As you know when we use int main() in
our program then we return an integer from the main function. Similarly when we define our own
functions in the program, that function should return appropriate value according to the data type
which is given before the name of function when we give its definition or implementation, just as we
return an integer when we use int main() and nothing in case of void main(). C++ assumes that every
function will return a value. If the programmer wants a return value, this is achieved using the return
statement. If no return value is required, none should be used when calling the function.
Function is written as
return_type function_name (comma separated list of parameters);
For example:
i. int main();
ii. float divide(int a, int b);
iii. void square(float x);
Here names of the functions are main, divide and square which take 0, 2 and 1 parameters respectively.
These functions would return an integer, float and void(nothing) respectively.
The prototype of a function is a way of describing the parameters (also called as arguments of function)
and parameter types with which a legal call to the function can be made. It contains the name of the
function, its parameters and their type, and the return value.
Pattern to write the function prototype is shown below.
return_type function_name (comma separated list of parameters);
Three examples shown above are examples of the function prototype. If you are asked to write the
prototype of any function it can be written as in the examples above.

FCS&E, GIK Institute Topi, Pakistan Page 62 of 103


If you need to do something again and again in the program after random time intervals (need to reuse
same code again and again) you should use function that should implement that task what is required.
And whenever that task is needed to be performed that function is just needed to be called and task
would be done. It would also decrease the size of the code and increases the reusability.
Lets do an example which calls a function which prints ten asterisks (*) in line. (**********)

In this example main function just calls the function named asterisks which just prints the line of ten
asterisks.

Example 8.1:

#include<iostream>
using namespace std;
void asteriks(); // prototype declaration
int main(){
asteriks(); // Function calling
system(“pause”);
return 0;
}
void asteriks(){ // Function definition
int i=0;
for(;i<10;i++)
cout<<"*";
}

Second line in the example is the prototype declaration of the function because before calling the
function it’s must that you should at least provide function prototype as given in example.
return_type function name(arguments separated by a comma);
Line 4 is the line which is calling the function.
asteriks() function in the previous example does not take any argument and does not return any thing
represented by empty braces() after function name and void before function name respectively.
After main the function definition of the function asterisks is given.
Lets go one step ahead, function asterisks (int a) with a single argument.

FCS&E, GIK Institute Topi, Pakistan Page 63 of 103


Example 8.2:

#include<iostream>
using namespace std;
void asteriks(int n); // prototype declaration
int main() {
asteriks(7); // Function calling
system(“pause”);
return 0; }
void asteriks(int num){ // Function definition
int i=0;
for(;i<num;i++)
cout<<"*"; }

This function would take an integer number as an argument and prints the no of asterisks equal to the
number given as argument to the function in straight line. As in example we have given 7 as an
argument while calling so it would print seven asterisks in line as 7 is passed to the function, int num
variable in function definition becomes equal to 7. As it is given in function prototype, compiler expects
function definition should take single argument which should be of integer data type. Due to this in
function calling you need to give an integer as argument (parameter) of a function.
Now an example of a function with two parameters.

Example 8.3:
#include<iostream>
using namespace std;
int add(int num1,int num2); // Function Prototype
int main(){
int s,a,b;
a=4;b=7;
s=add(a,b); // Function calling
cout<<s;
system("pause");
return 0;
}
int add(int num1,int num2 ){ // Function definition
int sum;
sum =num1+num2;
return sum;
}

FCS&E, GIK Institute Topi, Pakistan Page 64 of 103


The above function calculates the sum of two numbers passed as arguments to the function and returns
the sum to the calling function.
This function would be called from the main() function as
s = add(a , b);
where s, a, and b all would be integers declared in the main() function. When control in the main
function would reach to add(a,b) then, add function would be called and control would be transferred
to the code of add function and num1 and num2 of the add function would become equal to a and b
respectively.
The values of num1, and num2 are passed by the main function. The variable sum which is declared
inside the add function stores the sum of the numbers and return statement is used to return the result
calculated. You can declare any variable inside the function definition as it is done in main() as it is
shown in the example above.
int add(int num1,int num2 )

This line begins the function definition. It tells us the type of the return value, the name of the function,
and a list of arguments used by the function. The arguments and their types are enclosed in brackets,
each pair separated by commas.
The body of the function is bounded by a set of curly brackets. Any variables declared here will be
treated as local unless specifically declared as static or extern types.
return sum;
On reaching a return statement, the control of the program returns to the calling function. Value of sum
is returned from the add function to the main (calling function) at.
s = add(a , b);
it would become s = (value returned from the add function which is sum);
If the final closing curly bracket in the add function’s definition is reached before any return value, then
the function will return automatically, any return value will then be meaningless.
Example 8.4:
Lets do another example of making a program using functions which will tell us whether the input
number is even or odd.

#include<iostream>
using namespace std;
int is_even(int n); // (Prototype declaration)
int main()
{
int number, test;
cout<<"Enter a number to test even or odd"<<endl;
cin>>number;
test = is_even(number); // (Function calling)
if(test==0)
cout<<"The number is odd"<<endl;
else

FCS&E, GIK Institute Topi, Pakistan Page 65 of 103


cout<<"The number is even"<<endl;
system("pause");
return 0;
}

int is_even(int n){ //Function definition


int remainder;
remainder= n%2;
if(remainder==1)
return 0;
else
return 1;
}

Function is_even checks whether the number provided to it is even or odd and returns 0 or 1 for even or
odd number respectively.
Second line in the above program is the prototype declaration of the function is_even used in the
program. As mentioned earlier compiler needs to know at least the name of the function before calling
it. Method to give name of the function is to give the prototype of function as written in the program
above the main() function.
Note: You cannot define the function inside another function, can only call another function from inside
another function.
int is_even(int n); ------prototype
can also be witten as int is_even (int);
It means to say that variable name of the parameter is not necessary in prototype.

Whereas line
test=is_even(number); // (Function calling)
is calling the function is_even and passing the number to the function, n in the function definition
becomes equal to value of number. After the is_even function returns, the control would be transfered
back to the main() function and test in the main() function would become equal to the value returned by
the is_even function which is then further used in the main function.
One more way to write the same example is

FCS&E, GIK Institute Topi, Pakistan Page 66 of 103


Example 8.5:
#include<iostream>
using namespace std;
int is_even(int n){ //Function definition
int remainder;
remainder= n%2;
if(remainder==1)
return 0;
else
return 1;
}

int 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<<"The number is odd";
else
cout<<"The number is even";
system("pause");
return 0;
}

In this example what we have done is instead of giving prototype of the function before the main() just
give complete definition of the function. In this way there is no need of prototype definition. It would
work in the same way as previous one. Please try!!!!!!!
Compile and run this program.

Example 8.6:
#include<iostream>
using namespace std;
float avg(float num1, float num2, float num3); //(Prototype declaration)

int main()
{
float n1,n2,n3,result;
cout<<"Enter three number to find avg";

FCS&E, GIK Institute Topi, Pakistan Page 67 of 103


cin>>n1;
cin>>n2;
cin>>n3;
result=avg(n1,n2,n3); // (Function calling)
cout<<"The average is"<<result;
system("pause");
return 0;
}

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


cout<<"\nEntering the function";
float average=(a+b+c)/3;
return average;
}.

This program here takes three numbers from user in floating points, and send the numbers to the
function named avg( ).

float avg(float num1, float num2, float num3);


The prototype of the function tells us that it will take three float numbers and would return a floating
point number.
result=avg(n1,n2,n3);
This statement tells that the 3 numbers are passed to the function avg, and their return value would be
saved in the variable result.

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


cout<<"\nEntering the function";
float average= (a+b+c)/3;
return average;

In the definition part of the function the average calculated is saved in the variable average and is
returned by the returned function.

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 68 of 103


Lab#9: Functions Part 2

The aim of this lab is cover functions in detail.

Learning Objectives:
 To learn Function Call by Value
 To Learn Function Call by Reference
 To use Default values in parameters
 Random Number generation

Outcomes:
 Students should be able to Call Functions by value and by reference.
 Students should be able to generate random numbers.

FCS&E, GIK Institute Topi, Pakistan Page 69 of 103


Calling Functions:
Call by Value:
Call by value is used when whenever the called function does not need to modify the
value of the caller’s original variable. In this case a copy of the variable is passed to the function and
when the function changes its values then it has no effect on the value of the variable in the main
function.
Example 9.1:
#include<iostream>
using namespace std;
void func( int );
int main( ) {
int i = 8;
func( i );
cout<<"the value of i is"<< i<<endl;
system("pause");
return 0;
}
void func( int i) {
i = i + 10;
}

Example 9.2:
#include<iostream>
using namespace std;
void interchange(int,int);
int main()
{
int x=50, y=70;
interchange(x,y);
cout<<"x="<<x<<" and "<<"y="<<y<<endl;
system("pause");
return 0;
}
void interchange(int x1,int y1)
{
int z1; z1=x1; x1=y1; y1=z1;
cout<<"x1="<<x1<<" and "<<"y1="<<y1<<endl;;
}

FCS&E, GIK Institute Topi, Pakistan Page 70 of 103


Output:
x1=70 y1=50
x=50 y=70

Call by Reference:
If you are calling by reference it means that compiler will not create a local copy of the variable
which you are referencing to. It will get access to the memory where the variable saved. When you are
doing any operations with a referenced variable you can change the value of the variable.

Example 9.3:
#include<iostream>
using namespace std;
void interchange(int&, int&);
int main()
{
int x=50, y=70;
cout<<"before calling the function the values are"<<"x="<<x<<" and
y="<<y<<endl;
interchange(x,y);
cout<<"after calling the function the values are"<<"x="<<x<<" and
y="<<y<<endl;
system("pause");
return 0;
}
void interchange(int &x1,int &y1)
{
int z1; z1=x1; x1=y1; y1=z1;
}

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.
The output of Example 2 that is call by value is
x1=70 y1=50
x=50 y=70

But the output of Example 3 that is call by reference is

FCS&E, GIK Institute Topi, Pakistan Page 71 of 103


*x=70 *y=50
x=70 y=50
This is because in case of call by value the value is passed to function named as interchange and
there the value got interchanged and got printed as

x1=70 y1=50

and again since no values are returned back and therefore original values of x and y as in main
function namely

x=50 y=70 got printed.


___________________________________________________________
Passing by reference is also an effective way to allow a function to return more than one value.
For example, here is a function that returns the previous and next numbers of the first parameter
passed.
Example 9.4:
// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int& next)


{
prev = x-1;
next = x+1;
}

int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}

Output:
Previous=99, Next=101

Default values in parameters.


When declaring a function we can specify a default value for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function. To do
that, we simply have to use the assignment operator and a value for the arguments in the function
declaration. If a value for that parameter is not passed when the function is called, the default
value is used, but if a value is specified this default value is ignored and the passed value is used
instead. For example:

FCS&E, GIK Institute Topi, Pakistan Page 72 of 103


Example 9.5:
// default values in functions
#include <iostream>
using namespace std;

int divide (int a, int b=2)


{
int r;
r=a/b;
return (r);
}

int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}

Output:
6
5

Random Number Generation:


rand( ) function is used for generating random numbers. This function is defined in standard liberary of
C. The output of the rand( ) function could be in the range of 0 to 32767 which is the upper limit for an
integer.

Example 9.6:
#include<iostream>
using namespace std;
int main()
{
int number;
for(int i=1; i<=10; i++)
{
number=rand();
cout<<number<<endl;
}
system("pause");
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 73 of 103


To get the desired output from rand( ) function we need to do some mathematical calculation like to get
random numbers between 0 and 9 we will use:
Numbers = rand ( ) % 10;

Example 9.7:
#include<iostream>
using namespace std;
int main()
{
int number;
for(int i=1; i<=10; i++)
{
number=rand()%100;
cout<<number<<endl;
}
system("pause");
return 0;
}

srand( ) is another function to change the pattern of random numbers generation. So one can use
srand(time(NULL) ) to find different random number each time when program is executed. Remember
to #include <time.h> to enable your program to use the time function. The time(NULL) returns the
number of seconds of the current time since epoch.

Example 9.8:
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
srand(time(NULL));
int number;
for(int i=1; i<=10; i++)
{
number=rand();
cout<<number<<endl;
}
system("pause");
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 74 of 103


Example 9.9:
#include<iostream>
#include<time.h>
using namespace std;

int main()
{
srand(time(NULL));
int number;
for(int i=1; i<=10; i++)
{
number=rand()%100;
cout<<number<<endl;
}
system("pause");
return 0;
}

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 75 of 103


Lab#10: Arrays

In this lab Arrays are covered in detail

Learning Objectives:
 Array definition
 When to use Array
 Array declaration
 Array Initialization
 Accessing Array elements
 Copying Arrays

Outcomes:
 Students should be able to understand and use arrays.

FCS&E, GIK Institute Topi, Pakistan Page 76 of 103


What is Array?
Array is a data structure in C++, which stores a fixed size sequential collection of elements of the same
type. An array is used to store a collection of data. It is often useful to think of an array as a collection of
variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

When to use Array


Let's start by looking at listing 1 where a single variable is used to store a person's age.

Example 10.1:
#include <iostream>
using namespace std;
int main()
{
int age;
age=23;
cout<< age;
return 0;
}

It is quite simple. The variable age is created at line (5) as int. A value is assigned to it. Finally, age is
printed to the screen.
age. 23

2390(its address in memory)


Now let's keep track of 4 ages instead of just one. We could create 4 separate variables, but creating 4
separate variables is not a good approach. (If you are using 4 separate variables for it, then consider
keeping track of 1000 ages instead of just 4). Rather than using 4 separate variables, we'll use an array
because it is quite easy to handle one variable instead of 1000.

Declaration of Array
To declare an array in C++, the programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];

FCS&E, GIK Institute Topi, Pakistan Page 77 of 103


This is called a single-dimension array. The arraySize must be an integer constant greater than zero and
type can be any valid C++ data type. For example, to declare a 4-element array called age of type int, use
this statement:
int age[4];

Example 10.2:
#include <iostream>
using namespace std;
int main()
{
int age[4]; //declaration of Array
age[0]=23; //initialization of Array elements
age[1]=34;
age[2]=65;
age[3]=74;
return 0;
}

On line (5), an array of 4 int is created. Values are assigned to each variable in the array on line (6)
through line (9). In memory these are contiguous set of locations shown in following figure.
Age[0] age[1] age[2] age[3]

23 34 65 74

FCS&E, GIK Institute Topi, Pakistan Page 78 of 103


Example 10.3:
#include <iostream>
using namespace std;
int main()
{
int age[4]; //array ‘age’ of 4 ints
for(int j=0; j<4; j++) //get 4 ages
{
cout << “Enter an age: “;
cin >> age[j]; //access array element
}
for(j=0; j<4; j++) //display 4 ages
cout << “You entered “ << age*j+ << endl;
return 0;
}

Here’s a sample interaction with the program in example 3.1:


Enter an age: 44
Enter an age: 16
Enter an age: 23
Enter an age: 68
You entered 44
You entered 16
You entered 23
You entered 68
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};
Age[0] age[1] age[2] age[3]
Now how to initialize all the values in array to 0? It can be done by the following statement;

23 34 65 74

Int age[4]={0};
age[0] age[1] age[2] age[3]

0 0 0 0

FCS&E, GIK Institute Topi, Pakistan Page 79 of 103


Accessing elements of Array
In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value.
array_name[index];
Following the previous examples in which “age” had 4 elements and each of those elements was of type
int, the name which we can use to refer to each element is the following:
age[0] age[1] age[2] age[3]

For example, to store the value 75 in the third element of age , we could write the following statement:
age[2]=75; //note : array index start with 0 in c.
And, for example, to store the value of the third element of age to a variable called a, we could write:
int a=age[2];
Here’s another example of an array at work. This one, SALES, invites the user to enter a series of six
values representing widget sales for each day of the week (excluding Sunday), and then calculates the
average of these values. We use an array of type double so that monetary values can be entered.

Example 10.4:
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 variables
cout << “Enter widget sales for 6 days\n”;
for(int j=0; j<SIZE; j++) //put figures in array
cin >> sales[j];
double total = 0;
for(j=0; j<SIZE; j++) //read figures from array
total += sales[j]; //to find total
double average = total / SIZE; // find average
cout << “Average = “ << average << endl;
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 80 of 103


Here’s some sample interaction with SALES:
Enter widget sales for 6 days
352.64
867.70
781.32
867.35
746.21
189.45
Average = 634.11

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
Example 10.5: this:
#include <iostream>
using namespace std;
int main()
{
int age[4];
int same_age[4];
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];
return 0;
}

In the above program two arrays are created: age and same_age. Each element of the age array is
assigned a value. Then, in order to copy the four elements in age into the same_age array, we must do it

FCS&E, GIK Institute Topi, Pakistan Page 81 of 103


element by element. We have used for loop to access every element of array note that for loop takes
value from 0 to 3.
Note: Like printing arrays, there is no single statement in the language that says "copy an entire array
into another array". The array elements must be copied individually. Thus If we want to perform any
action on an array, we must repeatedly perform that action on each element in the array.
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’ …..
-----------------------------------------------------------------------------------------------------------------------------------

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 82 of 103


Lab#11: Pointers

In this lab we will be discussing pointers in detail. This is one of the most important concepts in C++
language. Pointers are used everywhere in C++, so if you want to use the C++ language fully you have to
have a very good understanding of pointers. They have to become comfortable for you. To fully grasp
the concept of pointers all you need is the concept and practice of pointers.

Learning Objectives:
 To understand Computer Memory and variable concept
 Pointer Introduction
 Pointer declaration
 Reference and Dereference Operators
 Pointer example and its explanation
 Pointer Arithmetic’s
 Sending Pointers as Arguments to Functions

Outcomes:
 Students should be able to understand and use pointers and can perform basic pointer’s
Arithmetic.

FCS&E, GIK Institute Topi, Pakistan Page 83 of 103


Computer Memory
Essentially, the computer's memory is made up of bytes. Each byte has a number, an address, associated
with it. The picture below represents several bytes of a computer's memory. In the picture, addresses
924 thru 940 are shown.

Variable and Computer Memory


A variable in a program is something with a name, the value of which can vary. The way the
compiler handles this is that it assigns a specific block of memory within the computer to hold the value
of that variable. The size of that block depends on the range over which the variable is allowed to vary.
For example, on 32 bit PC's the size of an integer variable is 4 bytes. On older 16 bit PCs integers were 2
bytes.

Example 11.1
#include<iostream>
using namespace std;
int main()
{
float fl=3.14;
cout<<fl;
cin>>fl;
return 0;
}

The output for this program will be

At line (4) in the program above, the computer reserves memory for fl. Depending on the computer's
architecture, a float may require 2, 4, 8 or some other number of bytes. In our example, we'll assume
that a float requires 4 bytes.

FCS&E, GIK Institute Topi, Pakistan Page 84 of 103


When fl is used in line (5), two distinct steps occur:
1. The program finds and grabs the address reserved for fl--in this example 924.
2. The contents stored at that address are retrieved
The illustration that shows 3.14 in the computer's memory can be misleading. Looking at the diagram, it
appears that "3" is stored in memory location 924, "." is stored in memory location 925, "1" in 926, and
"4" in 927. Keep in mind that the computer actually converts the floating point number 3.14 into a set of
ones and zeros. Each byte holds 8 ones or zeros. So, our 4 byte float is stored as 32 ones and zeros (8 per
byte times 4 bytes). Regardless of whether the number is 3.14, or -273.15, the number is always stored
in 4 bytes as a series of 32 ones and zeros.

Pointer:
In C++ a pointer is a variable that points to or references a memory location in which data is stored. A
pointer is a variable that points to another variable. This means that a pointer holds the memory
address of another variable. Put another way, the pointer does not hold a value in the traditional sense;
instead, it holds the address of another variable. A pointer "points to" that other variable by holding a
copy of its address. Because a pointer holds an address rather than a value, it has two parts. The pointer
itself holds the address and that address points to a value.

Pointer declaration:
A pointer is a variable that contains the memory location of another variable. The syntax is as shown
below. You start by specifying the type of data stored in the location identified by the pointer. The
asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the
variable.
Data_type *variable_name
Such a variable is called a pointer variable (for reasons which hopefully will become clearer a little later).
In C++ when we define a pointer variable we do so by preceding its name with an asterisk. In C++ we
also give our pointer a type which, in this case, refers to the type of data stored at the address we will be
storing in our pointer. For example, consider the variable declaration:
int *ptr;
int k;
ptr is the name of our variable (just as k is the name of our integer variable). The '*' informs the
compiler that we want a pointer variable, i.e. to set aside however many bytes is required to store an
address in memory. The int says that we intend to use our pointer variable to store the address of an
integer.

Referencing Operator
Suppose now that we want to store in ptr the address of our integer variable k. To do this we use the
unary & operator and write:
ptr = &k;
What the & operator does is retrieve the address of k, and copies that to the contents of our pointer ptr.
Now, ptr is said to "point to" k.

Dereferencing operator
The "dereferencing operator" is the asterisk and it is used as follows:
*ptr = 7;

FCS&E, GIK Institute Topi, Pakistan Page 85 of 103


will copy 7 to the address pointed to by ptr. Thus if ptr "points to" (contains the address of) k, the above
statement will set the value of k to 7. That is, when we use the '*' this way we are referring to the value
of that which ptr is pointing to, not the value of the pointer itself.
Similarly, we could write:
cout<<*ptr<<endl;
to print to the screen the integer value stored at the address pointed to by ptr;.
Here is graphical representation of
Pointers.

This Listing will be very helpful in understanding the pointers. Understand it thoroughly how it works
and then proceed.

Example 11.2
#include<iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout<<"First Value is " << firstvalue<<endl;
cout<<"Second Value is " <<secondvalue<<endl;
return 0;
}

FCS&E, GIK Institute Topi, Pakistan Page 86 of 103


Output of this listing is as follows:

How it Works:
Here in this code we are trying to play with memory and address of our variables for the better
understanding of Pointers. On line number 5 we have two integer variables (i.e firstvalue and
secondvalue). Both are assigned values of 5 and 15 respectively. On line number 6 we have two integer
pointer variables (i.e p1 and p2). Both are assigned addresses of variables in line 5 firstvalue and
secondvalue respectively in line 7 and 8.
In line 9 we see that *p1 is assigned value 10. This means that 10 should be copied in the variable, which
is lying on an address to which p1 is pointing. We know that p1 is pointing to address of firstvalue. So
line 9 results in assigning firstvalue the value of 10.
In line 10 we encounter another assignment which says that value of variable pointed by p2 should be
replaced with the value of variable pointed by p1. So now secondvalue is assigned with value 10 as well.
Well the assignment in line 11 is a bit confusing but very simple, all this assignment is doing is that now
p1 is pointing to the same address as p2. So now we can say p1 and p2 are pointing at same address.
In line 12 we see that *p1 is assigned value 20. This means that 10 should be copied in the variable,
which is lying on an address to which p1 is pointing. We know that p1 is now pointing to address of
secondvalue because in last line we pointed p1 to the address being pointed by p2. So line 12 results in
assigning secondvalue the value of 20.
Now when we print the value of first value and second value it prints 10 for firstvalue and 20 for
secondvalue; which is right due to the reasons explained above.

Pointers: Pointing to the Same Address


Here is a cool aspect of C++: Any number of pointers can point to the same address. For
example, you could declare p, q, and r as integer pointers and set all of them to point to i, as shown
here:
int i; int *p, *q, *r;
p = &i; q = &i; r = p;
Note that in this code, r points to the same thing that p points to, which is i. You can assign pointers to
one another, and the address is copied from the right-hand side to the left-hand side during the
assignment. After executing the above code, this is how things would look:

The variable i now has four names: i, *p, *q and *r. There is no limit on the number of pointers that can
hold (and therefore point to) the same address.

FCS&E, GIK Institute Topi, Pakistan Page 87 of 103


Pointer Arithmetic’s
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly
declared and initialized pointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;

C++ allows us to add integers to or subtract integers from pointers as well as to subtract one pointer
from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and
p1!=p2 are allowed.

When an integer is added to, or subtracted from, a pointer, the pointer is not simply incremented or
decremented by that integer, but by that integer times the size of the object to which the pointer refers.
The number of bytes depends on the object's data type.

/*Program to illustrate the pointer expression and pointer arithmetic*/

1:#include<iostream>
2:using namespace std;
3: int main()
4: {
5:int *ptr1,*ptr2;
6:int a,b,x,y,z;

7:a=30;b=6;

8:ptr1=&a;
9:ptr2=&b;

10:x=*ptr1 + *ptr2 - 6;
11:y=6 - *ptr1 / *ptr2 +30;

12: cout<<"Address of a: "<<ptr1<<endl;


13: cout<<"Address-Value in ptr1: "<<*ptr1<<endl<<endl;
//The comment value is the value of ptr1 (address of the a)

14: cout<<"Address of b: "<<ptr2<<endl;


15: cout<<"Address-Value in ptr1: "<<*ptr2<<endl<<endl;
//The comment value is the value of ptr2 (address of the b)

16: cout<<"a: " <<a<<" b: "<<b<<endl<<endl;


//Simply prints the value of a and b

FCS&E, GIK Institute Topi, Pakistan Page 88 of 103


17: cout<<"x: " <<x<<" y: "<<y<<endl<<endl;
//Simply prints the value of x and y.

18: ptr1=ptr1 + 1; // adds 280 in address of ptr1. (1*4 = 4)


19: ptr2= ptr2;

20: cout<<"a: " <<a<<" b: "<<b<<endl;


//Simply prints the value of a and b

21: cout<<"Value in ptr1: "<<ptr1<<endl<<endl; // 2293564


//The comment value is the new memory location value of ptr1

22: cout<<"\nAddress-Value in ptr1: "<<*ptr1<<endl<<endl; // garbage value


//The comment value is the new value of ptr1 (garbage value)
23: cout<<"Address of b: "<<ptr2<<endl<<endl;
24: cout<<"\nAddress-Value in ptr1: "<<*ptr2<<endl<<endl;
cin>>a;
}
Here note that adding some thing in *ptr1 changes the value of the address stored
in ptr. However adding some thing in ptr will change the address it is pointing to.
Printing ptr1 after adding 1 in it gives different address as it has changed by 4
Bytes.

How it Works:
This code explains all the rules related to arithematic of pointers. From line 1 to line 11, it is
simply adding, subtracting and like manipulating with the pointers and variables. After all the
manipulations and arithmetics it started printing values of pointers and other simple variables till
line 12.

FCS&E, GIK Institute Topi, Pakistan Page 89 of 103


a b
30
6
7864 7868 7872 7876 7880 7884 7888

ptr1 ptr2

At line 18 it adds 1 to ptr1. Mostly people think that this will change the address of the pointer,
but they are totally wrong. Remember pointer is pointing to an address. This addition does not
change the address of the pointer, infact it changes the value of the pointer (not the value of the
address pointer is pointing at.). ptr1 has the address of variable of variable a . So it adds 1 *4
Btytes = 4bytes in the address of a which is stored in ptr1. Where as ptr2 points at the same value
as before due to the assignment of line 19.
a b
30 0XF…
6
7864 7868 7872 7876 7880 7884 7888

ptr1 ptr2

Line 20 prints the same value as was printed by the Line 16, because values of the variable was
never changed, in fact ptr1’s value which was address of a was changed. Now Line 21 will print
the value stored in ptr1; which is address of memory 4 bytes ahead of variable a. Line 22 is
trying to print the value at address, ptr1 is now pointing to, which was never assigned any value.

Sending Pointers as Arguments to Functions


When we pass pointers to some function, the addresses of actual arguments in the calling function are
copied into the arguments of the called function. This means that using these addresses we would have
an access to the actual arguments and hence we would be able to manipulate them. The following
program illustrates this fact.
Try this out: C++ Code Listing
#include<iostream>
void swap(int *,int *);
using namespace std;

int main( )
{
int a = 10, b = 20 ;

swap( &a, &b) ;


cout<<"a: "<<a<<"b: "<<b<<endl;
cin>>a;

FCS&E, GIK Institute Topi, Pakistan Page 90 of 103


}
void swap( int *x, int *y )
{
int t = *x ;
*x = *y;
*y = t;
}
The output of the above program would be:

a = 20 b = 10
Note that this program manages to exchange the values of a and b using their addresses stored in x and
y.

Try on paper how this code works. Working of this code might be asked in Viva.

TASK: Tasks related to the lab will be provided by the instructor.

FCS&E, GIK Institute Topi, Pakistan Page 91 of 103


Lab#12 High Performance Computing

Learning Objectives:
 What is HPC
 Operating System of HPC
 Applications of HPC
 HPC System Specification in GIKI
 How to use HPC for your CS101 Lab

Outcomes:
 Students should be able to operate HPC.

FCS&E, GIK Institute Topi, Pakistan Page 92 of 103


What is High Performance Computing?
High Performance Computing most generally refers to the practice of aggregating computing power in a
way that delivers much higher performance than one could get out of a typical desktop computer or
workstation in order to solve large problems in science, engineering, or business.

Software makes the cluster go ‘round

Just like your desktop or laptop, your HPC cluster won’t run without software. Two of the most popular
choices in HPC are Linux (in all the many varieties) and Windows. The choice of operating system should
really be driven by the kinds of applications you need to run on your high performance computer. If you
are using Excel to run option calculations in parallel, you’ll want a Windows-based cluster; and so on
Linux currently dominates HPC installations due to HPC’s legacy in supercomputing, large scale
machines, and UNIX i.e. As HPC is used for computationally expensive tasks (Just as Supercomputers) so
Linux is used over them as Windows Based systems are Slow due to Graphical User Interfaces.

Applications of HPC

Structural Mechanics: - Computation has played a central role in mechanics for more than 30 years.
Current HPC systems are being used to address challenging Problems throughout the field. Some of the
Problems in which HPC is used are;

1. Crash testing of Automobiles


2. Simulation of structural response of buildings and bridges to earthquakes and explosions
3. Response of nano-scale cantilevers to very small electromagnetic fields
4. Two-orders-of magnitude reduction in the number of wind tunnel models tested
5. Design of artificial heart valves with minimal degradation
6. Design and manufacture of efficient mechanical devices with respect to heat and mass transfer.
Other Problems described as being “ripe of impact” include full aircraft flow analysis, turbulent
flow simulation, composite materials design, understanding phase transitions, polymeric
materials design, and analysis of multiphase and particulate flows.

Computational biology: - In biology today, HPC is used for a variety of problems. Some of them
are;

1. The human Proteome Project recently finished rough predictions for all the proteins in the
human genome in a single year- a job that would have taken a century on the available
laboratory cluster.
2. Structure of bio-molecules ( Protein folding, molecular docking)
3. Sequence matching for similarity searching in biological databases
4. Simulation of biological phenomena (vascular flows, impulse propagation in biological nerve
tissue, etc).

Commercial Applications: - the emerging wave of HPC-enabled data-intensive solutions can help
companies, government organizations, and others tackle a wide range of previously intractable

FCS&E, GIK Institute Topi, Pakistan Page 93 of 103


problems that are important for economic competitiveness, scientific advancement, national
security, and the quality of human life. Some of the problems in which HPC is required are;

1. Fraud Detection
2. Transaction processing
3. Data mining
4. Scalable Web and Database Servers etc

HPC System Specification in GIKI

The summary of the system is as follows:

 Total CPUs: 160 cores using latest 16C AMD Opteron Processors
 Total main memory: 640 GB of 1600MHz
 Total GPUs: 1024 cores (Tesla 2090
system)
 Connectivity: 10GB Ethernet switch
 Hard disks: 1.8TB with 15k rpm (speed)

The Cluster installed in GIKI is intended to provide


high performance computing and parallel processing
facilities to the GIKI R&D community. Currently, it is
being utilized for the study of various problems in the
scientific and engineering domains by graduate and
undergraduate students, research associates and
faculty. This facility is also intended as a hub and a
model for scientific technical/industrial and
business/commercial organizations of Pakistan to
fulfill their high-end computing needs.

FCS&E, GIK Institute Topi, Pakistan Page 94 of 103


FCS&E, GIK Institute Topi, Pakistan Page 95 of 103
Accessing the Cluster and Running your First C++ Program on it

1. Double click on the Putty (A Client Software for remote Login) on your Desktop, Enter the
Highlighted IP Address i.e. 192.168.100.21 and then click Open (Encircled in the Figure).

FCS&E, GIK Institute Topi, Pakistan Page 96 of 103


2. After you click on Open the following Screen Appears, This prompts the user for user name and
Password.

3. I have enter the user name u11 and Password 123

FCS&E, GIK Institute Topi, Pakistan Page 97 of 103


4. Now you are login in the Cluster as user u11 , this can be seen in the above screen shot.

To write your first C++ Program, We have to type our code in the editor.

5. When you press enter the following screen appears, which is the editor window:
 Type Your Program in the editor (Nano editor)

FCS&E, GIK Institute Topi, Pakistan Page 98 of 103


After you have finished typing your Program, Press Ctrl + O to save it, then Press Enter and the Ctrl + X to
exit the editor.
Now write the following Commands to Compile and Run your Program
 g++ myfirstprogram.cc -o myfirst

 The above command compiles and creates the output file myfirst

 ./myfirst ( to run the created myfirst file)

 You can see that the output appears after entering the ./myfirst

 The Output is “ This is my first C++ Program “

Similarly We can run Other C++ Programs.

FCS&E, GIK Institute Topi, Pakistan Page 99 of 103


TASKS:
 What’s the Procedure to Access the Cluster?

 Access the Cluster (using Putty)

 Open the NANO Editor or Vi Editor

 Use NANO Editor Commands

 Make a Simple Calculator which does basic Arithmetic using NANO Editor

 Compile and Run the Program

 Please Do Your Assign Lab Task on the Cluster

FCS&E, GIK Institute Topi, Pakistan Page 100 of 103


Lab#13: Open ended lab

Introduction:
An open ended lab is where students are given the freedom to develop their own critical thinking to
solve a given problem, instead of merely following the preset guidelines from the lab manual or a book.
Working on Open-ended pushes students to develop critical thinking and come up with their own
solutions. An important aspect of open ended lab that a given problem may be solved in different ways,
therefore, students are encouraged to investigate different methods and justify the adopted approach.
Lab Instructor will have a debriefing session at the end of the open ended lab. The instructor may drop
pointers for the students and perhaps talk about the difficulties that the student faced while solving the
problem. This may be in the form of a lecture or a discussion and emphasis on essential learning points.

OEL Problem 1: The problem statement will be provided by the instructor before the start of the open
ended lab.

Aims: To use the decision control structures, loops, arrays, pointers and functions to design and
implement the given problem (Provided by the instructor).

Expected outcomes:
 Problem Analysis
 Proposed methodologies
 Algorithm to solve the problem
 Detailed design flow chart
 Demonstration of programming skills.
 Source code.

FCS&E, GIK Institute Topi, Pakistan Page 101 of 103


References:

[1] http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

*2+ “ The C++ Programming Language” Bjarne Stroustrup, 2009

*3+ “Let us C++”, Yashwant Kanethkar , 2nd Edition

[4] http://www.cplusplus.com/doc/tutorial/functions/

[5] http://www.functionx.com/cpp/Lesson05.htm

[6] http://www.macs.hw.ac.uk/~pjbk/pathways/cpp1/node176.html

[7] http://programmers.stackexchange.com/questions/157739/2-dimensional-arrays-in-c

FCS&E, GIK Institute Topi, Pakistan Page 102 of 103


RUBERIC FOR LAB EVALUATIONS

GRADING CRITERIA:

 Lab Evaluations: 35%


 Mids : 25%
 Finals: 40%

CLO/PLO MAPPING:

 Lab1 and Lab 2 are mapped to CLO1, which states that the student should have basic
software & hardware understanding.
 Lab3 to Lab 12 are mapped to CLO 2, which states that the student should be able to
apply fundamental concepts of computer programming using mathematical concepts
and operations.
 Lab 13 is mapped to CLO 3, according to which a student should be able to analyze and
design simple modular program with elementary constructs of a programming language.
 All the labs are mapped to PLO 1, which states that a student is expected to show
guided response for all the programming concepts..

FCS&E, GIK Institute Topi, Pakistan Page 103 of 103

You might also like