0% found this document useful (0 votes)
21 views61 pages

Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views61 pages

Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 61

Prepared by: Mr.

Irfan Ahmed (Lecturer)

DAWOOD UNIVESITY OF ENGINEERING AND


TECHNOLOGY, KARACHI
Department of Computer Science (BSCS)

Lab Manual

Programming Fundamentals
BSCS-24/F-A1&A2
1st Semester, 1st Year
Instructor:
Mr. Irfan Ahmed

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Lab 01
Objective:

To Familiarize Integrated Development Environment: C++ Programming

Integrated Development Environment:

An integrated development environment (IDE), also known as integrated design


environment and integrated debugging environment, is a type of computer software that
assists computer programmers in developing software.

IDEs normally consist of a source code editor, a compiler and/or interpreter, build-
automation tools, and (usually) a debugger.

Source Code Editor:

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

What is Visual Studio Code?

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

1. Install Visual Studio Code

 Go to the VS Code website.


 Download and install the version of VS Code appropriate for your operating
system (Windows, macOS, or Linux).

2. Install C++ Compiler

 Windows: You can install MinGW or MSYS2 to get the g++ compiler.

2.1 Copy the MINGW64/bin Path

If you install with default options, MINGW64 will be installed in the path below. Copy
the path. C:\msys64\mingw64\bin

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

2.2 Add the Path to Environmental Variables

Go to Windows Settings. Seach for "edit environmental variables". Then


edit Path in User Variables:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

2.3. Check MINGW64 Installation

Open new Command Prompt or Terminal and write commands below:

 gcc --version
 g++ --version
 gdb --version

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

3. VSCode Activation

Created new folder and opened on VSCode.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Open Terminal and Configure Tasks

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Run and Select g++ build and debug activation file

4. Install C++ Extension in VS Code

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

5. Set Up Your Workspace

 Create a new folder for your lab.


 Open this folder in VS Code using File -> Open Folder.
 Inside the folder, create a new file with the .cpp extension. For example,
main.cpp.

6. Write a Sample C++ Program

In your main.cpp file, you can start with a simple "Hello, World!" program:

#include<iostream>

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

//#include<conio.h>

using namespace std;

int main()
{
cout<<"14 Computer Systems";
//getch();
return 0;
}

Exercise Solving

Exercise 1: On your computer, type in the hello program and


execute it. Show the pictures of both source code and output
screen.

Exercise 2: Take several programming examples from any


source, enter them into the computer, and run them. Show the
pictures of both source code and output screen.

Exercise 3: How do you run a C++ program from the terminal in


Visual Studio Code? Write the steps to compile and run a simple
"Hello, World!" program from the terminal using the g++
compiler.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Lab 02
Objective:

To Familiarize and Basic Structure of C/ C + + Programming

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.

Simple C++ program in DEV/VS code and understanding.

//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 3: A blank line. C++ ignores white space.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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: Every C++ statement ends with a semicolon;.

Note: The body of int main () could also been written as:
int main ()

{ cout << "Hello World! ";

return 0;}

Remember: The compiler ignores white spaces. However, multiple lines make the code
more readable.

Line 6: return 0 ends the main function.

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.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

EXAMPLE
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

EXAMPLE
cout << "Hello World!"; // This is a comment

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

C++ MULTI-LINE COMMENTS


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

EXAMPLE
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

C++ New Lines

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

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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 »

Another way to insert a new line, is with the endl manipulator:

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

 bool - stores values with two states: true or false

Declaring (Creating) Variables


Department of Computer Science,
Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

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:

int myNum = 15;


cout << myNum;

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

int myNum = 15; // myNum is 15


myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

Other Types

A demonstration of other data types:

Example

int myNum = 5; // Integer (whole number without decimals)


double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

You will learn more about the individual types in the Data Types chapter.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

int myAge = 35;


cout << "I am " << myAge << " years old.";

Add Variables Together


To add a variable to another variable, you can use the + operator:

Example

int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

Declare Many Variables


To declare more than one variable of the same type, use a comma-separated list:

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;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

C++ Identifiers
All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;
The general rules for naming variables are:

Names can contain letters, digits and underscores


Names must begin with a letter or an underscore (_)
Names are case-sensitive (myVar and myvar are different variables)
Names cannot contain whitespaces or special characters like !, #, %, etc.
Reserved words (like C++ keywords, such as int) cannot be used as names

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

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

const int myNum = 15; // myNum will always be 15


myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are
unlikely to change:

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:

const int minutesPerHour = 60;


This however, will not work:

const int minutesPerHour;


minutesPerHour = 60; // error
C++ User Input
You have already learned that cout is used to output (print) values. Now we will use cin
to get user input.

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;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

Creating a Simple Calculator


In this example, the user must input two numbers. Then we print the sum by calculating
(adding) the two numbers:

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!

Complete <iostream> Reference


Tip: Both cin and cout belongs to the <iostream> library, which is short for standard
input / output streams.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Familiarization with Constants, Variables, Keywords and Data types (int, float, char) and
using the Input & Output Functions

Constants: Constant is an entity that does not change.

Variables: An entity that may vary during program execution.

Keyword: A predefined word that cannot be used as a variable name. Also


called “Reserved Words”.

Character Set of C: It is a Combination of Alphabets, Digits, and Special


Symbols to form Constants, Variables and Keywords.

Data Types:

Type of Data that can be declared in C is as follow:

Character Character data Char


Integer Signed whole number int
Float Floating point number Float
Void Valueless Void
Double Double precision floating double
number

Variable Declaration:

Variables are generally declared as:

TYPE VAR-NAME;

Here ‘Type” is C data type and ‘var-name’ is the variable name.

You can also declare more than one variables of same type by using comma-separated
list. For example
int a,b,c ;

Value Assignment to the Variable:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

A programmer can assign unique value to the variable. The general form of an
assignment statement is

Variable name = value;


For Example
a=10;

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:

cin>> variable name


Let variable name is ‘a’
cin>>a;

(The entered value is saved with reference of variable ‘a’)

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

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Exercise:

1. Write the above example and observe the output.

2. Write a program in C++ to show the data types:

Lab# 03

Objective:

Identify with the different types of Operators, Expressions and the Formula Evaluation in
C+ +

Arithmetic Operator and Expression:

An expression is a combination of operators and operands to make programming easier


and efficient. C expression follows the rules of algebra. C describes the following
arithmetic operators:

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

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

cout << " Post increment operator" <<endl;


cout << " Value of x= " << x << endl;
cout << " Value of y= " << y << endl;
int a = 15;
int b = ++a;
cout << " Pre increment operator" << endl;
cout << " Value of a= " << a << endl;
cout << " Value of b= " << b << endl;
return 0 ;
}

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

Post decrement operator

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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 +, –, *, /, %

Operator Precedence: In an expression order of precedence of arithmetic operators must


be known. The *, / and % operator are higher precedence than the + and – 00001

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 & Expressions:

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.

Commonly used Relational operators are:

> greater than


< lesser than
>= greater than or equal to
<= less than or equal to
== is equal to
!= is not equal to

Logical Operators

Commonly used Logical operators are:

&& (Logical AND), | | (Logical OR), (Logical NOT)

Example:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

Max and min


The max(x,y) function can be used to find the highest value of x and y:

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

C++ <cmath> Library

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>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);
Department of Computer Science,
Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Arithmetic Functions:

Example:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

1. Write a program in c++ to calculate perimeter & area:


2. Write a program in c++ to calculate the total marks and percentage of 5 subjects.
the marks of the subjects are taken through input:
3. Write a C++ program to compute the quotient and remainder.
Sample Output:
Compute quotient and remainder :
-------------------------------------
Input the dividend : 25
Input the divisor : 3
The quotient of the division is : 8
The remainder of the division is : 1
4. Using ternary operator to find if a person can vote or not
5. Write a C++ program that takes two integers as input from the user and prints the
greater number using the ternary operator.
6. Write a C++ program that checks whether a number is positive, negative, or zero
using the ternary operator.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Lab# 05

Objective:

Studying conditional statement –if and studying various variations of If statement and
difference b/w them

