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

Department of Electrical and Computer Engineering

Pak-Austria Fachhochschule: Institute of Applied Sciences and


Technology, Haripur, Pakistan

Lab#01 Algorithm and Scratch

In this lab we will be discussing algorithm and scratch in detail.

Learning Objectives:
After completing this lab, student should be able to learn
➢ Algorithm
➢ Scratch

Outcomes:
➢ Students should be able to develop algorithm and implement them using scratch.

7
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

1 ALGORITHM

The word Algorithm means "a process or set of rules to be followed in problem-solving opera-
tions". Therefore Algorithm refers to a set of rules or instructions that step-by-step define how
a work is to be executed upon in-order to get the expected results.

PRACTICE PROBLEM

1. Write a pseudo code that calculates the average of 3 numbers.

2. Write a pseudo code that display all the multiples of 5 between 1 and 100.

3. Write a pseudo code that takes number from user and checks whether the number is
even or odd.
2 INTRODUCTION TO SCRATCH

Scratch is a programming language that lets you create your stories, animations, games,
music and art.
Go to the URL: https://scratch.mit.edu/

Perform the following steps

Step1: Make a new project by clicking on Create at top left

8
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
This would launch the following window

You can change the Backdrop from bottom right

Change the character Sprite by clicking on cat face logo

9
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Step2:: Drag the Move block in script area

Step3: Click on the Move block to make the cat move.

Step4: Click on the Looks. Drag out the Say block and snap it on the Move block.

Step5: Add another Move block. Click inside the block and type in a minus sign. Add another
Say block. Click on any of the blocks to run the stack.

10
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Step6: From Controls, drag out a Repeat block and drop it on top of the stack.You want the
mouth of the Repeat to wrap around the other blocks.

You may change the number of times it repeats.

Step7: Click on Events, drag out a Green Flag block and drop it on top of the stack. Whenever
you click the green flag, your script will start. To stop, click the stop button.

Click on the Green Flag to start the script.

11
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Click on the Red Button to stop the script.

Practice
Create a program that makes your character move around and draw continuously. You can use
pen down block to draw something.
Reference figure is given below for your help.

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

12
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

The aims of this lab are to introduce 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

13
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

14
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

2. Open new file (Ctrl+N) as

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

15
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

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

16
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

17
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

C++ Code

#include<iostream>
using namespace std;
int main()
{
cout<<" Welcome to C++ ";
return 0;
}

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 functionsthat the
program needs to use. iostream is a standard i/o library that contains declarations e.g., declaration for
cout.
Line 2: using namespace std
This is used to import the entirety of the std namespace into the current namespace of the program.
The statement using namespace std is generally considered a bad practice. When we import a
namespace we are essentially pulling all type definitions into the current scope. The std namespace is
huge. The alternative to this statement is to specify the namespace to which the identifier belongs
using the scope operator(::) each time we declare a type.
Line 3: 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 4: {
This opening bracket denotes the start of the program.
Line 5: 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 6: return 0;
This is also a statement. This statement is used to return a value from a function and indicates the
finishing of a function. This statement is basically used in functions to return the results of the
operations performed by a function.
Line 7: }
This closing bracket denotes the end of the program.

STANDARD OUTPUT (COUT)

cout is a C++ stream object, used for standard output by default is the screen. For formatted output
operations, cout is used together with the insertion operator, which is written as « (i.e., two "less than"
signs).

18
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Escape Sequences
Character combinations consisting of a backslash (\ ) followed by a letter or by a combination
of digits are called "escape sequences." To represent a newline character, single quotation
mark, or certain other characters in a character constant, you must use escape sequences.
An escape sequence is regarded as a single character and is therefore valid as a character
constant. Escape sequences are used to format our output. The following escape sequences
can be used to print out special characters.

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
\n Newline
\t Horizontal tab
\v Vertical tab

To insert a line break, a new-line character shall be inserted at the exact position the line
should be broken. In C++, a new-line character can be specified as n n (i.e., a backslash
character followed by a lowercase n). For example:

This produces the following output:

