0% found this document useful (0 votes)
3 views

Lab Manual Programming Fundamental

The document is a lab manual for Programming Fundamentals, detailing a 16-week curriculum covering topics such as installation of IDEs, C++ programming concepts, algorithms, data types, control structures, functions, memory management, and file handling. Each week includes specific lessons, examples, and practice questions designed to enhance understanding of programming in C++. The manual is structured to guide students from basic programming concepts to more advanced topics in C++.

Uploaded by

aroojsagir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab Manual Programming Fundamental

The document is a lab manual for Programming Fundamentals, detailing a 16-week curriculum covering topics such as installation of IDEs, C++ programming concepts, algorithms, data types, control structures, functions, memory management, and file handling. Each week includes specific lessons, examples, and practice questions designed to enhance understanding of programming in C++. The manual is structured to guide students from basic programming concepts to more advanced topics in C++.

Uploaded by

aroojsagir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 152

Lab

Manual
Programming Fundamental

Ms Memuna
Kauser
GSCWU BWP
Lab Manual
Contents
Week 01: Installation & overview................................................................................................................6
What is programming?............................................................................................................................6
What is computer language?...................................................................................................................6
Installation Of IDE.....................................................................................................................................7
Download and Install Code Blocks C & C++ IDE on Windows 10.............................................................7
How to install Code Blocks......................................................................................................................7
Installation Steps.....................................................................................................................................8
C++ Introduction.....................................................................................................................................15
Week 02: Introduction to problem solving & variables & Keywords.........................................................17
Introduction to Algorithm......................................................................................................................17
C++ Variables, Literals and Constants....................................................................................................18
C++ Variables.........................................................................................................................................18
C++ Literals............................................................................................................................................19
C++ Constants........................................................................................................................................21
Week 03: Data Types & Comments...........................................................................................................22
C++ Data Types......................................................................................................................................22
C++ Type Modifiers................................................................................................................................24
C++ Comments......................................................................................................................................25
Week 04: Basic Structure of program &Working of program....................................................................26
Structure of a Program/Syntax..............................................................................................................26
How does Program work.......................................................................................................................27
C++ Basic Input/Output.........................................................................................................................28
Example for C++ Output........................................................................................................................29
Example for C++ Input...........................................................................................................................30
Examples................................................................................................................................................31

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 2


Practice Questions.................................................................................................................................32
Week 05: Operators & Directives..............................................................................................................32
Operators in C++....................................................................................................................................32
Relational Operator...............................................................................................................................33
Logical Operator....................................................................................................................................34
Increment and Decrement Operators...................................................................................................35
Practice Questions With Solution..........................................................................................................36
Practice Question Home Task................................................................................................................39
Week 06: Flow Control.............................................................................................................................40
Decisions................................................................................................................................................40
Forms of if-else statement in C++..........................................................................................................40
C++ if Statement................................................................................................................................40
C++ if...else Statement......................................................................................................................41
C++ if...else...else if statement...........................................................................................................43
C++ Nested if...else............................................................................................................................44
Practice Questions.................................................................................................................................46
Practice Question If-Else........................................................................................................................46
Week 07: Loops........................................................................................................................................48
Introduction to Loops............................................................................................................................48
For Loop.................................................................................................................................................48
While Loops...........................................................................................................................................49
Do-While Loop.......................................................................................................................................50
Examples:..............................................................................................................................................51
Practice Question..................................................................................................................................56
Week 08: Break &Continue & Switch Statement & GOTO Statement.......................................................56
C++ break Statement.............................................................................................................................56
C++ continue Statement........................................................................................................................57
C++ Switch..Case Statement..................................................................................................................58
GOTO Statement...................................................................................................................................61
Week 09: C++ Functions............................................................................................................................63
Functions...............................................................................................................................................63
Types of function...................................................................................................................................63

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 3


C++ User-defined Function....................................................................................................................63
C++ Function Declaration...................................................................................................................64
Calling a Function..................................................................................................................................64
Examples................................................................................................................................................65
Function Parameters.............................................................................................................................66
Return Statement..................................................................................................................................67
Function Prototype................................................................................................................................69
Benefits of Using User-Defined Functions.............................................................................................71
C++ Library Functions............................................................................................................................71
Week 10: C++ User define Function Types & Overloading........................................................................72
User-defined Function Types.................................................................................................................72
Examples:..............................................................................................................................................73
Which method is better?.......................................................................................................................77
Overloading...........................................................................................................................................77
C++ Function Overloading..................................................................................................................77
Examples:..............................................................................................................................................78
Week 11: C++Default Arguments, Storage Class and Recursion................................................................81
C++ Programming Default Arguments (Parameters).............................................................................81
Example: Default Argument...............................................................................................................83
C++ Storage Class...................................................................................................................................86
Local Variable........................................................................................................................................86
Example 1: Local variable...................................................................................................................86
Global Variable......................................................................................................................................87
Example 2: Global variable................................................................................................................87
Static Local variable...............................................................................................................................88
Example 3: Static local variable..........................................................................................................89
C++ Recursion........................................................................................................................................90
Week 12: C++ Return Reference, Strings...................................................................................................94
C++ Return by Reference.......................................................................................................................94
Example: Return by Reference..............................................................................................................94
C++ Strings.............................................................................................................................................95
C - Strings...............................................................................................................................................95

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 4


String Object..........................................................................................................................................97
Passing String to a Function...................................................................................................................98
C++ Stack...............................................................................................................................................99
Create a Stack........................................................................................................................................100
Example: C++ STL Stack..................................................................................................................100
Stack Methods........................................................................................................................................101
Week 13: Arrays, Multidimensional array, Function and array...............................................................109
C++ Arrays...........................................................................................................................................109
C++ Array Declaration......................................................................................................................109
Access Elements in C++ Array..........................................................................................................109
C++ Array Initialization.....................................................................................................................110
C++ Array With Empty Members.....................................................................................................110
Examples.............................................................................................................................................112
C++ Multidimensional Arrays...............................................................................................................115
Multidimensional Array Initialization...................................................................................................116
Example...............................................................................................................................................117
Example 3: Three Dimensional Array...................................................................119
Passing Array to a Function in C++ Programming................................................................................121
Examples.............................................................................................................................................121
Week 14: Pointers, Pointers and arrays, Pointer and function................................................................124
C++ Pointers........................................................................................................................................124
Address in C++.................................................................................................................................124
Assigning Addresses to Pointers......................................................................................................126
C++ Pointers and Arrays......................................................................................................................129
Example 1: C++ Pointers and Arrays....................................................................................................131
C++ Call by Reference: Using pointers.................................................................................................132
Week 15: Memory Management and File...............................................................................................136
C++ Memory Management: new and delete.......................................................................................136
C++ new Operator...............................................................................................................................136
Delete Operator...................................................................................................................................137
Examples:............................................................................................................................................138
C++ File Handling.....................................................................................................................................140

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 5


Read From a File................................................................................................................................143
Write to a File....................................................................................................................................145
Append to a Text File........................................................................................................................147
File Handling With fstream...............................................................................................................149
Week 16 : Revision, Presentation and Quiz.............................................................................................151

Week 01: Installation & overview


What is programming?
Programming is the process of creating sets of instructions that tell a computer what to do.

It involves writing code in a programming language to solve problems or automate tasks.

Key Elements of Programming

● Instructions: Creating step-by-step instructions to guide the computer's actions.


● Language: Using a programming language to communicate with the computer.
● Problem Solving: Analyzing problems and designing solutions using logical thinking.

Programming Languages

Definition: Programming languages are formal languages designed to communicate instructions


to a computer.

Examples: Python, Java, C++, Kotlin

What is computer language?


The computer language is defined as code or syntax which is used to write programs.

Low level language

• Machine Language
• Assembly Language

High Level Language

• C, C++, java, C# etc


Language processors:

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 6


• Assembler
• Compiler
• Interpreter

Assembler converts program written in assembly language into machine language.

Compilers and interpreters are program that help convert the high-level language into machine
code.

Compiler Vs Interpreter

• Compiler convert the whole high level language program to machine language at a time
while

• Interpreter converts high level language program to machine language line by line.

C++ Compiler:

• GCC stands for GNU Compilers Collections is used to compile mainly C and C++
language.

Installation Of IDE
Download and Install Code Blocks C & C++ IDE on Windows 10
Code Blocks is a free and cross platform IDE for C, C++, and Fortran. Here is the list of features
available in Code Blocks IDE –

How to install Code Blocks


Download the latest version of Code Blocks for your Operating System from
here http://www.codeblocks.org/downloads
'OR' You can also download the latest version for Windows directly from the following
download button if the above method doesn't work -
DOWNLOAD CODE BLOCKS

Run the downloaded .exe file to install Code Blocks in your system.

Follow the setup instructions.

You can watch the following video to check how to download and install Code Blocks IDE for
Windows –

https://www.youtube.com/watch?v=eXx2bmHm7ZQ

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 7


Installation Steps

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 8


Lab Manual Programming Fundamental By Ms Sidra Khalid Page 9
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 10
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 11
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 12
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 13
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 14
C++ Introduction

What is C++?

C++ is a cross-platform language that can be used to create high-performance applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and memory.

The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C+
+17, C++20.

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.

C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.

C++ is fun and easy to learn!

As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice
versa.

Difference between C and C++


C++ was developed as an extension of C, and both languages have almost the same syntax.

The main difference between C and C++ is that C++ support classes and objects, while C does
not.

C++ Quickstart
Let's create our first C++ file.

Open Codeblocks and go to File > New > Empty File.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 15


Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):

myfirstprogram.cpp

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Don't worry if you don't understand the code above - we will discuss it in detail in later
chapters. For now, focus on how to run the code.

In Codeblocks, it should look like this:

Then, go to Build > Build and Run to run (execute) the program. The result will look something
to this:

Output:

Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.