The if else Statement:

This is used to decide whether to do something at a special point, or to decide between


two courses of action. The following test decides whether a student has passed an exam
with a pass mark of 50.

if (result >= 50)


cout<<"Pass";
else
cout<<"Fail";
It is possible to use the if part without the else.
if (temperature < 0)
cout<<"Frozen";

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 (result >= 50)


{
cout<<“Passed";
cout<<"Congratulations ";
}
else
{
cout<<"Failed";
cout<<"Better luck next time";
}
Multiple if statements:
Department of Computer Science,
Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Consider the following example

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:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

1. Write a program to check number is Negative or Positive:

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:

Understand and using the Switch case and Conditional Operator

The switch Statement

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)

cout <<"Your average must be below 60");


}

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

case 'b': case 'B': ...


etc.
The break statement also works loops; it causes an immediate exit from the loop.

Conditional operator ( ? )

Its format is as:


condition ? result1 : result2

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:

7= =5 ? 4 : 3 // returns 3, since 7 is not equal to 5.


7= =5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
Example:
#include <iostream>
using namespace std;
int main() {
int a,b,c;

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:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Month Days Calculator


 Objective: Create a program that takes the month number (1-12) as input and
outputs the number of days in that month.
 Conditions:
o January, March, May, July, August, October, December: 31 days
o April, June, September, November: 30 days
o February: 28 or 29 days (assume 28 for simplicity in this task)

1) Write a program to determine the number is odd or even:


2) Write a c++ program to print first 20 odd numbers.

LAB# 07
Objective:

Understand the concept and functionality of “for loop”

The For Loop:

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)

Having the following format,

for (<initialization>; <continuation(Test)>; <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.

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

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

for(i = 0; i < 102; i = i + 5)

{
cout<<”value of i =”<<i;

getche ( );

Exercise:

1. Write a program to display sum of digits of the number given by user:

2. Write a c++ program to print first 20 even numbers using loop:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Lab# 08
Objective:

Understanding ‘While Loop’ structure:

The while Loop:

‘While loop’ structure is same as the ‘for loop’ and simple but it is distributed throughout
the program. It has the general form as:

while (test expression)


{
Statements;
Or multiple statements;
}
The value of the testing variable is checked at the start of the loop but all the variations
like increment, decrement, comparison etc are done with in the statements in body of the
loop.

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;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

cout<<“type a phrase…”;
while(getche() != ‘\r’)
{
count++;
}
Cout<<“\n character count is”<<count;
}

Exercise:

1. Observe the output of the above program.

2. Write a program to calculate average of numbers.

LAB# 09
Objective:

Familiarize & Understand “do while” Loop

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.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

LAB# 10
Objective:

To familiarize and understand Arrays

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

Element 1 Element 2 Element 3 Element 4 Element 5


Index # 0 Index # 1 Index # 2 Index # 3 Index # 4

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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)

int results_3d[20][5][3]; (Three Dimensional Arrays)

Arrays & For Loop:

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

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

array[i] = 0;

Limitations- handling with arrays:

C/ C++ do not tell if you try to write to elements of an array which do not exist.
For example:

char array[5]; (is an array with 5 elements)


array[7] = '*';

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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.

1. Write a c++ program to display sum and average of array


2. elements using for loop and write program to take input of 1d & 2d array
elements and display those elements:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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.

Structure of the Function

There are three basic elements of a function. These elements are:

1. Function Declaration
2. Function Definition
3. Function Call

Function Declaration

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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.

Example 01: Print 1 2 3 by functions.

#include <iostream>
using namespace std;
func1( ); // function declaration ( user defined function)
func2( ); // function declaration ( user defined function)

int main() {

func2 ( ); // function call and control is transfer to func2 (step 1)


cout<<”3”; // print 3 (step 5)
getche( );
}
func2( ) // function definition
{
func1 ( ); // function call and control is transfer to func1 (step 2)
cout<<”2”; // print 2 and control is back to where the function1 is called (step 4)
}
func1( )
{
cout<<“1”; // print 1 and control is back to where the function1 is called (step 3)
}