Alternatively, the endl manipulator can also be used to break lines. For example:

Output

19
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 2.1

Following program shows the use of Newline Escape Sequence (n n)

Output

Your Turn: Edit above given code and use endl manipulator.

Example 2.2

This program shows the use of Horizontal tab Escape Sequence (\t)

Output

20
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Now try escape sequences yourself.

Example 2.3

Program using multiple insertion operations («)

Output

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

21
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Lab#3: Variables, Inputs/Outputs and Comments

The aims of this lab are to cover some basics of C++ programming e.g., Variables, Types.

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.

22
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

23
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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- line /*Printing the
comment. variables
The comment characters (/*, */, and //) have no special */
meaning within a character constant, string literal, or comment. cout<<“The value of ch is ”
<<ch<<endl;
Example 3.2
cout<<“The value
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.

24
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

25
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

26
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

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

27
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#4: Arithmetic Operators, Comparison Operators, logical Operators,


Type Conversion

The aims of this lab are to cover some basics of C++ programming e.g., Operators and Type conversion.

Learning Objectives:
➢ To learn and to use
• Arithmetic Operators
• Comparison/Relational Operators
• logical Operators
• Type Conversion

Outcomes:
➢ Students should be able to know C++ different operators.
➢ Students should be able to use Type Conversion in the programs.

28
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

Example 4.1

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

29
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

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

30
IT & Computer Science Department
Example 4.2 Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
// C++ program demonstrating ! operator truth table
#include <iostream>
using namespace std;

int main() {
int a = 5;

// !false = true
cout << !(a == 0) << endl;

// !true = false
cout << !(a == 5) << endl;

return 0;
}

Output
1
0

31
IT & Computer Science Department
Example 4.3 Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
// C++ program demonstrating || operator truth table

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 9;

// false && false = false


cout << ((a == 0) || (a > b)) << endl;

// false && true = true


cout << ((a == 0) || (a < b)) << endl;

// true && false = true


cout << ((a == 5) || (a > b)) << endl;

// true && true = true


cout << ((a == 5) || (a < b)) << endl;

return 0;
}

Output
0
1
1
1

Type Conversion in C++


A type cast is basically a conversion from one type to another. There are two types of type conversion:

Implicit Type Conversion Also known as ‘automatic type conversion’.


• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.

• All the data types of the variables are upgraded to the data type of the variable with largest
data type.
bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

32
IT & Computer Science Department
Pak-Austria
long longFachhochschule: Institute
-> float -> double -> of Applied Sciences and
long double
Technology, Haripur, Pakistan
• It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).

Example 4.4

// An example of implicit conversion

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}

Output
x = 107
y=a
z = 108

Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user
can typecast the result to make it of a particular data type. This is done by explicitly defining the required
type in front of the expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.

33
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Example 4.5
// C++ program to demonstrate
// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Output
Sum = 2

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

34
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#5: Decision Control Statements I (If and If-else statements)

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

Learning Objectives:
➢ If Statement
➢ If - else statement
➢ else - if Statement

Outcomes:

➢ Students should be able to use if, if-else and else-if statements

35
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

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

36
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
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;
}
Example: 5.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;

return 0;
}

37
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Nested if-else statement


Nested if is basically if inside if.

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

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

38
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

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

39
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

40
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

41
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#6: Decision Control Statements II (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.

42
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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:

43
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 6.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";
}
}

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

44
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

45
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 6.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;
}

46
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

Example 6.4:
#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.

47
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#7: Iteration Structure I (While Loop and do 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.

48
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

49
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

50
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 7.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 7.3: Printing the numbers you entered using a while loop

51
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

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

52
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

53
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#8: Iteration Structure I (For Loop and Nested 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.

54
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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:

55
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

output:
Example 6.1:
8.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 8.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 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 ofloops
may be nested, the most commonly nested loops are for loops.

56
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.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 8.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");
}