Congratulations! You have now written and executed your first C++ program.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 16


Week 02: Introduction to problem solving &
variables & Keywords
Introduction to Algorithm
• Algorithm:- It is a method of representing the step by step process for solving a
problem. Each step is called an instruction.

What are the Characteristics of an Algorithm?

Example 01

Write a C++ algorithm to write a program to add two numbers.

Algorithm Steps are given below:

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 17


Start

Accept num1, num 2

Sum= num1+ num2

Display sum

Stop

Example 02

C++ Variables, Literals and Constants

C++ Variables
In programming, a variable is a container (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier). For
example,

int age = 14;

Here, age is a variable of the int data type, and we have assigned an integer value 14 to it.

Note: The int data type suggests that the variable can only hold integers. Similarly, we can use
the double data type if we have to store decimals and exponentials.

We will learn about all the data types in detail in the next tutorial.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 18


The value of a variable can be changed, hence the name variable.

int age = 14; // age is 14

age = 17; // age is 17

Rules for naming a variable

 A variable name can only have alphabets, numbers, and the underscore _.

 A variable name cannot begin with a number.

 It is a preferred practice to begin variable names with a lowercase character. For


example, name is preferable to Name.

 A variable name cannot be a keyword. For example, int is a keyword that is used to
denote integers.

 A variable name can start with an underscore. However, it's not considered a good
practice.

Note: We should try to give meaningful names to variables. For example, first_name is a better
variable name than fn.

C++ Literals
Literals are data used for representing fixed values. They can be used directly in the code. For
example: 1, 2.5, 'c' etc.

Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these terms.

Here's a list of different literals in C++ programming.

1. Integers
An integer is a numeric literal(associated with numbers) without any fractional or exponential
part. There are three types of integer literals in C programming:

 decimal (base 10)

 octal (base 8)

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 19


 hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C++ programming, octal starts with a 0, and hexadecimal starts with a 0x.

2. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponent form.
For example:

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5

3. Characters
A character literal is created by enclosing a single character inside single quotation marks. For
example: 'a', 'm', 'F', '2', '}' etc.

4. Escape Sequences
Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C++
programming. For example, newline (enter), tab, question mark, etc.

In order to use these characters, escape sequences are used.

Escape Sequences Characters


\b Backspace

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 20


\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null Character

5. String Literals

"good" string constant


"" null string constant
"" string constant of six white space
"x" string constant having a single character
"Earth is round\n" prints string with a newline
A string literal is a sequence of characters enclosed in double-quote marks. For example:

C++ Constants
In C++, we can create variables whose value cannot be changed. For that, we use
the const keyword. Here's an example:

const int LIGHT_SPEED = 299792458;

LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.

Here, we have used the keyword const to declare a constant named LIGHT_SPEED. If we try to
change the value of LIGHT_SPEED, we will get an error.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 21


A constant can also be created using the #define preprocessor directive. We will learn about it
in detail in the C++ Macros tutorial.

Week 03: Data Types & Comments


C++ Data Types
In C++, data types are declarations for variables. This determines the type and size of data
associated with variables. For example,

int age = 13;

Here, age is a variable of type int. Meaning, the variable can only store integers of either 2 or 4
bytes.

C++ Fundamental Data Types

The table below shows the fundamental data types, their meaning, and their sizes (in bytes):

Data Type Meaning Size (in Bytes)


Int Integer 2 or 4
Float Floating-point 4
Double Double Floating-point 8
char Character 1
wchar_t Wide Character 2
bool Boolean 1
void Empty 0
Now, let us discuss these fundamental data types in more detail.

1. C++ int

 The int keyword is used to indicate integers.

 Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to
2147483647.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 22


 For example,

int salary = 85000;

2. C++ float and double

 float and double are used to store floating-point numbers (decimals and exponentials).

 The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times
the precision of float. To learn more, visit C++ float and double.

 For example,

float area = 64.74;

double volume = 134.64534;

As mentioned above, these two data types are also used for exponentials. For example,

double distance = 45E12 // 45E12 is equal to 45*10^12

3. C++ char

 Keyword char is used for characters.

 Its size is 1 byte.

 Characters in C++ are enclosed inside single quotes ' '.

 For example,

char test = 'h';

4. C++ wchar_t

 Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead
of 1.

 It is used to represent characters that require more memory to represent them than
a single char.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 23


 For example,

wchar_t test = L'‫ 'ם‬// storing Hebrew character;

Notice the letter L before the quotation marks.

5. C++ bool

 The bool data type has one of two possible values: true or false.

 Booleans are used in conditional statements and loops (which we will learn in later
chapters).

 For example,

bool cond = false;

6. C++ void

 The void keyword indicates an absence of data. It means "nothing" or "no value".

 We will use void when we learn about functions and pointers.

Note: We cannot declare variables of the void type.

C++ Type Modifiers


We can further modify some of the fundamental data types by using type modifiers. There are
4 type modifiers in C++. They are:

1. signed

2. unsigned

3. short

4. long

We can modify the following data types with the above modifiers:

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 24


 int

 double

 char

C++ Modified Data Types List

Data Type Size (in Meaning


Bytes)
signed int 4 used for integers (equivalent to int)

unsigned int 4 can only store positive integers

Short 2 used for small integers (range -32768 to 32767)

unsigned short 2 used for small positive integers (range 0 to 65,535)

Long at least 4 used for large integers (equivalent to long int)

unsigned long 4 used for large positive integers or 0 (equivalent to unsigned long int)

long long 8 used for very large integers (equivalent to long long int).

unsigned long 8 used for very large positive integers or 0 (equivalent to unsigned long
long long int)
long double 12 used for large floating-point numbers

signed char 1 used for characters (guaranteed range -127 to 127)


unsigned char 1 used for characters (range 0 to 255)
Let's see a few examples.

long b = 4523232;

long int c = 2345342;

long double d = 233434.56343;

short d = 3434233; // Error! out of range

unsigned int a = -5; // Error! can only store positive numbers or 0

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

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 25


be singled-lined or multi-lined.

Single-line Comments

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!";

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!";

Week 04: Basic Structure of program


&Working of program
Structure of a Program/Syntax
Let us look at a simple code that would print the words Hello World.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 26


#include<iostream>

using namespace std;

int main()

cout << "Hello World"; // prints Hello World return 0;

How does Program work

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 27


C++ Basic Input/Output
C++ Output

 In C++, cout sends formatted output to standard output devices, such as


the screen. We use the cout object along with the << operator for
displaying output.

Example 1: String Output

#include <iostream>

using namespace std;

int main()

// prints the string enclosed in double quotes


Lab Manual Programming Fundamental By Ms Sidra Khalid Page 28
cout << "This is C++ Programming";

return 0;

Output: This is C++ Programming

How this Program works

 We first include the iostream header file that allows us to display


output.
 The cout object is defined inside the std namespace. To use the std
namespace, we used the using namespace std; statement.
 Every C++ program starts with the main() function. The code execution
begins from the start of the main() function.
 cout is an object that prints the string inside quotation marks " ". It is
followed by the << operator.
 return 0; is the "exit status" of the main() function. The program ends
with this statement, however, this statement is not mandatory

Note: If we don't include the using namespace std; statement, we need to use
std::cout instead of cout.

Example for C++ Output


// C++ program to illustrate the use of cout object

#include <iostream>
using namespace std;

// main Code
int main()
{
// Print standard output
// on the screen
cout << "Welcome to C++ Programming";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 29


return 0;
}
C++ Basic Input/Output
C++ Input
In C++, cin takes formatted input from standard input devices such as the
keyboard. We use the cin object along with the >> operator for taking input.
Example 3: Integer Input/Output
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}
Output
Enter an integer: 70
The number is: 70
In the program, we used
cin >> num;
To take input from the user. The input is stored in the variable num.
We use the >> operator with cin to take input.
Note: If we don't include the using namespace std; statement, we need to use
std::cin instead of cin.

Example for C++ Input


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

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 30


cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output
Enter your age: 18
Your age is: 18

Examples
1. Write a program that print your name?

// C++ program to print name

// as output

#include <iostream>

using namespace std;

int main()

cout << "My Name is Sidra:";

return 0;

2. Write a program that print your roll no, name ,class and age?

#include <iostream>

using namespace std;

int main() {

int rollNo = 12345;

string name = "John";

string className = "Class 10";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 31


int age = 16;

cout << "Roll No: " << rollNo << endl;

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

cout << "Class: " << className << endl;

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

return 0;

Practice Questions
1. Write a program that print pakistan?

2. Write a program that print your city?

3. Write a program that input two number add this number?

4. Write a program that input three numbers add this number?

Week 05: Operators & Directives


Operators in C++

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 32


Example
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;
// printing the division of a by b
cout << "a / b = " << (a / b) << endl;
// printing the modulo of a by b
cout << "a % b = " << (a % b) << endl;
return 0;
}

Relational Operator

Example:
Lab Manual Programming Fundamental By Ms Sidra Khalid Page 33
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 5;
bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;
result = (a != b); // true
cout << "3 != 5 is " << result << endl;
result = a > b; // false
cout << "3 > 5 is " << result << endl;
result = a < b; // true
cout << "3 < 5 is " << result << endl;
result = a >= b; // false
cout << "3 >= 5 is " << result << endl;
result = a <= b; // true
cout << "3 <= 5 is " << result << endl;
return 0;
}

Logical Operator

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 34


Example:
#include <iostream>

using namespace std;