Function with return ( ) statement

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.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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.

Limitation of return ( ) statement

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.

Example 02: (Value passes and returns to functions)

Add two numbers by functions

#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++:

2. Write a c++ program to make calculator using functions:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

3. Write a program that overloads a function calculateArea() to calculate the area


of:
1. A rectangle.
2. A circle.
3. A triangle.

Instructions:

1. Define a function calculateArea():


o For a rectangle, take two arguments (length and width).
o For a circle, take one argument (radius).
o For a triangle, take two arguments (base and height).
2. Test your function with appropriate inputs for each shape.

Task 2: Function Overloading with Default Arguments

Problem Statement: Write a program to overload a function displayMessage():

1. One version should take no arguments and print a default message.


2. Another version should take one argument (a string) and display it.
3. A third version should take two arguments (a string and an integer) and display
them.

Instructions:

 Call all three versions of the function from main().

Task 3: Variable Scope Demonstration

Problem Statement: Write a program to demonstrate the difference between global,


local.

Instructions:

1. Declare a global variable count and initialize it to 10.


2. Define a function incrementCounter():
o Use a local variable count.
o Print the local after incrementing them.
3. Call incrementCounter() multiple times and observe the behavior.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Task 4: Combining Overloading and Scope

Problem Statement: Write a program that overloads a function sumValues():

1. One version adds two integers.


2. Another version adds two floating-point numbers.
3. A third version adds three integers and utilizes a global variable in the calculation.

Instructions:

1. Define a global variable extra = 5.


2. Ensure the third version of sumValues() adds the global variable to the sum of
three integers.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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 (C-style Strings)

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

How to define a C-string?

char str[] = "C++";

In the above code, str is a string and it holds 4 characters.

Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.

Alternative ways of defining a string

char str[4] = "C++";

char str[] = {'C','+','+','\0'};

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String to read a word

C++ program to display a string entered by user.

#include <iostream>

using namespace std;

int main()

char str[100];

cout << "Enter a string: ";

cin >> str;

cout << "You entered: " << str << endl;

cout << "\nEnter another string: ";

cin >> str;

cout << "You entered: "<<str<<endl;

return 0;

Output

Enter a string: C++

You entered: C++

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Enter another string: Programming is fun.

You entered: Programming

Notice that, in the second example only "Programming" is displayed instead of


"Programming is fun".

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.

Example 3: C++ string using string data type

#include <iostream>

using namespace std;

int main()

// Declaring a string object

string str;

cout << "Enter a string: ";

getline(cin, str);

cout << "You entered: " << str << endl;

return 0;

Output

Enter a string: Programming is fun.

You entered: Programming is fun.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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:

1. C++ program to read and display an entire line entered by user.

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.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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

Structure is a collection of variables of different data types under a single name. It is


similar to a class in that, both holds a collection of data of different data types.

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.

How to declare a structure in C++ programming?

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;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

};

Here a structure person is defined which has three members: name, age and salary.

When a structure is created, no memory is allocated.

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.

Note: Remember to end the declaration with a semicolon (;)

How to define a structure variable?

Once you declare a structure person as above. You can define a structure variable as:

Person bill;

Here, a structure variable bill is defined which is of type structure Person.

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.

Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.

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;

Example: C++ Structure

C++ Program to assign data to members of a structure variable and display it.

#include <iostream>

using namespace std;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

struct Person

char name[50];

int age;

float salary;

};

int main()

Person p1;

cout << "Enter Full name: ";

cin.get(p1.name, 50);

cout << "Enter age: ";

cin >> p1.age;

cout << "Enter salary: ";

cin >> p1.salary;

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

cout << "Name: " << p1.name << endl;

cout <<"Age: " << p1.age << endl;

cout << "Salary: " << p1.salary;

return 0;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Output

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

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

1) WRITE A PROGRAM TO ASSIGN DATA TO MEMBERS (NAME, AGE,


SALARY, QUALIFICATION) OF A STRUCTURE AND DISPLAY IT IN C++:

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

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,

Example 1: Printing Variable Addresses in C++

#include <iostream>

using namespace std;

int main()

// declare variables