57
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.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. 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, DO NOT put a semicolon after the
for's parentheses. Doing so will cause the for statement to execute only the counting portion of the
loop, creating the illusion of a timing loop. The body of the loop will never be executed.
Semicolons are required inside the parentheses of the for loop. The for loop is the only statement that
requires such semicolon placement.

58
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 8.6:
do-while:
int ctr = 1;
do
{
cout<<ctr++ <<"\n";
}while (ctr<= 20);
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.

59
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#9: 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.

60
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

61
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

62
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

63
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

64
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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 ? Trythis:

Example 9.5:
#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
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.

65
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

66
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#9: Multi-dimensional Arrays, Character Arrays

In this lab Arrays are covered in detail

Learning Objectives:
➢ 2D Array definition
➢ 2D Array declaration
➢ 2D Array Initialization
➢ Accessing 2D Array elements
➢ Reading string
➢ Displaying strings

Outcomes:
➢ Students should be able to understand and use 2D arrays and character arrays.

67
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Dimensional (2-D) Arrays


So far we have explored arrays with only one dimension. It is also possible for arrays to have two or
more dimensions. The two-dimensional array is also called a matrix.
Here is a sample program that stores roll number and marks obtained by a student side by side in a
matrix.

Example 10.1:
#include<iostream.h>
using namespace std:
void main( )
{
int stud[4][2] ; int i,j ;

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


{
cout<<"\n Enter roll no. and marks "<<endl ; cin>>stud[i][0]>>stud[i][1];
}
cout<<"The Roll No. and Marks are: "<<endl<<endl; cout<<"RollNo.\t Marks\n";
for ( i = 0 ; i <= 3 ; i++ )
cout<<stud[i][0]<<" \t "<<stud[i][1]<<endl ;

There are two parts to the program—in the first part through a for loop we read in the values of roll
no. and marks, whereas, in second part through another for loop we print out these values.
Look at the cin( ) statement used in the first for loop:

cin>>stud[i][0]>>stud[i][1];

In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for
every student. The second subscript tells which of the two columns are we talking about—the zeroth
column which contains the roll no. or the first column which contains the marks. Remember the
counting of rows and columns begin with zero. The complete array arrangement is shown below. Thus,
1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above arrangement

68
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
highlights the fact that a two- dimensional array is nothing but a collection of a number of one-
dimensional arrays placed one below the other.
In our sample program the array elements have been stored rowwise and accessed rowwise. However,
you can access the array elements columnwise as well. Traditionally, the array elements are being
stored and accessed rowwise; therefore we would also stick to the same strategy.

Initializing a 2-Dimensional Array

How do we initialize a two-dimensional array? As simple as this:


int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};

Or we can write like this also..

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

The above format work also but it is more difficult to read as compared to the first one. It is
important to remember that while initializing a 2-D array it is necessary to mention the second
(column) dimension, whereas the first dimension (row) is optional.

Thus the declarations,


int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;

int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;

are perfectly acceptable, whereas,


int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;

int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;


would never work.

Memory Map of a 2-Dimensional Array

Let see the arrangement of the above student arrays in memory which contains roll number and marks.

69
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Example 10.2:

This example will simply define an array of 2x3 and take input from user and prints scanned
array.

#include<iostream.h>
Using namespace std;
void main()
{
int arr[2][3],i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
{
cout<<"Enter Value for " <<i+1 << " row " <<j+1 <<" column\n";
cin>>arr[i][j];
}
cout<<"\n!!!Scanning Array Complete!!!\n\n\n";
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
cout<<arr[i][j] <<"\t";
cout<<"\n\n";
}
}

70
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 10.3:

#include <iostream>

using namespace std;

int main()

// A 2-Dimensional array

double distance[2][4];

cout<<"Enter values\n";

for(int i = 0; i < 2; ++i) // this loop is for Rows

for(int j = 0; j < 4; ++j) // this loop is for Columns

cin>>distance[i][j]; //getting values from the user

cout << "Members of the array"; // the statement will be print as it is

for(int i = 0; i < 2; ++i) // For Rows

for(int j = 0; j < 4; ++j) // For Columns

cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j]; //Printing Rows and Columns

cout << endl;