int main() {

bool result;

result = (3 != 5) && (3 < 5); // true

cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false

cout << "(3 == 5) && (3 < 5) is " << result <<

endl; result = (3 == 5) && (3 > 5); // false

cout << "(3 == 5) && (3 > 5) is " << result <<

endl; result = (3 != 5) || (3 < 5); // true

cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true

cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false

cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true

cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false

cout << "!(5 == 5) is " << result << endl;

return 0;

Increment and Decrement Operators


 C++ also provides increment and decrement operators: ++ and -- respectively.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 35


 ++ increases the value of the operand by 1

 -- decreases it by 1

For example,

int num = 5;

// increment operator

++num; // 6

Here, the code ++num; increases the value of num by 1.

Example Increment/Decrement Operator


// Working of increment and decrement operators

#include <iostream>

using namespace std;

int main()

int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a

result_a = ++a;

cout << "result_a = " << result_a << endl;

// decrementing b by 1 and storing the result in result_b

result_b = --b;

cout << "result_b = " << result_b << endl;

return 0;

Practice Questions With Solution


1. Write a Program to Print Number Entered by User?

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 36


2. Write a Program to Add Two Float Numbers?

3. Write a Program to Find Quotient and Remainder?

4. Write a Program to Find Size of int, float, double and char in Your System?

5. Write a Program to Swap Two Numbers?

Solutions

1.
#include <iostream>

using namespace std;

int main()

int number;

cout << "Enter an integer: ";

cin >> number;

cout << "You entered " << number;

return 0;

2.
#include <iostream>

using namespace std;

int main() {

float first_number, second_number, sum;

cout << "Enter two float numbers: ";

cin >> first_number >> second_number;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 37


// sum of two numbers in stored in variable sumOfTwoNumbers

sum = first_number + second_number;

// prints sum

cout << first_number << " + " << second_number << " = " << sum;

return 0;

3.
#include <iostream>

using namespace std;

int main()

int divisor, dividend, quotient, remainder;

cout << "Enter dividend: ";

cin >> dividend;

cout << "Enter divisor: ";

cin >> divisor;

quotient = dividend / divisor;

remainder = dividend % divisor;

cout << "Quotient = " << quotient << endl;

cout << "Remainder = " << remainder;

return 0;

4.
#include <iostream>

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 38


using namespace std;

int main()

cout << "Size of char: " << sizeof(char) << " byte" << endl;

cout << "Size of int: " << sizeof(int) << " bytes" << endl;

cout << "Size of float: " << sizeof(float) << " bytes" << endl;

cout << "Size of double: " << sizeof(double) << " bytes" << endl;

return 0;

5.
#include <iostream>

using namespace std;

int main()

int a = 5, b = 10, temp;

cout << "Before swapping." << endl;

cout << "a = " << a << ", b = " << b <<

endl; temp = a; a = b; b = temp;

cout << "\nAfter swapping." << endl;

cout << "a = " << a << ", b = " << b <<

endl; return 0;

Practice Question Home Task

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 39


• Write a program to input the value of the radius of a circle from keyboard and then
calculate its perimeter and area.

• Enter two numbers from keyboard. Write a program to check if the two numbers are
equal.

• Write a program to enter the values of two variables 'a' and 'b' from keyboard and then
check if both the conditions 'a < 50' and 'a < b' are true.

Week 06: Flow Control


Decisions
C++ if, if...else and Nested if...else

• In computer programming, we use the if...else statement to run one block of code under certain
conditions and another block of code under different conditions.

• For example, assigning grades (A, B, C) based on marks obtained by a student.

• if the percentage is above 90, assign grade A

• if the percentage is above 75, assign grade B

• if the percentage is above 65, assign grade C

Forms of if-else statement in C++


C++ if Statement
The syntax of the if statement is:

if (condition)

// body of if statement

The if statement evaluates the condition inside the parentheses ( ).

If the condition evaluates to true, the code inside the body of if is executed.

If the condition evaluates to false, the code inside the body of if is skipped.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 40


Note: The code inside { } is the body of the if statement.

Example 1: C++ if Statement


// Program to print positive number entered by the user // If the user enters a negative
number, it is skipped
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}

C++ if...else Statement


The if statement can have an optional else clause. Its syntax is:

if (condition)
{
// block of code if condition is true
}
else
{

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 41


// block of code if condition is false
}
The if..else statement evaluates the condition inside the parenthesis.

If the condition evaluates true,

the code inside the body of if is executed

the code inside the body of else is skipped from execution

If the condition evaluates false,

the code inside the body of else is executed

the code inside the body of if is skipped from execution

Example 2: C++ if...else Statement

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 42


• In the above program, we have the condition number >= 0. If we enter the number
greater or equal to 0, then the condition evaluates true.

• Here, we enter 4. So, the condition is true. Hence, the statement inside the body of if is
executed.

C++ if...else...else if statement


• The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, we use
the if...else if...else statement.

• The syntax of the if...else if...else statement is:

Here,

If condition1 evaluates to true, the code block 1 is executed.

If condition1 evaluates to false, then condition2 is evaluated.

If condition2 is true, the code block 2 is executed.

If condition2 is false, the code block 3 is executed.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 43


Example 3: C++ if...else...else if
// Program to check whether an integer is positive, negative or zero
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if (number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
}
else if (number < 0) {
cout << "You entered a negative integer: " << number << endl;
}
else {
cout << "You entered 0." << endl;
}
cout << "This line is always printed.";
return 0;
}
• In this program, we take a number from the user. We then use the if...else
if...else ladder to check whether the number is positive, negative, or zero.
• If the number is greater than 0, the code inside the if block is executed. If the number is
less than 0, the code inside the else if block is executed. Otherwise, the code inside
the else block is executed.

C++ Nested if...else


• Sometimes, we need to use an if statement inside another if statement. This is known as
nested if statement.
• Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is
another, inner if statement. Its syntax is:
// outer if statement
if (condition1)
{
// statements

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 44


// inner if statement if (condition2)
{
// statements
}
}
Notes:
We can add else and else if statements to the inner if statement as required.
The inner if statement can also be inserted inside the outer else or else if statements (if they exist).
We can nest multiple layers of if statements.
Example 4: C++ Nested if
// C++ program to find if an integer is positive, negative or zero
// using nested if statements
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
// outer if condition
if (num != 0) {
// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}
cout << "This line is always printed." << endl;
return 0;
}
In the above example,
We take an integer as an input from the user and store it in the variable num.
We then use an if...else statement to check whether num is not equal to 0.
If true, then the inner if...else statement is executed.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 45


If false, the code inside the outer else condition is executed, which prints "The number is 0 and it is
neither positive nor negative."
The inner if...else statement checks whether the input number is positive i.e. if num is greater
than 0.
If true, then we print a statement saying that the number is positive.
If false, we print that the number is negative.
Note: As you can see, nested if...else makes your logic complicated. If possible, you should always
try to avoid nested if...else.

Practice Questions
1. write a program to Check Whether Number is Even or Odd

2. write a program to Check Whether a character is Vowel or Consonant.

3. write a program Find Largest Number Among Three Numbers.

4. Take input from user and Check the year is leap year or not using if else structure.

5. Program to Find All Roots of a Quadratic Equation

Hint:

For a quadratic equation ax2+bx+c = 0 (where a, b and c are coefficients), it's roots is given by
following the formula.

Practice Question If-Else


1. Take values of length and breadth of a rectangle from user and check if it is square or not.

#include <iostream>
using namespace std;
int main()
{
int length,breadth;
cout<<"Enter length"<<endl;
cin>>length;
cout<<"Enter breadth"<<endl;
cin>>breadth;
if(length==breadth)
{

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 46


cout<<"It is a square"<<endl;
}
else {
cout<<"It is a rectangle"<<endl;
}
return 0;
}
2. Take two int values from user and print greatest among them.

#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
if (num1 > num2)
{
cout << num1 << " is greater than " << num2 << endl;
}
else if (num1 == num2)
{
cout << "Both numbers are equal" << endl;
}
else
{
cout << num2 << " is greater than " << num1 << endl;
}
return 0;
}
3. 3. A shop will give discount of 10% if the cost of purchased quantity is more than 1000.
Ask user for quantity
Suppose, one unit will cost 100.
Judge and print total cost for user.
#include <iostream>
using namespace std;
int main()
{
int quantity,price;
cout << "Enter quantity" << endl;
cin >> quantity;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 47


price = quantity*100;
if (price>1000)
{
cout << "Total cost is " << price-(price*.1) << endl;
}
Else
{
cout << "Total cost is " << price << endl;
}
return 0;
}

Week 07: Loops


Introduction to Loops
• Loops are a powerful programming construct that allows us to execute a block of code
repeatedly until a certain condition is met. This can be useful for tasks such as iterating
over a list of items, performing a calculation multiple times, or waiting for a specific
event to occur.

There are three main types of loops in C++:

 For loops: For loops are used to iterate over a sequence of values, such as a list of
numbers or characters.

 While loops: While loops are used to execute a block of code repeatedly until a
condition is met.

 Do-while loops: Do-while loops are similar to while loops, but they always execute the
block of code at least once, even if the condition is not met.

For Loop
• For loops are the most common type of loop in C++. They are used to iterate over a
sequence of values, such as a list of numbers or characters. The syntax for a for loop is
as follows

for (initializer; condition; increment)

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 48


// loop body

• Initializer: The initializer is executed at the beginning of the loop. It is typically used to
initialize a loop variable.

• Condition: The condition is evaluated at the beginning of each iteration of the loop. If
the condition is true, the loop body is executed. If the condition is false, the loop
terminates.

• Increment: The increment is executed at the end of each iteration of the loop. It is
typically used to increment the loop variable.

Here is an example of a for loop:

#include<iostream>
Using namespace std;
int main()
{
int sum = 0;
for (int i = 0; i < 10; i++)
{
sum = sum+i;
}
cout << "The sum of the numbers from 0 to 9 is: " << sum << endl;
return 0;
}
Output:
The sum of the numbers from 0 to 9 is: 45

While Loops
• While loops are used to execute a block of code repeatedly until a condition is met. The syntax
for a while loop is as follows:

while (condition)

// loop body

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 49


The condition is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop
body is executed. If the condition is false, the loop terminates.

Here is an example of a while loop:

#include<iostream>
using namespace std;
int main() {
int i = 0;
while (i < 10)
{
cout << i << endl;
i++;
}
return 0;
}

Do-While Loop
• The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Syntax

do {
// code block to be executed
}
while (condition);

Example: Display Numbers from 1 to 5

#include <iostream>
using namespace std;
int main() {
int i = 1;
// do...while loop from 1 to 5
do {
cout << i << " ";
++i;
}
while (i <= 5);

return 0;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 50


}
Example: Sum of Positive Numbers Only
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);

// display the sum


cout << "\nThe sum is " << sum << endl;
return 0;
}

Examples:
 Print the numbers from 1 to 100, one per line. Using For Loop

#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
cout << i << endl;
}
return 0;
}
 Calculate the sum of the numbers from 1 to 100. Using for Loop

#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++)
{

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 51


sum = sum + i;
}
cout << "The sum of the numbers from 1 to 100 is: " << sum << endl;
return 0;
}
 Print the even numbers from 1 to 100, one per line. Using While Loop
#include <iostream>
using namespace std;
int main() {
int i = 2;
while (i <= 100) {
cout << i << endl;
i += 2;
}
return 0;
}
 Program to print one statement for n time using while loop
#include <iostream>
using namespace std;
int main()
{
int n, i = 1;
cout << "Enter number:" << endl;
cin >> n;
cout << endl;
while (i <= n)
{
cout << "Hello C++" << endl;
i++;
}
return 0;
}
 Write a program in C++ to check whether a number is prime or not.
#include <iostream>
using namespace std;
int main()
{
int num1, ctr = 0;
cout << "\n\n Check whether a number is prime or not:\n";
cout << " \n";
cout << " Input a number to check prime or not: ";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 52


cin>> num1;
for (int a = 1; a <= num1; a++)
{
if (num1 % a == 0)
{
ctr++;
}
}
if (ctr == 2)
{
cout << " The entered number is a prime number. \n";
}
else {
cout << " The number you entered is not a prime number. \n";
}
}

 Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.
#include <iostream>
using namespace std;
int main()
{
int num1, num2, gcd;
cout << "\n\n Find the Greatest Common Divisor of two numbers:\
n"; cout << " \n";
cout << " Input the first number: ";
cin >> num1;
cout << " Input the second number: ";
cin >> num2;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 53


for (int i = 1; i <= num1 && i <= num2; i++)
{
if (num1 % i == 0 && num2 % i == 0)
{
gcd = i;
}
}
cout << " The Greatest Common Divisor is: " << gcd << endl;
return 0;
}

 Write a program in C++ to find the sum of the digits of a given number.
#include <iostream>
using namespace std;
int main()
{
int num1, num2, r, sum=0;
cout << "\n\n Find the sum of digits of a given number:\n";
cout << " \n";
cout << " Input a number: ";
cin >> num1;
num2 = num1;
while (num1 > 0)
{
r = num1 % 10;
num1 = num1 / 10;
sum = sum + r;
}
cout << " The sum of digits of " << num2 << " is: " << sum << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 54


}


#include <iostream>
using namespace std;
int main()
{
int n = 5;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
cout << " ";
}
for (int k = 1; k <= 2 * i - 1; k++)
{
cout << “X";
}
cout << endl;
}
return 0;
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 55


Practice Question

Week 08: Break &Continue & Switch


Statement & GOTO Statement
C++ break Statement
• In C++, the break statement terminates the loop when it is encountered.

• The syntax of the break statement is:

break;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 56


Break with for loop
// program to print the value of i

#include <iostream>

using namespace std;

