Lab Manual
Lab Manual
Lab Manual
Programming Fundamentals
BSCS-24/F-A1&A2
1st Semester, 1st Year
Instructor:
Mr. Irfan Ahmed
Lab 01
Objective:
IDEs normally consist of a source code editor, a compiler and/or interpreter, build-
automation tools, and (usually) a debugger.
It is a text editor program designed specifically for editing source code of computer
programs by programmers. Source code editors may have features specifically designed
to simplify and speed up input of source code, such as syntax highlighting and auto
complete
Visual Studio Code is a free, lightweight but powerful source code editor that runs on
your desktop and on the web and is available for Windows, macOS, Linux, and
Raspberry Pi OS. It comes with built-in support for JavaScript, TypeScript, and Node.js
and has a rich ecosystem of extensions for other programming languages (such as C++,
C#, Java, Python, PHP, and Go), runtimes (such as .NET and Unity), environments (such
as Docker and Kubernetes), and clouds (such as Amazon Web Services, Microsoft Azure,
and Google Cloud Platform).
Windows: You can install MinGW or MSYS2 to get the g++ compiler.
If you install with default options, MINGW64 will be installed in the path below. Copy
the path. C:\msys64\mingw64\bin
gcc --version
g++ --version
gdb --version
3. VSCode Activation
If it asks you “Do you trust the authors of the files in folder?”, Check the “Trust the
authors of all files in th parent folder” option.
Open VS Code.
Click on the Extensions icon on the left sidebar or press Ctrl+Shift+X.
Search for C++ and install the extension provided by Microsoft (C/C++ Extension
Pack).
This extension provides syntax highlighting, IntelliSense (code completion),
debugging, etc.
In your main.cpp file, you can start with a simple "Hello, World!" program:
#include<iostream>
//#include<conio.h>
int main()
{
cout<<"14 Computer Systems";
//getch();
return 0;
}
Exercise Solving
Lab 02
Objective:
Writing a Program:
To write a program in any programming language, it is necessary to know what about its
command and syntax. Programmers must also know the programming structure.
//Hello World
#include<iostream> // Pre-processor Directives
using namespace std;
int main() // Body of Program
{
Cout<< “Hello World”;
retrun 0;
}
EXAMPLE EXPLAINED
Line 1: #include <iostream> is a header file library that lets us work with input and
output objects, such as cout (used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables
from the standard library.
Don't worry if you don't understand how #include <iostream> and using namespace
std works. Just think of it as something that (almost) always appears in your program.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called
a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the INSERTION
OPERATOR (<<) to output/print text. In our example it will output "Hello World".
Note: The body of int main () could also been written as:
int main ()
return 0;}
Remember: The compiler ignores white spaces. However, multiple lines make the code
more readable.
Line 7: Do not forget to add the closing curly bracket} to actually end the main function.
C++ COMMENTS
Comments can be used to explain C++ code, and to make it more readable. It can also be
used to prevent execution when testing alternative code. Comments can be singled-lined or
multi-lined.
Any text between // and the end of the line is ignored by the compiler (will not be executed).
EXAMPLE
// This is a comment
cout << "Hello World!";
EXAMPLE
cout << "Hello World!"; // This is a comment
EXAMPLE
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
❮ PreviousNext ❯
New Lines
To insert a new line in your output, you can use the \n character:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Try it Yourself »
You can also use another << operator and place the \n character after the text, like this:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "\n";
cout << "I am learning C++";
return 0;
}
Try it Yourself »
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "\n\n";
cout << "I am learning C++";
return 0;
}
Try it Yourself »
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
string - stores text, such as "Hello World". String values are surrounded by double
quotes
Syntax
Where type is one of C++ types (such as int), and variableName is the name of the variable
(such as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the previous
value:
Example
Other Types
Example
You will learn more about the individual types in the Data Types chapter.
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Example
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;
C++ Identifiers
All C++ variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Example
// Good
int minutesPerHour = 60;
Constants
When you do not want others (or yourself) to change existing variable values, use the
const keyword (this will declare the variable as "constant", which means unchangeable
and read-only):
Example
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
cin is a predefined variable that reads data from the keyboard with the extraction operator
(>>).
In the following example, the user can input a number, which is stored in the variable x.
Then we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
There you go! You just built a basic calculator!
Exercise:
1. Write a program to display the following through input (name, father’s name,
department, roll number).
2. Write a program in c++ to convert hours into mins and secs by taking input from
the user:
Lab 03
Objective:
Familiarization with Constants, Variables, Keywords and Data types (int, float, char) and
using the Input & Output Functions
Data Types:
Variable Declaration:
TYPE VAR-NAME;
You can also declare more than one variables of same type by using comma-separated
list. For example
int a,b,c ;
A programmer can assign unique value to the variable. The general form of an
assignment statement is
cout:
cout is for character out, the ‘cout’ is a powerful and versatile object. Cout<< is an output
statement, it can be used to print numbers, strings of characters. Cout is an object and it is
defined as a keyword. Syntax of cout is as follows:
Cout<<“DCET”;
cin:
cin is for character in, the ‘cin’ receives input from the keyboard. Syntax of cin is as
follows:
Example:
#include <iostream>
using namespace std;
int main() {
int i;
float f;
i=10;
f=i;
f=f+0.5;
cout<<”Integer value is”<<i;
cout<<“Float value is”<<f;
}
Exercise:
Lab# 03
Objective:
Identify with the different types of Operators, Expressions and the Formula Evaluation in
C+ +
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder Operator)
The +, -, /, * operators are used with any of the data type but % operator can only be
used with integer type only. Arithmetic operators are further more divided in two forms
described below:
Unary Operators:
Unary operators are those which can be implemented on a single operand. Commonly
used unary operators are + +, - -
Increment Operator
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y = x++;
Output
Post increment operator
Value of x= 11
Value of y= 10
Pre increment operator
Value of a= 16
Value of b= 16
Decrement Operator
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y = x--;
cout << " Post decrement operator"<< endl;
cout << " Value of x = " << x << endl;
cout << " Value of y = " << y << endl;
int a = 15;
int b = --a;
cout << " Pre decrement operator" << endl;
cout << " Value of a = " << a << endl;
cout << " Value of b = " << b << endl;
return 0 ;
}
Output
Value of x = 9
Value of y = 10
Pre decrement operator
Value of a = 14
Value of b = 14
Binary Operators:
Binary operators are those which can be implemented on two operands. Commonly used
binary operators are +, –, *, /, %
operators. However a programmer can alter the order of evaluation using parentheses. For
example, the result of the following expression is ‘0’.
40 – 10 * 4
but the following produces 120
(40 – 10) * 4
Relational Operators are used for comparison; the operators are used to determine
whether two expressions or numbers are equal, greater, less than the other expressions.
These are the expressions that result in being true or false.
Logical Operators
Example:
#include <iostream>
using namespace std;
int main() {
int num,sqroot;
float a,b,c,d;
cout<<“enter number for root ”<<endl;
cin>>num;
cout<<“enter values for a & b”<<endl;
cin>>a>>b;
sqroot=sqrt(num);
cout<<”the value of square root is”<<sqroot
c=a+b/sroot;
d=(a+b)/sroot;
cout<<”the results of other operations are”<<c<<endl<<d;
getche( );
}
C++ Math
C++ has many functions that allow you to perform mathematical tasks on numbers.
Example
cout << max (5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);
Other functions, such as sqrt (square root), round (rounds a number) and log (natural
logarithm), can be found in the <cmath> header file:
Example
// Include the cmath library
#include <cmath>
Arithmetic Functions:
Example:
#include <iostream>
using namespace std;
int main() {
float x,res;
cout<<”enter the value of x to calculate the log”<<endl;
cin>>x;
res=log(x);
cout<<”value of log”<<x<<”is ”<<res<<endl;
cout<<”enter the value of x to calculate the sin”<<endl;
cin>>x;
res=sin(x);
cout<<”value of sin”<<x<<”is ”<<res<<endl;
getche();
Exercise:
Lab# 05
Objective:
Studying conditional statement –if and studying various variations of If statement and
difference b/w them
If the test is true then the next statement is executed, if is false then the statement
following the else is executed. After this, the rest of the program continues as normal.
If more than one statement following the “if” or the “else”, the statements written in the
body of the “if” and “else” Such a grouping is called a compound statement or a block.
if (exp 1)
{
statement 1;
----------
----------
}
if (exp 2)
{
statement 2;
----------
----------
}
else
{
statement;
}
In the above example exp 1 will be evolved independently. Means, exp 2 will be
executed what is the result (true/ false) of exp 1. It is noted that “else” will be executed if
all the test condition result is false.
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. In
the following example we are awarding grades depending on the exam result.
Example Else-if
if (result >= 75)
cout<<"Passed: Grade A";
else if (result >= 60)
cout<<"Passed: Grade B";
else if (result >= 45)
cout<<"Passed: Grade C";
else cout<<" Failed";
In the above example evolving of exp 2 will depend on exp 1. Means, 2 will be evolved if
exp 1 evolved as false. But else will be executed if all the test conditions evolve as false.
Number of else-if statements will depend on programmer’s requirement.
Exercise:
2. Write a c++ program that determines student grade. the program will read 3
types of scores (quiz, midterm and final term numbers and determine grade:
Lab# 06
Objective:
The switch statement can be used to replace the multi-way test (alternative way of if
statements and have clear format). When the tests are like this:
If (grade = = ‘A’) ...
else if( grade = = 'B' ) ...
else if( grade = = 'C' ) ...
else ...
Testing a value against a series of constants, switch statement having the clearer format
and it can be used as the given example
#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”);
break;
case 'B':
cout<<"Your average must be between 80 - 89");
break;
case 'C':
cout <<"Your average must be between 70 - 79");
break;
case 'D':
cout <<"Your average must be between 60 - 69");
break;
default:
Department of Computer Science,
Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)
The case statements, if true the compiler runs that case; default condition runs if none of
the other cases are satisfied. (A default is optional)
The “Break Statement” just breaks the execution, if one of the cases is true, because cases
runs one after the other and as one of the cases is true then break uses as an explicit
action to escape.
case 'a': case 'A': ...
Conditional operator ( ? )
If the condition is true the ‘result1’ expression will be executed and if the condition
becomes false the ‘result2’ expression will run.
See the following statements:
a=2;
b=7;
c = (a>b) ? a : b;
cout<<c;
}
In the above example value of a is 2 and b is 7, now the condition is evaluated as false
since “a>b” is not true, thus the first value specified after the question mark was
discarded in favor of the second value (the one after the colon) therefore value of b is
transferred or shifted in c, and value of c will be printed as 7.
Exercise:
LAB# 07
Objective:
The “for loop” in C/ C + + is the most general looping construct. The loop header
contains three parts:
Initialization,
Test Expression (continuation condition)
an increment/decrement operator (action)
<Statements>
At the first step initialization is done once before the body of the loop is entered. The
loop continues to run until the test condition remains true. After every execution of the
loop, the action is executed. The following example executes 10 times by counting 0,
1,2……9.
{
<Statement>
}
Each of the three parts of ‘for loop’ can be made up of multiple expressions separated by
commas. Expressions separated by commas are executed in order, left to right, and
represent the value of the last expression.
Example
#include <iostream>
using namespace std;
int main() {
int i;
{
cout<<”value of i =”<<i;
getche ( );
Exercise:
Lab# 08
Objective:
‘While loop’ structure is same as the ‘for loop’ and simple but it is distributed throughout
the program. It has the general form as:
Nearly same as for loop as first the condition is initialized then test and after execute the
loop body action (increment/decrement) be done; but it is more appropriate, when some
statements or part of program should be run on unknown multiple times or when the limit
is unknown.
Example
#include <iostream>
using namespace std;
int main() {
int count=0;
cout<<“type a phrase…”;
while(getche() != ‘\r’)
{
count++;
}
Cout<<“\n character count is”<<count;
}
Exercise:
LAB# 09
Objective:
Do while loop:
It is the last loop structure i-e ‘do-while’ loop. This loop is very identical to the ‘while’
loop but, the difference is in the ‘do’ loop, the test condition is executed/evaluated after
the loop is executed rather than before. It has the general form as:
do
{
Statements;
Or multiple statements;
}
While (expression);
As in the if else or for loop, if only one statement is in the loop body, the curly braces are
not necessary.
Do while operation:
The “do” part executes while expressions are “TRUE”. The uniqueness of the “do while
loop” is that, it executes the do part statement, if the condition is FALSE, since the
expression controlling the loop is tested at the bottom of the loop.
The operation of this loop is like a upside down version of the ‘while’ loop. The body of
the loop is first executed then the test condition is checked therefore the body of the loop
is always executed at least once.
Example:
#include <iostream.h>
#include <conio.h>
void main(void)
{
clrscr();
char ch;
do
{
cout<<"\n Type character from 'a' to 'e'"<<endl;
while ((ch = getche ())!='c')
{
cout<<ch<<"is incorrect"<<endl;
cout<<"try again";
}
cout<<"\n thats it!"<<endl;
cout<<"\n play again?(type 'y' or 'n'";
}
While (getche ( ) = = 'y');
{
cout<<"\n Thanks for playing";
}
getche ( );
}
Exercise:
1. Write a c++ program to print the table of any number through input:
LAB# 10
Objective:
Arrays:
When the programmer needs to store the seven integer values, so seven variable of
integer type has to be declared but; this is difficult to control lot of variables and it is
burden to a compiler, answer to this solution is an “Array”. Array may be one
dimensional, two dimensional and may be more dimensional.
Arrays contain the contiguous block of memory and contain the same type of data items.
Arrays are a handy way of grouping a lot of variables under a single variable name. The
data store in the arrays is called “Array Elements” and the elements can be addressed by
the index number. Index number starts from zero (0), if one is declare the array of 5
elements the maximum index is of 4.
Initializing an Array:
An array can be declared and initialize as int temp [5], “int” is the data type of array,
“temp” is name of array and “5” is the size of an array.
int temp [5] tells the compiler that an array is declare having name “ temp” and holds the
“ 5” spaces of “ int” type in the memory.
Array---- temp
Multi-Dimensional Arrays:
Multidimensional arrays are arrays that have more than one index: instead of being just a
single line of slots, multidimensional arrays can be thought of as having values that
spread across two or more dimensions.
Arrays can have more dimensions, in which case they might be declared as
int results_2d[20][5]; (two Dimensional Arrays)
For Loop is the co-worker with arrays. ‘For Loop’ is used to handle the index number of
the array. Consider a one dimensional array having name test. A for loop can be used to
insert the elements in an array, so that all its elements contain zero.
void main ()
int test[5];
array[i] = 0;
C/ C++ do not tell if you try to write to elements of an array which do not exist.
For example:
C++ language will write the character ‘* ‘ at the specified (seventh) location; but the
array is declare of 5 spaces. The result will be unpredictable or the program is crash or
corrupted. Writing over the bounds of an array is a common source of error. C + + does
not have range checking, (range checking can be done, the value of for loop variable is
checked with the index number) so if values is more than the index, it will not tell you
about it. It will give the garbage data.
Example:
#include <iostream>
using namespace std;
int main() {
int abc[5];
int i;
int sum=0;
float avg;
int a=0;
clrscr();
for(i=1;i<6;i++)
{
cout<<"enter "<<++a<<" number"<<endl;
cin>>abc[i];
sum+=abc[i];
}
cout<<"sum = "<<sum<<endl;
avg=sum/5;
cout<<"avg ="<<avg<<endl;
getche();
}
Exercise
1. Observe the output and remove the logical errors in the above program.
LAB# 11
Objective:
To familiarize with Functions and Understand Function Declaration, Call and functions
with return Statement:
Theory:
In C + +, Function is the basic building block. Functions are the specific or certain parts
of the program. Different functions are used to fulfill the task. C/C++ offers some
functions such as clrscr ( ), sqrt ( ) and others called Pre defined functions and user can
make their own function called User Defined Functions.
Use of Function
In many programs some task has to be done repeatedly or some specific code runs more
than once. If repetition is done by writing the code multiple times, it causes to increase
the programming code, and thus size and complexity of the program increases. In order to
remove or avoid this problem, Function is the answer. The code of function is written
once and utilized number of times, thus the size and complexity of program is reduced.
1. Function Declaration
2. Function Definition
3. Function Call
Function Declaration
A function is defined by function name; it tells the compiler that what is the name of the
function, function return some value or not if returns what will be the data type and
function passing the arguments.
Function Definition
Function definition is the function itself. Function definition tells the compiler that a
function is being defined which can perform certain specific task. Infact, it is the
programming code of the function. Function definition includes the function name,
number and data type of the values the function is returning.
Function Call
Function call transfers the control to the called function to do the assigned task.
#include <iostream>
using namespace std;
func1( ); // function declaration ( user defined function)
func2( ); // function declaration ( user defined function)
int main() {
If a function wants to return value in a program then “return ( )’ statement is used. The
‘return ( )’ statement has two purposes. First, it immediately transfers control from the
function back to the calling program (from where the function was called). Secondly,
whatever is inside the parenthesis following the ‘return’ is returned as a value to the
calling program.
The ‘return’ statement does not need to be at the end of the function. It can occur
anywhere in the function, control will be transferred to the calling program.
There are certain limitations for using ‘return’ statement. It can only return a single value.
Therefore using a ’return’ statement, only one value can be returned by a function.
#include <iostream>
using namespace std;
int add (int, int); // function declaration
void main()
{
int a,b;
int result;
cout<<"enter 1st number to add"<<endl;
cin>>a;
cout<<"enter 2nd number to add"<<endl;
cin>>b;
result =add(a,b); // function call
cout<<"result is=\t"<<result; // print result (result having the value of “ ans” of add
function)
getche( );
}
int add(int x, int y) // function definition
{
int ans;
ans= x+y;
return (ans); // return value to where the function is called
}
Exercise:
1. Find the area of shapes (circle, triangle, rectangle, and square). using function
overloading in c++:
Instructions:
Instructions:
Instructions:
Instructions:
LAB #12:
Objective:
In this lab, you'll learn to handle strings in C++. You'll learn to declare them, initialize
them and use them for various input/output operations.
Theory
String is a collection of characters. There are two types of strings commonly used in C++
programming language:
Strings that are objects of string class (The Standard C++ Library string class)
C-strings
In C programming, the collection of characters is stored in the form of arrays. This is also
supported in C++ programming. Hence it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).
Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.
Like arrays, it is not necessary to use all the space allocated for the string. For example:
#include <iostream>
int main()
char str[100];
return 0;
Output
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per
your requirement.
#include <iostream>
int main()
string str;
getline(cin, str);
return 0;
Output
In this program, a string str is declared. Then the string is asked from the user.
Instead of using cin>> or cin.get() function, you can get the entered line of text
using getline().
getline() function takes the input stream as the first parameter which is cin and str as the
location of the line to be stored.
Exercise:
2. Write a program to compare two strings for equality using the == and ! =
operators. Suppose you ask the user for his or her name. If the user is Julie, the
program prints a warm welcome. If the user is not Neal, the program prints the
normal message. Finally… if the user is Neal, it prints a less enthusiastic
response.
LAB #13
Objective:
In this lab, you'll learn about structures in C++ programming; what is it, how to define it
and use it in your program.
Theory
For example: You want to store some information about a person: his/her name,
citizenship number and salary. You can easily create different variables name, citNo, and
salary to store these information separately.
However, in the future, you would want to store information about multiple persons.
Now, you'd need to create different variables for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable
and efficient as well.
This collection of all related information under a single name Person is a structure.
The struct keyword defines a structure type followed by an identifier (name of the
structure).
Then inside the curly braces, you can declare one or more members (declare variables
inside curly braces) of that structure. For example:
struct Person
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and salary.
The structure definition is only the blueprint for the creating of variables. You can
imagine it as a datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is defined.
Once you declare a structure person as above. You can define a structure variable as:
Person bill;
When structure variable is defined, only then the required memory is allocated by the
compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.
Suppose, you want to access age of structure variable bill and assign it 50 to it. You can
perform this task by using following code below:
bill.age = 50;
C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
struct Person
char name[50];
int age;
float salary;
};
int main()
Person p1;
cin.get(p1.name, 50);
return 0;
Output
Enter age: 27
Displaying Information.
Age: 27
Salary: 1024.4
Here a structure Person is declared which has three members name, age and salary.
Inside main () function, a structure variable p1 is defined. Then, the user is asked to enter
information and data entered by user is displayed.
Exercise
LAB #14:
Objective:
In this lab, we will learn about pointers in C++ and their working with the help of
examples.
Theory
In this tutorial, we will learn about pointers in C++ and their working with the help of
examples.
In C++, pointers are variables that store the memory addresses of other variables.
Address in C++
If we have a variable var in our program, &var will give us its address in the memory.
For example,
#include <iostream>
int main()
// declare variables
int var1 = 3;
Output
Notice that the first address differs from the second by 4 bytes and the second address
differs from the third by 4 bytes.
Note: You may not get the same results when you run the program.
C++ Pointers
As mentioned above, pointers are used to store addresses rather than values.
int *pointVar;
int* pointVar, p;
Note: The * operator is used after the data type to declare pointers.
var = 5;
pointVar = &var;
Here, 5 is assigned to the variable var. And, the address of var is assigned to
the pointVar pointer with the code pointVar = &var.
To get the value pointed by a pointer, we use the * operator. For example:
var = 5;
pointVar = &var;
In the above code, the address of var is assigned to pointVar. We have used
the *pointVar to get the value stored in that address.
When * is used with pointers, it's called the dereference operator. It operates on a
pointer and gives the value pointed by the address stored in the pointer. That
is, *pointVar = var.
#include <iostream>
int main() {
int var = 5;
int* pointVar;
pointVar = &var;
cout << "Address of var (&var) = " << &var << endl
<< endl;
cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar
<< endl;
return 0;
Department of Computer Science,
Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)
Output
var = 5
pointVar = 0x61ff08
If pointVar points to the address of var, we can change the value of var by
using *pointVar.
For example,
int var = 5;
int* pointVar;
pointVar = &var;
*pointVar = 1;
Here, pointVar and &var have the same address, the value of var will also be changed
when *pointVar is changed.
#include <iostream>
int main() {
int var = 5;
int* pointVar;
pointVar = &var;
// print var
// print *pointVar
<< endl;
var = 7;
// print var
// print *pointVar
<< endl;
*pointVar = 16;
// print var
// print *pointVar
return 0;
Output
var = 5
*pointVar = 5
var = 7
*pointVar = 7
var = 16
*pointVar = 16
// Wrong!
varPoint = var;
// Wrong!
// &var is an address
*varPoint = &var;
// Correct!
varPoint = &var;
// Correct!
*varPoint = var;
Exercise