return 0;}

Arrays of Characters

Re-Introduction to Characters

As it happens, strings are the most used items of computers. In fact, anything the user types is a
string. It is up to you to convert it to another, appropriate, type of your choice. This is because
calculations cannot be performed on strings. On the other hand, strings can be a little complex,

71
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

which is why we wanted to first know how to use the other types and feel enough comfortable
with them.

Consider a name such as James. This is made of 5 letters, namely J, a, m, e, and s. Such letters,
called characters, can be created and initialized as follows:
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:

cout << "The name is " << L1 << L2 << L3 << L4 << L5;

Here is such a program:

Example 10.4:

#include <iostream>
using namespace std;

int main()

{
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

cout << "The name is " << L1 << L2 << L3 << L4 << L5; return 0;
}

Declaring and Initializing an Array of Characters

When studying arrays, we were listing the numeric members of the array between curly
brackets. Here is an example:

int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
Because a character is initialized by including it in single-quotes, when creating an array of
characters, to initialize it, you must also include each letter accordingly. A name such as
James can be initialized as follows:

char Name[6] = { 'J', 'a', 'm', 'e', 's' };

As done with other arrays, each member of this array of characters can be accessed using
its index. Here is an example:

72
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 10.5:

#include <iostream>
using namespace std; int main()

{
char Name[6] = { 'J', 'a', 'm', 'e', 's' };
cout << "The name is " << Name[0] << Name[1] << Name[2] << Name[3] << Name[4];
return 0;
}

The C/C++ provides another alternative. It allows you to declare and initialize the array as
a whole. To do this, include the name in double-quotes. With this technique, the curly
brackets that delimit an array are not necessary anymore. Here is an example:

char Name[12] = "James";

With this technique, the item between the double-quotes is called a string. It is also
referred to as the value of the string or the value of the variable.

When declaring and initializing an array of characters, the compiler does not need to know
the number of characters of the string. In fact, you can let the compiler figure it out.
Therefore, you can leave the square brackets empty:

char Name[] = "James";

After declaring such an array, the compiler would count the number of characters of the
variable, add one more variable to it and allocate enough space for the variable. The
character added is called the null-terminated character and it is represented as \0.
Therefore, a string such as James would be stored as follows:

J A m e s \0

Streaming an Array of Characters

Like any other variable, before using a string, you must first declare it, which is done by type
the char keyword, followed by the name of the variable, followed by square brackets.
73
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

When declaring the variable, if/since you do not know the number of characters needed for
the string; you must still provide an estimate number. You can provide a value large enough
to accommodate the maximum number of characters that would be necessary for the
variable. For a person's name, this could be 20. For the title of a book or a web page, this
could be longer. Here are examples:

char Name[20];
char BookTitle[40];
char WebReference[80];
char WeekDay[4];

To request the value of an array of characters, use the cin extractor just like you would
proceed with any other variable, without the square bracket. Here is an example:

char WeekDay[12];
cout << "Enter today's name: ";
cin >> WeekDay;

To display the value of an array of characters, use the cout extractor as we have used it
with all other variables, without the square brackets. Here is an example:

Example 10.6:

#include <iostream>
using namespace std;
int main()
{
char WeekDay[12];
char EndMe[] = "\n";
cout << "Enter today's name: ";
cin >> WeekDay;
cout << "Today is " << WeekDay;
cout << EndMe;
return 0;

Here is an example of running the program:

Enter today's name: Thursday

Today is Thursday
Multidimensional Arrays of Characters

C/C++ treats arrays of characters differently than it does the other arrays. For example, we
have learned to declare a two-dimensional array of integers as follows:
74
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

int Number[2][6] = { { 31, 28, 31, 30, 31, 30 },

{ 31, 31, 30, 31, 30, 31 } };

This variable is in fact two arrays and each array contains 6 integers. For a string, if you
want to declare a two-dimension array of characters, the first dimension specifies the
number of string in the variable. The second dimension specifies the number of characters
that each string can hold. Here is an example:

char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

In this case, the StudentName variable is an array of 4 strings and each string can have a
maximum of 9 characters (+1 for the null-terminated character). To locate a string on this
variable, type the name of the array followed by its index, which is the index of the column.
This means that the first string of the StudentName array can be accessed with
StudentName[0]. The second would be StudentName[1], etc. This allows you to display each
string on the cout extractor:

Example 10.7:

#include <iostream>

using namespace std;


int main()

{
char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };
cout << "Student Names";
cout << "\nStudent 1: " << StudentName[0];
cout << "\nStudent 2: " << StudentName[1];
cout << "\nStudent 3: " << StudentName[2];
cout << "\nStudent 4: " << StudentName[3];
return 0;
}