int main() {

for (int i = 1; i <= 5; i++) {

// break condition

if (i == 3) {

break;

cout << i << endl;

return 0;

C++ continue Statement


• In computer programming, the continue statement is used to skip the current iteration
of the loop and the control of the program goes to the next iteration.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 57


• The syntax of the continue statement is:

continue;

Continue with for loop

// program to print the value of i

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}

C++ Switch..Case Statement


• The switch statement allows us to execute a block of code among many alternatives.

• The syntax of the switch statement in C++ is:

switch (expression)
{
case constant1:
// code to be executed if

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 58


// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
Example: Create a Calculator using the switch Statement
// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 59


break;
}
return 0;
}

Example : A simple grade calculator


// C++ program to Find Grade of Student
#include<iostream>
using namespace std;
int main()
{
// variables
int score;
char grade;

// take score
cout << "Enter score(0-100): ";
cin >> score;

// check score is valid or not


// score is valid if it belongs to 0-100
if(score<0 || score>100)
{
cout << "Invalid Score" << endl;
return 0; // stop execution
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 60


// find grade using switch-case
switch(score/10)
{
case 10:
case 9:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
case 6:
grade = 'D';
break;
case 5:
grade = 'E';
break;
default:
grade = 'F';
}

// display grade
cout << "Grade = " << grade << endl;

return 0;
}
Output:-

Enter score(0-100): 92 Grade = A

Enter score(0-100): 50 Grade = E

GOTO Statement
In C++ programming, the goto statement is used for altering the normal sequence of program execution
by transferring control to some other part of the program.
Syntax of goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 61


statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is encountered, the control of program
jumps to label: and executes the code below it.

Example: goto Statement


// This program calculates the average of numbers entered by the user.
// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.

# include <iostream>
using namespace std;

int main()
{
float num, average, sum = 0.0;
int i, n;

cout << "Maximum number of inputs: ";


cin >> n;

for(i = 1; i <= n; ++i)


{
cout << "Enter n" << i << ": ";
cin >> num;

if(num < 0.0)


{
// Control of the program move to jump:
goto jump;
}
sum += num;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 62


}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95

Week 09: C++ Functions


Functions
A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:

1. a function to draw the circle


2. a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.

Types of function
There are two types of function:

1. Standard Library Functions: Predefined in C++

2. User-defined Function: Created by users

C++ User-defined Function


C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a
name (identifier).

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 63


When the function is invoked from any part of the program, it all executes the codes defined in
the body of the function.

C++ Function Declaration


The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {

// function body

Here's an example of a function declaration.

// function declaration

void greet() {

cout << "Hello World";

Here,

 the name of the function is greet()

 the return type of the function is void

 the empty parentheses mean it doesn't have any parameters

 the function body is written inside {}

Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function,
we need to call it.

Here's how we can call the above greet() function.

int main() {

// calling a function

greet();

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 64


Examples
Example 1: Display a Text
#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 65


Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function.

For example, let us consider the function below:

void printNum(int num) {

cout << num;

Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.

int main() {

int n = 7;

// calling the function

// n is passed to the function as argument

printNum(n);

return 0;

Example 2: Function with Parameters

// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}

int main() {

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 66


int num1 = 5;
double num2 = 5.5;

// calling the function


displayNum(num1, num2);

return 0;
}

In the above program, we have used a function that has one int parameter and
one double parameter.
We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.

Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.

Return Statement
In the above programs, we have used void in the function declaration. For example,

void displayNumber() {

// code

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 67


This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.

For example,

int add (int a, int b) {

return (a + b);

Here, we have the data type int instead of void. This means that the function returns
an int value.

The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code after return inside the
function is not executed.

Example 3: Add Two Numbers

// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
return (a + b);
}

int main() {

int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 68


cout << "100 + 78 = " << sum << endl;

return 0;
}

In the above program, the add() function is used to find the sum of two numbers.

We pass two int literals 100 and 78 while calling the function.

We store the returned value of the function in the variable sum, and then we print it.

Notice that sum is a variable of int type. This is because the return value of add() is of int type.

Function Prototype
In C++, the code of function declaration should be before the function call. However, if we want
to define a function after the function call, we need to use the function prototype. For example,

// function prototype

void add(int, int);

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 69


int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b) {
cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters. That's
why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype


// using function definition after main() function
// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 70


cout << "100 + 78 = " << sum << endl;

return 0;
}

// function definition
int add(int a, int b) {
return (a + b);
}

The above program is nearly identical to Example 3. The only difference is that here, the function is
defined after the function call.
That's why we have used a function prototype in this example.

Benefits of Using User-Defined Functions


 Functions make the code reusable. We can declare them once and use them multiple
times.

 Functions make the program easier as each small task is divided into a function.

 Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't need to
write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these
library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to
include the header file cmath.

Example 5: C++ Program to Find the Square Root of a Number

#include <iostream>

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 71


#include <cmath>
using namespace std;

int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}

In this program, the sqrt() library function is used to calculate the square root of a number.
The function declaration of sqrt() is defined in the cmath header file. That's why we need to
use the code #include <cmath> to use the sqrt() function.
Try it yourself
1. Make a function of add, subtract, multiplication and division and displays output in main
function .

Week 10: C++ User define Function Types &


Overloading
User-defined Function Types
For better understanding of arguments and return in functions, user-defined functions can be
categorised as:

 Function with no argument and no return value

 Function with no argument but return value

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 72


 Function with argument but no return value

 Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by
making user-defined function in 4 different ways as mentioned above.

Examples:
Example 1: No arguments passed and no return value

# include <iostream>
using namespace std;

void prime();

int main()
{
// No argument is passed to prime()
prime();
return 0;
}

// Return type of function is void because value is not returned.


void prime()
{

int num, i, flag = 0;

cout << "Enter a positive integer enter to check: ";


cin >> num;

for(i = 2; i <= num/2; ++i)


{
if(num % i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 73


cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number.";
}
}
In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is a prime
number or not.
Since, return type of prime() is void, no value is returned from the function.
Example 2: No arguments passed but a return value
#include <iostream>
using namespace std;

int prime();

int main()
{
int num, i, flag = 0;
// No argument is passed to prime()
num = prime();
for (i = 2; i <= num/2; ++i)
{
if (num%i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 74


return 0;
}
// Return type of function is int
int prime()
{
int n;
printf("Enter a positive integer to check: ");
cin >> n;

return n;
}
In the above program, prime() function is called from the main() with no arguments.
prime() takes a positive integer from the user. Since, return type of the function is an int, it
returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto the
screen.
Example 3: Arguments passed but no return value
#include <iostream>
using namespace std;

void prime(int n);

int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;

// Argument num is passed to the function prime()


prime(num);
return 0;
}

// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n)
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 75


{
if (n%i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}
In the above program, positive number is first asked from the user which is stored in the
variable num.
Then, num is passed to the prime() function where, whether the number is prime or not is
checked and printed.
Since, the return type of prime() is a void, no value is returned from the function.
Example 4: Arguments passed and a return value.
#include <iostream>
using namespace std;

int prime(int n);

int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;

// Argument num is passed to check() function


flag = prime(num);

if(flag == 1)
cout << num << " is not a prime number.";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 76


else
cout<< num << " is a prime number.";
return 0;
}

/* This function returns integer value. */


int prime(int n)
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}

return 0;
}
In the above program, a positive integer is asked from the user and stored in the variable num.
Then, num is passed to the function prime() where, whether the number is prime or not is
checked.
Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the
number is a prime number, 1 is returned. If not, 0 is returned.
Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the
corresponding text is printed onto the screen.

Which method is better?


All four programs above gives the same output and all are technically correct program.
There is no hard and fast rule on which method should be chosen.
The particular method is chosen depending upon the situation and how you want to solve a
problem.
Practice Question
1. Use these four methods to check whether the number is even or odd.

Overloading
C++ Function Overloading
In C++, two functions can have the same name if the number and/or type of arguments passed
is different.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 77


These functions having the same name but different arguments are known as overloaded
functions.

For example:

// same name different arguments

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Here, all 4 functions are overloaded functions.

Notice that the return types of all these 4 functions are not the same. Overloaded functions
may or may not have different return types but they must have different arguments.

For example,

// Error code

int test(int a) { }

double test(int b){ }

Here, both functions have the same name, the same type, and the same number of arguments.
Hence, the compiler will throw an error.

Examples:
Example 1: Overloading Using Different Types of Parameter

// Program to compute absolute value


// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 78


// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}

int main() {

// call function with int type parameter


cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter


cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output

Absolute value of -5 = 5

Absolute value of 5.5 = 5.5

Working of overloading for the absolute() function

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 79


In this program, we overload the absolute() function. Based on the type of parameter passed
during the function call, the corresponding function is called.
Example 2: Overloading Using Different Number of Parameters

#include <iostream>
using namespace std;

// function with 2 parameters


void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// function with double type single parameter


void display(double var) {
cout << "Double number: " << var << endl;
}

// function with int type single parameter


void display(int var) {
cout << "Integer number: " << var << endl;
}

int main() {

int a = 5;
double b = 5.5;

// call function with int type parameter


display(a);

// call function with double type parameter


display(b);

// call function with 2 parameters


display(a, b);

return 0;
}
Output

Integer number: 5

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 80


Float number: 5.5

Integer number: 5 and double number: 5.5

Here, the display() function is called three times with different arguments. Depending on the
number and type of arguments passed, the corresponding display() function is called.

Working of overloading for the display() function

The return type of all these functions is the same but that need not be the case for function
overloading.

Note: In C++, many standard library functions are overloaded. For example, the sqrt() function
can take double, float, int, etc. as parameters. This is possible because the sqrt() function is
overloaded in C++.

Week 11: C++Default Arguments, Storage Class


and Recursion
C++ Programming Default Arguments (Parameters)
In C++ programming, we can provide default values for function parameters.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 81


If a function with default arguments is called without passing arguments, then the default
parameters are used.

However, if arguments are passed while calling the function, the default arguments are
ignored.

Working of default arguments

How default arguments work in C++

We can understand the working of default arguments from the image above:

1. When temp() is called, both the default parameters are used by the function.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 82


2. When temp(6) is called, the first argument becomes 6 while the default value is used for
the second parameter.

3. When temp(6, -2.3) is called, both the default parameters are overridden, resulting in i =
6 and f = -2.3.

4. When temp(3.4) is passed, the function behaves in an undesired way because the
second argument cannot be passed without passing the first argument.

Therefore, 3.4 is passed as the first argument. Since the first argument has been defined
as int, the value that is actually passed is 3.

Example: Default Argument


#include <iostream>
using namespace std;

// defining the default arguments


void display(char = '*', int = 3);

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters
display();

cout << "First argument passed: ";


// #, 3 will be parameters
display('#');

cout << "Both arguments passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}

void display(char c, int count) {

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 83


for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}

Output
Here is how this program works:
No argument passed: ***
First argument passed:
1. is called without passing any arguments. In this case, display uses both the default
display
### Both arguments
passed: $$$$$ c = '*' n=1
parameters and .
2.is display('#')
called with only one argument. In this case, the first becomes '#'. The second
default parameter
isn retained.
=1
is called with both arguments. In this case, default arguments are not used.
3. display('#', count)
We can also define the default parameters in the function definition itself. The program below
is equivalent to the one above.

#include <iostream> using namespace std;

// defining the default arguments


void display(char c = '*', int count = 3) { for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 84


display();

cout << "First argument passed: ";


// #, 3 will be
parameters display('#');

cout << "Both argument passed: ";


// $, 5 will be
parameters display('$',
count);

return 0;
}
Things to Remember

1. Once we provide a default value for a parameter, all subsequent parameters must also have
default values. For example,

2. If we are defining the default arguments in the function definition instead of the function
// Invalid
prototype,
void add(int then
a,the function
int b = 3,must
intbe c,
defined
int before
d); the function call.

// Invalid
// Invalid code
void add(int a, int b = 3, int c, int d = 4);
int main() {
// //
function
Valid call display();
} void add(int a, int c, int b = 3, int d = 4);

void display(char c = '*', int count = 5) {


// code

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 85


}

C++ Storage Class


Every variable in C++ has two features: type and storage class.

Type specifies the type of data that can be stored in a variable. For
example: int, float, char etc.
And, storage class controls two different properties of a variable: lifetime (determines how long
a variable can exist) and scope (determines which part of the program can access it).

Depending upon the storage class of a variable, it can be divided into 4 major types:

 Local variable



Global variable
 Static local variable Register Variable
Thread Local Storage

Local Variable
A variable defined inside a function (defined inside function body between braces) is called a local
variable or automatic variable.

Its scope is only limited to the function where it is defined. In simple terms, local variable exists and
can be accessed only inside a function.

The life of a local variable ends (It is destroyed) when the function exits.

Example 1: Local variable


#include <iostream>
using namespace std;

void test();

int main()
{
// local variable to main()

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 86


int var = 5;

test();

// illegal: var1 not declared inside main()


var1 = 9;
}

void test()
{
// local variable to test()
int var1;
var1 = 6;

// illegal: var not declared inside test()


cout << var;
}
The variable var cannot be used inside test() and var1 cannot be used inside main() function.

Keyword auto was also used for defining local variables before as: auto int var;

But, after C++11 auto has a different meaning and should not be used for defining local variables.

Global Variable

If a variable is defined outside all functions, then it is called a global variable.

The scope of a global variable is the whole program. This means, It can be used and changed at any
part of the program after its declaration.

Likewise, its life ends only when the program ends.

Example 2: Global variable


#include <iostream>
using namespace std;

// Global variable declaration


int c = 12;

void test();

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 87


int main()
{
++c;

// Outputs 13
cout << c <<endl;
test();

return 0;
}

void test()
{
++c;

// Outputs 14
cout << c;
}
Output

13

14

In the above program, c is a global variable.

This variable is visible to both functions main() and test() in the above program.

In the above program, c is a global variable.

This variable is visible to both functions main() and test() in the above program

Static Local variable


Keyword static is used for specifying a static variable. For example:

int main()

static float a;

... .. ...

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 88


}

A static local variable exists only inside a function where it is declared (similar to a local variable) but
its lifetime starts when the function is called and ends only when the program ends.

The main difference between local variable and static variable is that, the value of static variable
persists the end of the program.

Example 3: Static local variable


#include <iostream>
using namespace std;

void test()
{
// var is a static variable
static int var = 0;
++var;

cout << var << endl;


}

int main()
{

test();
test();

return 0;
}
Output

In the above program, test() function is invoked 2 times.

During the first call, variable var is declared as static variable and initialized to 0. Then 1 is added
to var which is displayed in the screen.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 89


When the function test() returns, variable var still exists because it is a static variable.

During second function call, no new variable var is created. The same var is increased by 1 and then
displayed to the screen.

Output of above program if var was not specified as static variable

C++ Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion

Working of Recursion in C++

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 90


How recursion works in C++ programming

The recursion continues until some condition is met.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and the other doesn't.

Example 1: Factorial of a Number Using Recursion


// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 91


}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output

Enter a non-negative number: 4

Factorial of 4 = 24

Working of Factorial Program

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 92


How this C++ recursion program works

As we can see, the factorial() function is calling itself. However, during each call, we have
decreased the value of n by 1. When n is less than 1, the factorial() function ultimately returns
the output.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 93


Week 12: C++ Return Reference, Strings
C++ Return by Reference
In C++ Programming, not only can you pass values by reference to a function but you can also

return a value by reference.


 Global variables
To understand this feature, you should have the knowledge of:
Example: Return by Reference

Output
#include
<iostream> using
namespace std;

// global
variable int
num;

// function
declaration int&
test();

int main() {

// assign 5 to num variable


// equivalent to num =
5; test() = 5;

cout <<

num;

return 0;
}

// function definition

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 94


5

In program above, the return type of function test() is int& . Hence, this function returns a
reference of the variable num.

The return statement is return num;. Unlike return by value, this statement doesn't return
value of num, instead it returns the variable itself (address).

So, when the variable is returned, it can be assigned a value as done in test() = 5;

This stores 5 to the variable num, which is displayed onto the screen.

C++ Strings
String is a collection of characters. There are two types of strings commonly used in C++
programming language:

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 \0 (ASCII value of null


ch terminated with null character, that
character is 0). is,

How to define a C-string?

char str[] = "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];

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 95


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

Enter another string: Programming is fun.

You entered: Programming

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

This is because the extraction operator >> works as scanf() in C and considers a space " " has a
terminating character.

Example 2: C++ String to read a line of text


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

#include <iostream>

using namespace std;

int main()

char str[100];

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 96


cout << "Enter a string: ";

cin.get(str, 100);

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

return 0;

Output

Enter a string: Programming is fun.

You entered: Programming is fun.

To read the text containing blank space, cin.get function can be used. This function takes two
arguments.

First argument is the name of the string (address of first element of string) and second
argument is the maximum size of the array.

In the above program, str is the name of the string and 100 is the maximum size of the array.

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

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 97


cout << "You entered: " << str << endl;
return 0;
}
Output

Enter a string: Programming is fun.

You entered: Programming is fun.

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.

Passing String to a Function


Strings are passed to a function in a similar way arrays are passed to a function.

#include <iostream>

using namespace std;

void display(char *);s


void display(string);

int main()
{
string str1;
char str[100];

cout << "Enter a string: ";


getline(cin, str1);

cout << "Enter another string: ";


cin.get(str, 100, '\n');

display(str1);
display(str);
return 0;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 98


}

void display(char s[])


{
cout << "Entered char array is: " << s << endl;
}

void display(string s)
{
cout << "Entered string is: " << s << endl;
}
Output

Enter a string: Programming is fun.

Enter another string: Really?

Entered string is: Programming is fun.

Entered char array is: Really?

In the above program, two strings are asked to enter. These are stored
in str and str1 respectively, where str is a char array and str1 is a string object.

Then, we have two functions display() that outputs the string onto the string.

The only difference between the two functions is the parameter. The first display() function
takes char array as a parameter, while the second takes string as a parameter.

This process is known as function overloading.

C++ Stack
The stack provides the functionality of a stack data structure in C++.

The stack data structure follows the LIFO (Last In First Out) principle. That is, the element
added last will be removed first.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 99


Stack Data Structure

Create a Stack
In order to create a stack in C++, we first need to include the stack header file.

#include <stack>

Once we import this file, we can create a stack using the following syntax:

stack<type> st;

Here, type indicates the data type we want to store in the stack. For instance,

// create a stack of integers

stack<int> integer_stack;

// create a stack of strings

stack<string> string_stack;

Example: C++ STL Stack


#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of strings


Lab Manual Programming Fundamental By Ms Sidra Khalid Page 100
stack<string> languages;

// add element to the Stack

languages.push("C++");

languages.push("Java");

languages.push("Python");

// print top element

cout << languages.top();

return 0;

Output

Python

In the above example, we have created a stack of strings named languages.

Here, we have used the push() method to add elements to the stack. We have then used
the top() method to display the top element.

We will learn more about push() and top() method later in the tutorial.

Stack Methods
In C++, the stack class provides various methods to perform different operations on a stack.

Operation Description

push() adds an element into the stack

pop() removes an element from the stack

top() returns the element at the top of the stack

size() returns the number of elements in the stack

empty() returns true if the stack is empty

Add Element Into the Stack

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 101


We use the push() method to add an element into a stack. For example,

#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of strings

stack<string> colors;

// push elements into the stack

colors.push("Red");

colors.push("Orange");

cout << "Stack: ";

// print elements of stack

while(!colors.empty()) {

cout << colors.top() << ", ";

colors.pop();

return 0;

Output

Stack: Orange, Red,

In the above example, we have created a stack of strings called colors. Then, we have used
the push() method to add elements to the stack.

colors.push("Red");

colors.push("Orange");

Instead of directly printing the contents of the stack, we have used a while loop and various stack
methods.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 102


while(!colors.empty()) {

cout << colors.top() << ", ";

colors.pop();

To print all elements of the stack, we print its top element and then pop (remove) it inside the
loop. This process continues repeatedly until the stack is empty.

We will learn about the pop(), top() and empty() methods in the coming sections.

Also notice that we have inserted the elements in this order: {"Red", "Orange"}.

But when printing the elements, we get {"Orange", "Red"} instead.

This is because the stack is a LIFO data structure, which means that the element inserted last is
retrieved first.

Note: Unlike vectors or other containers, we cannot use a ranged for loop to iterate through a
stack. This is because the STL stack is an STL Container Adapter, which provides restrictive
access to make it behave like a standard stack data structure.

Remove Elements From the Stack

We can remove an element from the stack using the pop() method. For example,

#include <iostream>

#include <stack>

using namespace std;

// function prototype for display_stack utility

void display_stack(stack<string> st);

int main() {

// create a stack of strings

stack<string> colors;

// push elements into the stack

colors.push("Red");

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 103


colors.push("Orange");

colors.push("Blue");

cout << "Initial Stack: ";

// print elements of stack

display_stack(colors);

// removes "Blue" as it was inserted last

colors.pop();

cout << "Final Stack: ";

// print elements of stack

display_stack(colors);

return 0;

// utility function to display stack elements

void display_stack(stack<string> st) {

while(!st.empty()) {

cout << st.top() << ", ";

st.pop();

cout << endl;

Output

Initial Stack: Blue, Orange, Red,

Final Stack: Orange, Red,

In the above example, we have used the pop() method to remove an element from the stack.

Initially, the contents of the stack are {"Blue", "Orange", "Red"}.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 104


Then we have used the pop() method to remove the element.

// removes top element

colors.pop()

This removes the element at the top of the stack i.e. the element inserted last, which is "Blue".

Hence, the final stack becomes {"Orange", "Red"}.

Access Elements From the Stack

We access the element at the top of the stack using the top() method. For example,

#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of strings

stack<string> colors;

// push element into the stack

colors.push("Red");

colors.push("Orange");

colors.push("Blue");

// get top element

string top = colors.top();

cout << "Top Element: " << top;

return 0;

Output

Top Element: Blue

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 105


In the above example, we have created a stack of strings called colors and added the following
elements: "Red", "Orange" and "Blue".

We have then used the top() method to access the top element:

string top = colors.top();

Here, "Blue" was inserted last, so it is the top element.

Get the Size of the Stack

We use the size() method to get the number of elements in the stack. For example,

#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of int

stack<int> prime_nums;

// push elements into the stack

prime_nums.push(2);

prime_nums.push(3);

prime_nums.push(5);

// get the size of the stack

int size = prime_nums.size();

cout << "Size of the stack: " << size;

return 0;

Output

Size of the stack: 3

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 106


In the above example, we have created a stack of integers called prime_nums and added three
elements to it.

Then we have used the size() method to find the number of elements in the stack:

prime_nums.size();

Since we have added 3 elements to the stack, prime_nums.size() returns 3.

Check if the Stack Is Empty

We use the empty() method to check if the stack is empty. This method returns:

 1 (true) - if the stack is empty

 0 (false) - if the stack is not empty

For example,

#include <iostream>

#include <stack>

using namespace std;

int main() {

// create a stack of double

stack<double> nums;

cout << "Is the stack empty? ";

// check if the stack is empty

if (nums.empty()) {

cout << "Yes" << endl;

else {

cout << "No" << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 107


cout << "Pushing elements..." << endl;

// push element into the stack

nums.push(2.3);

nums.push(9.7);

cout << "Is the stack empty? ";

// check if the stack is empty

if (nums.empty()) {

cout << "Yes";

else {

cout << "No";

return 0;

Output

Is the stack empty? Yes

Pushing elements...

Is the stack empty? No

In the above example, we have used the empty() method to determine if the stack is empty,

if(nums.empty()) { // returns false

cout << "Yes" << end;;

else {

cout << "No" << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 108


Initially, the stack has no elements in it. So nums.empty() returns true.

We have then added elements to the stack.

Again, we use nums.empty() to determine if the stack is empty. This time, it returns false.

Week 13: Arrays, Multidimensional array,


Function and array
C++ Arrays
In C++, an array is a variable that can store multiple values of the same type. For example,

Suppose a class has 27 students, and we need to store the grades of all of them. Instead of
creating 27 separate variables, we can simply create an array:

double grade[27];

Here, grade is an array that can hold a maximum of 27 elements of double type.

In C++, the size and type of arrays cannot be changed after its declaration.

C++ Array Declaration


dataType arrayName[arraySize];

For example,

int x[6];

Here,

 int - type of element to be stored

 x - name of the array

 6 - size of the array

Access Elements in C++ Array


In C++, each element in an array is associated with a number. The number is known as an array
index. We can access elements of an array by using those indices.

// syntax to access array elements

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 109


array[index];

Consider the array x we have seen above.

Elements of an array in C++

C++ Array Initialization


In C++, it's possible to initialize an array during declaration. For example,

// declare and initialize and array

int x[6] = {19, 10, 8, 17, 9, 15};

C++ Array elements and their data

Another method to initialize array during declaration:

// declare and initialize an array

int x[] = {19, 10, 8, 17, 9, 15};

Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.

C++ Array With Empty Members

In C++, if an array has a size n, we can store upto n number of elements in the array. However,
what will happen if we store less than n number of elements.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 110


For example,

// store only 3 elements in the array

int x[6] = {19, 10, 8};

Here, the array x has a size of 6. However, we have initialized it with only 3 elements.

In such cases, the compiler assigns random values to the remaining places. Often times, this
random value is simply 0.

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9 mark[3] = 9;

// take input from the user


// store the value at third position cin >> mark[2];

// take input from the user


// insert at ith position cin >> mark[i-1];

// print first element of the array cout << mark[0];

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 111


// print ith element of the array cout >> mark[i-1];

Examples
Example 1: Displaying Array Elements

#include <iostream>

using namespace std;

int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements

// using range based for loop

for (int n : numbers) {

cout << n << " ";

cout << "\nThe numbers are: ";

// Printing array elements

// using traditional for loop

for (int i = 0; i < 5; ++i) {

cout << numbers[i] << " ";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 112


return 0;

Output
The numbers are: 7 5 6 12 35

The numbers are: 7 5 6 12 35

Example 2: Take Inputs from User and Store Them in an Array


#include <iostream>
using namespace std;

int main() {

int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;
}

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 113


Output

Example 3: 5Display
Enter Sum and Average of Array Elements Using for Loop
numbers:
11 <iostream>
#include
12
using namespace
13 std;
14
15
The { numbers are: 11
int main() 12 13 14 15

// initialize an array without specifying size

double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;

double count = 0;

double average;

cout << "The numbers are: ";

// print array elements

// use of range-based for loop

for (double n : numbers) {

cout << n << " ";

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 114


// calculate the sum

sum += n;

// count the no. of array elements

++count;

// print the sum

cout << "\nTheir Sum = " << sum << endl;

// find the average

average = sum / count;

cout << "Their Average = " << average << endl;

return 0;

C++ Multidimensional Arrays


In C++, we can create an array of an array, known as a multidimensional array. For example:

int x[3][4];

Here, x is a two-dimensional array. It can hold a maximum of 12 elements.

We can think of this array as a table with 3 rows and each row has 4 columns as shown below.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 115


Three-dimensional arrays also work in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements.

We can find out the total number of elements in the array simply by multiplying its dimensions:

2 x 4 x 3 = 24

Multidimensional Array Initialization


Like a normal array, we can initialize a multidimensional array in more than one way.

1. Initialization of two-dimensional array

int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same array
elements is given below:

int test[2][3] = { {2, 4, 5}, {9, 0, 19}};

This array has 2 rows and 3 columns, which is why we have two rows of elements with 3
elements each.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 116


2. Initialization of three-dimensional array

int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,

2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

This is not a good way of initializing a three-dimensional array. A better way to initialize this
array is:

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }

};

Notice the dimensions of this three-dimensional array.

The first dimension has the value 2. So, the two elements comprising the first dimension are:

Element 1 = { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }

Element 2 = { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }

Example
Example 1: Two Dimensional Array

// C++ Program to display all elements


// of an initialised two dimensional array

#include
<iostream> using

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 117


int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};

// use of nested for loop


// access rows of the
array for (int i = 0; i <
3; ++i) {

// access columns of the


array for (int j = 0; j <
2; ++j) {
cout << "test[" << i << "][" << j << "] = " << test[i][j] <<
endl;
}
}

Example 2: Taking Input for Two Dimensional Array

#include
<iostream> using
namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 118


for (int j = 0; j < 3; ++j) { cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements for (int i = 0; i < 2; ++i) {


for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] <<
endl;
}
}

return 0;
}

Example 3: Three Dimensional Array


// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream> using namespace std;

int main() {
// This array can store upto 12 elements (2x3x2) int test[2][3][2] = {
{

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 119


{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};

// Displaying the values with proper


index. for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; +
+k) {
cout << "test[" << i << "][" << j << "][" << k << "] = " <<
test[i][j][k] << endl;
}
}
}

return 0;
}

Output

test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 120


Passing Array to a Function in C++ Programming
In C++, we can pass arrays as an argument to a function. And, also we can return arrays from a
function.

Syntax for Passing Arrays as Function Parameters

The syntax for passing an array to a function is:

returnType functionName(dataType arrayName[arraySize]) {

// code

Let's see an example,

int total(int marks[5]) {

// code

Examples
Example 1: Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students

#include <iostream>

using namespace std;

// declare function to display marks

// take a 1d array as parameter

void display(int m[5]) {

cout << "Displaying marks: " << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 121


// display array elements

for (int i = 0; i < 5; ++i) {

cout << "Student " << i + 1 << ": " << m[i] << endl;

int main() {

// declare and initialize an array

int marks[5] = {88, 76, 90, 61, 69};

// call display function

// pass array as argument

display(marks);

return 0;

Example 2: Passing Multidimensional Array to a Function


Lab Manual Programming Fundamental By Ms Sidra Khalid Page 122
// C++ Program to display the elements of two

// dimensional array by passing it to a function

#include <iostream>

using namespace std;

// define a function

// pass a 2d array as a parameter

void display(int n[][2]) {

cout << "Displaying Values: " << endl;

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

for (int j = 0; j < 2; ++j) {

cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;

int main() {

// initialize 2d array

int num[3][2] = {

{3, 4},

{9, 5},

{7, 1}

};

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 123


// call the function

// pass a 2d array as an argument

display(num);

return 0;

Week 14: Pointers, Pointers and arrays, Pointer


and function
C++ Pointers
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;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 124


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;

// print address of var3


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

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;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 125


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

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

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;

Example 1: 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;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 126


// print the content of the address pointVar points to

cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar << endl;

return 0;

Changing Value Pointed by Pointers


If pointVar points to the address of var, we can change the value of var by using *pointVar.

int var = 5; int* pointVar;

// assign address of var pointVar = &var;

// change value at address pointVar

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 127


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

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

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 128


// change value of var to 16
*pointVar = 16;

// print var
cout << "var = " << var << endl;

// print *pointVar
cout << "*pointVar = " << *pointVar << endl;
return 0;
}

C++ Pointers and Arrays


In C++, Pointers are variables that hold addresses of other variables. Not only can a pointer store the
address of a single variable, it can also store the address of cells of an array.

Consider this example:

int *ptr;

int arr[5];

// store the address of the first

// element of arr in ptr

ptr = arr;

Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of
the first element of the array in variable ptr.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 129


Notice that we have used arr instead of &arr[0]. This is because both are the same. So, the code
below is the same as the code above.

int *ptr;

int arr[5];

ptr = &arr[0];

Point to Every Array Elements


We need to point to the fourth element of the array using the same pointer ptr.

Here, if ptr points to the first element in the above example then ptr + 3 will point to the fourth
element. For example,

int *ptr;

int arr[5];

ptr = arr;

ptr + 1 is equivalent to &arr[1];

ptr + 2 is equivalent to &arr[2];

ptr + 3 is equivalent to &arr[3];

ptr + 4 is equivalent to &arr[4];

Similarly, we can access the elements using the single pointer. For example,

// use dereference operator

*ptr == arr[0];

*(ptr + 1) is equivalent to arr[1];

*(ptr + 2) is equivalent to arr[2];

*(ptr + 3) is equivalent to arr[3];

*(ptr + 4) is equivalent to arr[4];

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 130


Example 1: C++ Pointers and Arrays
// C++ Program to display address of each element of an array

#include <iostream>
using namespace std;

int main()
{
float arr[3];

// declare pointer variable


float *ptr;

cout << "Displaying address using arrays: " << endl;

// use for loop to print addresses of all array elements


for (int i = 0; i < 3; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}

// ptr = &arr[0]
ptr = arr;

cout<<"\nDisplaying address using pointers: "<< endl;

// use for loop to print addresses of all array elements


// using pointer notation
for (int i = 0; i < 3; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}

return 0;
}
Example 2: Array name used as pointer
// C++ Program to insert and display data entered by using pointer notation.

#include <iostream>
using namespace std;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 131


int main() {
float arr[5];

// Insert data using pointer notation


cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) {

// store input number in arr[i]


cin >> *(arr + i) ;

// Display data using pointer notation


cout << "Displaying data: " << endl;
for (int i = 0; i < 5; ++i) {

// display value of arr[i]


cout << *(arr + i) << endl ;

return 0;
}

C++ Call by Reference: Using pointers

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 132


We learned about passing arguments to a function. This method used is called passing by value
because the actual value is passed.
However, there is another way of passing arguments to a function where the actual values of
arguments are not passed. Instead, the reference to values is passed.
For example,

Example 1: Passing by reference without pointers


#include <iostream>
// function that takes value as parameter
using namespace std;
void func1(int numVal) {
// code
// function definition to swap values
}
void swap(int &n1, int &n2) {
intfunction
// temp; that takes reference as parameter
temp
// = n1; the & before the
notice
n1 = n2; void func2(int
parameter
&numRef) {
// code
}

int main() {
int num = 5;

// pass by
value
func1(num);

// pass by
reference
func2(num);

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 133


n2 = temp;
}

int main() {

// initialize variables
int a = 1, b = 2;

cout << "Before swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

// call function to swap numbers


swap(a, b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

return 0;
}

In this program, we passed the variables a and b to the swap() function. Notice the function
definition,
void swap(int &n1, int &n2)
Here, we are using & to denote that the function will accept addresses as its parameters.
Hence, the compiler can identify that instead of actual values, the reference of the variables is
passed to function parameters.

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 134


In the swap() function, the function parameters n1 and n2 are pointing to the same value as the
variables a and b respectively. Hence the swapping takes place on actual value.
Example 2: Passing by reference using pointers
#include <iostream>
using namespace std;

// function prototype with pointers as parameters


void swap(int*, int*);

int main() {

// initialize variables
int a = 1, b = 2;

cout << "Before swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

// call function by passing variable addresses


swap(&a, &b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

// function definition to swap numbers


void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output
Before swapping
a=1
b=2

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 135


After swapping
a=2
b=1
Here, we can see the output is the same as in the previous example. Notice the line,
// &a is address of a
// &b is address of b
swap(&a, &b);
Here, the address of the variable is passed during the function call rather than the variable.
Since the address is passed instead of the value, a dereference operator * must be used to
access the value stored in that address.
temp = *n1;
*n1 = *n2;
*n2 = temp;
*n1 and *n2 gives the value stored at address n1 and n2 respectively.
Since n1 and n2 contain the addresses of a and b, anything is done to *n1 and *n2 will change
the actual values of a and b.
Hence, when we print the values of a and b in the main() function, the values are changed.

Week 15: Memory Management and File


C++ Memory Management: new and delete
C++ allows us to allocate the memory of a variable or an array in run time. This is known as
dynamic memory allocation. In C++, we need to deallocate the dynamically allocated memory

manually after we have no use for the variable.

We can allocate and then deallocate memory dynamically using the new and delete operators
respectively.
C++ new Operator
The new operator allocates memory to a variable. For example,

// declare an int pointer

int* pointVar;

// dynamically allocate memory

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 136


// using the new keyword

pointVar = new int;

// assign value to allocated memory

*pointVar = 45;

Here, we have dynamically allocated memory for an int variable using the new operator.

Notice that we have used the pointer pointVar to allocate the memory dynamically. This is
because the new operator returns the address of the memory location.

In the case of an array, the new operator returns the address of the first element of the array.

From the example above, we can see that the syntax for using the new operator is

pointerVariable = new dataType;

Delete Operator
Once we no longer need to use a variable that we have declared dynamically, we can deallocate
the memory occupied by the variable.

For this, the delete operator is used. It returns the memory to the operating system. This is
known as memory deallocation.

The syntax for this operator is

delete pointerVariable;

Consider the code:

// declare an int pointer

int* pointVar;

// dynamically allocate memory

// for an int variable

pointVar = new int;

// assign value to the variable memory

*pointVar = 45;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 137


// print the value stored in memory

cout << *pointVar; // Output: 45

// deallocate the memory

delete pointVar;

Examples:
Example 1: C++ Dynamic Memory Allocation

#include
<iostream> using
namespace std;

int main() {

// declare an int
pointer int*
pointInt;

// declare a float pointer


float* pointFloat;

// dynamically allocate
memory pointInt = new int;
pointFloat = new float;

// assigning value to the memory


*pointInt = 45;
*pointFloat = 45.45f;

cout << *pointInt <<


endl; cout <<
*pointFloat << endl;

// deallocate the
memory delete
pointInt;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 138


Example 2: C++ new and delete Operator for Arrays

// C++ Program to store GPA of n number of students and display it


// where n is the number of students entered by the user

#include
<iostream> using
namespace std;

int

main()

{ int

num;
cout << "Enter total number of students: ";
cin >>
num;
float*
ptr;

// memory allocation of num number of


floats ptr = new float[num];

cout << "Enter GPA of students." <<


endl; for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 <<
": "; cin >> *(ptr + i);
}

cout << "\nDisplaying GPA of students." <<


endl; for (int i = 0; i < num; ++i) {

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 139


C++ File Handling
File handling in C++ is a mechanism to create and perform read/write operations on a file.

We can access various file handling methods in C++ by importing the <fstream> class.

#include <fstream>

<fstream> includes two classes for file handling:

 ifstream - to read from a file.

 ofstream - to create/open and write to a file.

Note: Our online compiler cannot handle file handling right now. So, please install an IDE or
text editor on your computer to run the programs given here.

Opening and Closing a File


In order to work with files, we first need to open them. In C++, we can open a file using
the ofstream and ifstream classes.

For example, here's how we can open a file using ofstream:

std::ofstream my_file("example.txt");

Here,

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 140


 my_file - the name of the object of the ofstream class.

 example.txt - the name and extension of the file we want to

open. Note: We can also use the open() function to open a file. For

example, std::ofstream my_file.open("example.txt");

Closing a File

Once we're done working with a file, we need to close it using the close() function.

my_file.close();

Let's take an example program to look at these operations.

Example 1: Opening and Closing a File

#include <iostream>

#include <fstream>

using namespace std;

int main() {

// opening a text file for writing

ofstream my_file("example.txt");

// close the file

my_file.close();

return 0;

This code will open and close the file example.txt.

Note: If there's no such file to open, ofstream my_file("example.txt"); will instead create a new
file named example.txt.

Check the File for Errors

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 141


In file handling, it's important to ensure the file was opened without any error before we can
perform any further operations on it.There are three common ways to check files for errors:

1. By Checking the File Object

ofstream my_file("example.txt");

// check if the file has been opened

properly if (!my_file) {

// print error message

cout << "Error opening the file." << endl;

// terminate the main() function

return 1;

Notice the condition in the if statement:

if (!my_file) {...}

This method checks if the file is in an error state by evaluating the file object itself.

 If the file has been opened successfully, the condition evaluates to true.

 If there's an error, it evaluates to false, and you can handle the error accordingly.

2. Using the is_open() Function

The is_open() function returns

 true - if the file was opened successfully.

 false - if the file failed to open or if it is in a state of

error. For example,

ofstream my_file("example.txt");

if (!my_file.is_open()) {

cout << "Error opening the file." << endl;

return 1;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 142


}

3. Using the fail() Function

The fail() function returns

 true - if the file failed to open or if it is in a state of error.

 false - if the file was opened successfully.

ofstream my_file("example.txt");

if (my_file.fail()) {

cout << "Error opening the file." << endl;

return 1;

Note: For simplicity, we recommend using the first method.

Read From a File


Reading from text files is done by opening the file using the ifstream class. For example,

ifstream my_file("example.txt");

Then, we need to read the file line-by-line. To do this, we need to loop through each line of the
file until all the lines are read, i.e., until we reach the end of the file.

We use the eof() function for this purpose, which returns

 true - if the file pointer points to the end of the file

 false - if the file pointer doesn't point to the end of the file

For example,

// variable to store file content

string line;

// loop until the end of the file

while (!my_file.eof()) {

// store the current line of the file

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 143


// in the "line" variable

getline(my_file, line);

// print the line variable

cout << line << endl;

Here, the while loop will run until the end of the file. In each iteration of the loop,

 getline(my_file, line); reads the current line of the file and stores it in the line variable.

 Then, it prints the line variable.

Next, let's clarify this with a working example.

Example 2: Read From a File


#include <iostream>

#include <fstream>

using namespace std;

int main() {

// open a text file for reading

ifstream my_file("example.txt");

// check the file for

errors if(!my_file) {

cout << "Error: Unable to open the file." << endl;

return 1;

// store the contents of the file in "line" string

string line;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 144


// loop until the end of the text file

while (!my_file.eof()) {

// store the current line of the file

// in the "line" variable

getline(my_file, line);

// print the line variable

cout << line << endl;

// close the file

my_file.close();

return 0;

Suppose example.txt contains the following text:

Contents of example.txt

Then, our terminal will print the following output:

Hello, World!

How are you?

Write to a File
We use the ofstream class to write to a file. For example,

ofstream my_file("example.txt");

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 145


We can then write to the file by using the insertion operator << with the ofstream object my_file.
For example,

#include <iostream>

#include <fstream>

using namespace std;

int main() {

// open a text file for writing

ofstream my_file("example.txt");

// check the file for

errors if(!my_file) {

cout << "Error: Unable to open the file." << endl;

return 1;

// write multiple lines to the file

my_file << "Line 1" << endl;

my_file << "Line 2" << endl;

my_file << "Line 3" << endl;

// close the file

my_file.close();

return 0;

Notice the following code for writing to the file:

my_file << "Line 1" << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 146


my_file << "Line 2" << endl;

my_file << "Line 3" << endl;

This is similar to printing output to a screen:

cout << "Line1" << endl;

In file handling, we just replace cout with the file object to write to the file instead of the
console.

Our particular code will write the following text to example.txt:

Line1

Line2

Line3

Note: Writing to an existing file will overwrite the existing contents of the file.

Append to a Text File


To add/append to the existing content of a file, you need to open the file in append mode.

In C++, you can achieve this by using the ios::app flag when opening the file:

ofstream my_file("example.txt", ios::app);

Now, let's add some more text to the existing content of example.txt:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

// open a text file for appending

ofstream my_file("example.txt", ios::app);

// if the file doesn't open successfully, print an error message

if(!my_file) {

cout << "Failed to open the file for appending." << endl;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 147


return 1;

// append multiple lines to the file

my_file << "Line 4" << endl;

my_file << "Line 5" << endl;

my_file << "Line 6" << endl;

// close the file

my_file.close();

return 0;

This will add the following lines to example.txt:

Line 4

Line 5

Line 6

Contents Appended to an Existing File

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 148


File Handling With fstream
Instead of using ifstream to read from a file and ofstream to write to the file, we can simply use
the fstream class for all file operations.

The constructor for fstream allows you to specify the file name and the mode for file operations.

Mode Description

ios::in Opens the file to read (default for ifstream).

ios::out Opens the file to write (default for ofstream).

ios::app Opens the file and appends new content to itat the end.

Let's look at an example:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

// 1. write to a text file

fstream my_file("example.txt", ios::out);

if (my_file) {

my_file << "This is a test line." << endl;

my_file.close();

else {

cout << "Unable to open file for writing." << endl;

return 1;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 149


// 2. read from the same file

string line;

my_file.open("example.txt", ios::in);

if (my_file) {

while (!my_file.eof()) {

getline(my_file, line);

cout << "Read from file: " << line << endl;

my_file.close();

else {

cout << "Unable to open file for reading." << endl;

return 1;

// 3. append data to the end of the file

my_file.open("example.txt", ios::app);

if (my_file) {

my_file << "This is another test line, appended to the file." << endl;

my_file.close();

else {

cout << "Unable to open file for appending." << endl;

return 1;

return 0;

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 150


}

Output

Read from file: This is a test line.

Read from file:

If we look at the file after running the program, we will find the following contents:

File Handling Using fstream

Note: Using ifstream and ofstream explicitly signifies the intention of reading or writing,
respectively, making the code more readable and less prone to errors. Using fstream for both
might lead to ambiguity or unintended operations if not handled carefully.

Week 16 : Revision, Presentation and Quiz

Lab Manual Programming Fundamental By Ms Sidra Khalid Page 151

You might also like