int var1 = 3;

int var2 = 24;

int var3 = 17;

// print address of var1

cout << "Address of var1: "<< &var1 << endl;

// print address of var2

cout << "Address of var2: " << &var2 << endl;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

// print address of var3

cout << "Address of var3: " << &var3 << endl;

Output

Address of var1: 0x7fff5fbff8ac

Address of var2: 0x7fff5fbff8a8

Address of var3: 0x7fff5fbff8a4

Here, 0x at the beginning represents the address is in the hexadecimal form.

Notice that the first address differs from the second by 4 bytes and the second address
differs from the third by 4 bytes.

This is because the size of an int variable is 4 bytes in a 64-bit system.

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.

Here is how we can declare pointers.

int *pointVar;

Here, we have declared a pointer pointVar of the int type.

We can also declare pointers in the following way.

int* pointVar; // preferred syntax

Let's take another example of declaring pointers.

int* pointVar, p;

Here, we have declared a pointer pointVar and a normal variable p.

Note: The * operator is used after the data type to declare pointers.

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Assigning Addresses to Pointers

Here is how we can assign addresses to pointers:

int* pointVar, var;

var = 5;

// assign address of var to pointVar pointer

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.

Get the Value from the Address Using Pointers?

To get the value pointed by a pointer, we use the * operator. For example:

int* pointVar, var;

var = 5;

// assign address of var to pointVar

pointVar = &var;

// access value pointed by pointVar

cout << *pointVar << endl; // Output: 5

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.

Note: In C++, pointVar and *pointVar is completely different. We cannot do something


like *pointVar = &var;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Example 2: Working of C++ Pointers

#include <iostream>

using namespace std;

int main() {

int var = 5;

// declare pointer variable

int* pointVar;

// store address of var

pointVar = &var;

// print value of var

cout << "var = " << var << endl;

// print address of var

cout << "Address of var (&var) = " << &var << endl

<< endl;

// print pointer pointVar

cout << "pointVar = " << pointVar << endl;

// print the content of the address pointVar points to

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

Address of var (&var) = 0x61ff08

pointVar = 0x61ff08

Content of the address pointed to by pointVar (*pointVar) = 5

Changing Value Pointed by Pointers

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;

// assign address of var

pointVar = &var;

// change value at address pointVar

*pointVar = 1;

cout << var << endl; // Output: 1

Here, pointVar and &var have the same address, the value of var will also be changed
when *pointVar is changed.

Example 3: Changing Value Pointed by Pointers

#include <iostream>

using namespace std;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

int main() {

int var = 5;

int* pointVar;

// store address of var

pointVar = &var;

// print var

cout << "var = " << var << endl;

// print *pointVar

cout << "*pointVar = " << *pointVar << endl

<< endl;

cout << "Changing value of var to 7:" << endl;

// change value of var to 7

var = 7;

// print var

cout << "var = " << var << endl;

// print *pointVar

cout << "*pointVar = " << *pointVar << endl

<< endl;

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

cout << "Changing value of *pointVar to 16:" << endl;

// change value of var to 16

*pointVar = 16;

// print var

cout << "var = " << var << endl;

// print *pointVar

cout << "*pointVar = " << *pointVar << endl;

return 0;

Output

var = 5

*pointVar = 5

Changing value of var to 7:

var = 7

*pointVar = 7

Changing value of *pointVar to 16:

var = 16

*pointVar = 16

Common mistakes when working with pointers

Department of Computer Science,


Dawood University of Engineering & Technology
Prepared by: Mr. Irfan Ahmed (Lecturer)

Suppose, we want a pointer varPoint to point to the address of var. Then,

int var, *varPoint;

// Wrong!

// varPoint is an address but var is not

varPoint = var;

// Wrong!

// &var is an address

// *varPoint is the value stored in &var

*varPoint = &var;

// Correct!

// varPoint is an address and so is &var

varPoint = &var;

// Correct!

// both *varPoint and var are values

*varPoint = var;

Exercise

1. C++ Program to display address of each element of an array

Department of Computer Science,


Dawood University of Engineering & Technology

You might also like