This would produce:

Student Names
Student 1: Hermine
Student 2: Paul
Student 3: Gertrude
Student 4: Leon

75
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

When declaring and initializing such an array, the compiler does not need to know the
number of strings in the array; it can figure it out on its own. Therefore, you can leave the
first pair square brackets empty. If you are only declaring the array but cannot initialize,
then you must specify both dimensions.

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

76
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#11: Structures

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 Structures will be covered.

Learning Objectives:
➢ Structure Declaration
➢ Structure Definition
➢ Structure Variables
➢ Structure Membership

Outcomes:
➢ Students should be able to use Structures.

77
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

STRUCTURES

Arrays require that all elements be of the same data type. Many times it is necessary to group
information of different data types. An example is a materials list for a product. The list typically
includes a name for each item, a part number, dimensions, weight, and cost.

C and C++ support data structures that can store combinations of character, integer floating point and
enumerated type data. They are called a STRUCTS.

Often multiple variables must be passed from one function to another, and often these variables have
different data types. Thus, it is useful to have a container to store various types of variables in. Structs
allow the programmer to do just that

A struct is a derived data type that consists of members that are each fundamental or derived data
types.

struct is used to declare a new data-type. Basically this means grouping variables together.

Structures Definition

Before a structure is created, it is necessary to define its overall composition. The format of the a structure
is provided in the shape of a template or pattern which is then used to create structure variables of the
same composition. The template is composed of the names and attributes of the data items to be included
in the structure. The definition begins with the keyword struct which is followed bya structure declaration
consist of a set of user-defined data names and data types. These entries are separated by semicolons
and enclosed within a pair of curly brackets. The definition ends with a semicolon. Thus, in general, the
structure definition has the form

struct tag-name
{
type var-1;
type-var-2;
........
typevar-n;

};
where tag-name is the user-supplied name that identified the structure template; type refers to
anyvalid data type such as char, int, float, and so forth; and var-1, var-2, ….var-n are user-defined
variables names, arrays or pointers. The components of a structure are commonly referred to as
members or field.

78
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 11.1:
struct employee
{
char name[30];
int age;
float salary;
}

Representation in Memory
struct student
{
char name[20];
int roll_no;
};
struct student st;

...
0123 19
roll_no

Structures Variables

This code fragment illustrates how structure variables of the type structemployee are defined.
struct employee{
char name[30];
int age;
float salary;
};
structemployee emp1, emp2, emp3;

In the above example three structure variables emp1, emp2, and emp3 are created. Each structure
consists of three members identified by name, age, and salary.

OR

79
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
struct employee
{char name[30];
int age;
float salary;

} emp1, emp2, emp3;

Structure membership
Members themselves are not variables they should be linked to structure variables in order to make
them meaningful members.
The link between a member and a variable is established using the member operator ‘.’ i.e. dot
operator or period operator. We access individual members of a structure with the .operator. For
example to assign a value, we can enter:

struct x
{int a;
int b;
int c;
};

main()
{
struct x z;

z.a = 10; // assigns member ‘a’ of structure variable z value 10.


z.b = 20;
z.c = 30;
}

And to retrieve a value from a structure member:

struct x
{
int a; int b; int c;
};
main()
{ struct x z;
z.a = 10; // Assigning a value to a member through a structure variable
z.a++; // incrementing the member variable.
cout<<z.a; // Retrieving the value.}

80
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 11.2

Accessing Structure Variables example:

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

81
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Creating multiple structure variables.

void main (void)


{
struct Library
{
int ISBN, copies, PYear;
char bookName[30], AuthorName[30], PublisherName[30];
};
Library libraryVariable1, libraryVariable2, libraryVariable3, libraryVariable4;
Library LibraryArray [4]; // alternative and easiest way
}

Assignment a structure variable to another Structure Variable

The value of a structure variable can be assigned to another structure variable of the same type, e.g:

Library libraryVariable1, libraryVariable2;


libraryVariable1.ISBN = 1293;
libraryVariable2 = libraryVariable1;

Common Errors in Accessing Structures

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

82
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#12: Functions I

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.

83
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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 itis
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() inour 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.

84
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

85
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 12.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 12.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;}

86
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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 transferredto 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 isshown
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 12.4:
Lets do another example of making a program using functions which will tell us whether the input number
is even or odd.

87

87
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

88

88
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

Example 12.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!!!!!!!

89

89
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Compile and run this program.

Example 12.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";

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.

90

90
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.

91

91
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#13: Functions II

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.

92

92
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

93

93
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

94

94
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

95

95
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

Example 13.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;
}

The output of the rand( ) function could be in the range of 0 to 32767 which is the upper limit for an integer.
96

96
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

97

97
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

98

98
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#14: File Handling

In this lab we will be discussing file handling in detail. This is one of the most important concepts in C++
language.

Learning Objectives:
After completing this lab, student should be able to learn
➢ Streams in c++
➢ Input/output with files
➢ Open a file
➢ Closing a file
➢ Checking for end of file

Outcomes:
➢ Students should be able to understand and use file handling

99

99
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Streams in C++

A stream is basically flow of data from or to the program. There are two types of streams
1. Input Stream- An input stream is flow of data into the program (e.g. cin)
2. Output Stream- An output stream is flow of data out of the program (e.g. cout)

What does iostream.h contain?

#include <iostream>
When we write this at the beginning of the program, it basically means that we are instructingthe
compiler to include the contents of the file iostream.h into our source file before compiling.

iostream.h (short for input/output stream) has certain classes and objects defined within the file,
which we can use in our program directly. It contains the following classes for input/output of data:
• ios- Base class for all other classes for input and output
• istream- Derived from ios. Used to input data into the program (input stream). cin
is an object of this class.
• ostream- Derived from ios. Used to output data out of the program (output
tream).cout is an object of this class.
Meaning of cin>> and cout<<

When we write the statement:


cout << "Hello";

the << (insertion operator) passes the value following it (i.e a char * pointing to the string
―Hello‖) to the object cout, which in turn acts as an output stream, and hence passes it on to the
screen from the program.
Similarly, when we write the statement:

string s; cin
>> s;
The >> (extraction operator) passes each character of the value the user enters to the object cin, which
in turn acts as an input stream, and hence passes it from the keyboard into the program.
The problem with cout<< is that it only allows flow of data from the program to the screen. Similarly,
cin>> only allows flow of data from the keyboard into the program.

100
100
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

In order to output data from our program to a physical file, or to input from a physical file into our
program, we use the concept of file-handling. We will work with text files for now.

Input/output with files

C++ provides the following classes to perform output and input of characters to/from files:
#include<fstream>
The file fstream.h contains all the contents of iostream.h (istream class, ostream class etc.),along
with certain classes of its own. It contains:
• ifstream- Class derived from istream. Allows input from other sources apart
from justthe keyboard.
• ofstream- Class derived from ostream. Allows output other than just the screen.
• fstream- a class which contains all the contents of ifstream, and ofstream
throughmultiple inheritance.

Writing to a physical file

Example 14.1:
#include <fstream>
using namespace
std;int main ()
{
fstream myfile; //Declare an object of class fstream
myfile.open("abc.txt",ios::out); //open the file using a
stream
myfile << "Hello" << endl; //write to file using the object
declared
myfile << "World" << endl;
myfile.close(); //close the file
return 0;
}

This code creates a file called abc.txt and inserts words into it in the same way we are used to do with
cout, but using the file stream myfileinstead.

101
101
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Reading from a physical file

#include <iostream>
#include <fstream>
using namespace
std;int main ()
{
fstream myfile; //Declare an object of class fstream

myfile.open("story.txt",ios::in); //open the file using astream


string s;
myfile >> s; //read from file using the object declared
myfile.close(); //close the file
return 0;
}

This piece of code reads from a physical file. But let‘s go step by step:

Open a file

The open() function is used to opening an object in a particular stream. It takes twoarguments, the
name of the file (datatype char*), and the mode in which to open the file.
• ios::out- Output mode to take data from program out to a file.
• ios::in- Input mode to take data from file into the program.
• ios::app- Append mode to add data to an existing file. If this is not specified, opening
the file in output mode will overwrite the existing contents of the file, if the file already
exists.
• ios::trunc- Truncate mode to indicate that the file, if it exists, should be overwritten
on.

The mode can be have more than one value, separated by the | operator. For example:

myfile.open("abc.txt", ios::out | ios::app);

102

102
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode
that is used if the file is opened without a second argument:

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even ifa
mode that does not include them is passed as second argument to the open() memberfunction.

The default value is only applied if the function is called without specifying any value for the mode
parameter. If the function is called with any value in that parameter the default mode is overridden,not
combined.

Additional ways to read from file

If you have an object which opens a file in input mode, writingF >> s;
Is similar to doing cin >> s. Just like cin >>, F >> would read just a word from the file, as it takes any white-
space (i.e space, tab or new line) as a string terminator. There are a few alternate ways of inputting data:

getline()

It is a member function of class istream, and is used to input a line from the user. Forexample:
cin.getline(str,80);

It takes 3 arguments:
1. The name of the string (usually a character array and not a cstyle string)
2. Maximum number of characters in the string (it is important to remember that the last
character must also be string terminator)
3. A delimeter which terminates string input as soon as it is encountered (default is the
enter key) i.e as soon as the user enters the enter key, the string is terminated.
We can also use getline() with fstream objects:

fstream F; char str[80];


F.getline(str,80);

103

103
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

get()

It is a member function of class istream, and is used to input a character from the user. For example:

char ch; ch=cin.get();

Similarly it can also be used with fstream objects:


ch=F.get();

Closing a file

When we are finished with our input and output operations on a file we shall close it so that its resources
become available again. In order to do that we have to call the stream's member function close(). This
member function takes no parameters, and what it does is to flush the associated buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used to open another file, and the file is
available again to be opened by other processes.

In case that an object is destructed while still associated with an open file, the destructor automatically
calls the member function close().

Checking for end of file

When reading the entire contents of a file, it is often required to check whether we havereached
the end of a file or not.

Function eof()- end of file

This is a function which returns true if we have reached the end of a file.

fstream f;
f.open("story.txt",ios::in);
string s;
f>>s;
while(!f.eo
f())
{
cout<<s<<e
ndl;f>>s;
}
104

104
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
Practice Problem

What task does the following program perform?

#include<iostream>
#include<fstream> using
namespace std;

int main()

char data[100];
ifstream ifile;

//create a text file before executing.


ifile.open ("text.txt");
while ( !ifile.eof() )

ifile.getline (data, 100);cout


<< data << endl;

return 0;

Solution:
The program takes input from ‗text.txt‘ file and then prints on the terminal.

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

105

105
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Lab#15: 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.

106

106
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

107

107
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

108

108
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
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;

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.

109

109
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

Example 15.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;
}

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

110
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan
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 shownhere:
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.
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*/

111

111
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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

112
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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.
a b
30

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 valueas before
due to the assignment of line 19.
a b
30 0XF…

7864 7868 7872 7876 7880 7884 7888

ptr1 ptr2
113

113
IT & Computer Science Department
Pak-Austria Fachhochschule: Institute of Applied Sciences and
Technology, Haripur, Pakistan

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


114

114

You might also like