Lab Manual Programming Fundamental
Lab Manual Programming Fundamental
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
Programming Languages
• Machine Language
• Assembly 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 –
Run the downloaded .exe file to install Code Blocks in your system.
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
What is C++?
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.
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.
As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice
versa.
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.
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.
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.
Example 01
Display sum
Stop
Example 02
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,
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.
A variable name can only have alphabets, numbers, and the underscore _.
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.
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:
octal (base 8)
For example:
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
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.
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null Character
5. String Literals
C++ Constants
In C++, we can create variables whose value cannot be changed. For that, we use
the const keyword. Here's an example:
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.
Here, age is a variable of type int. Meaning, the variable can only store integers of either 2 or 4
bytes.
The table below shows the fundamental data types, their meaning, and their sizes (in bytes):
1. C++ int
Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to
2147483647.
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,
As mentioned above, these two data types are also used for exponentials. For example,
3. C++ char
For example,
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.
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,
6. C++ void
The void keyword indicates an absence of data. It means "nothing" or "no value".
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
double
char
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
long b = 4523232;
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
Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
Example
// This is a comment
cout << "Hello World!";
Example
int main()
#include <iostream>
int main()
return 0;
Note: If we don't include the using namespace std; statement, we need to use
std::cout instead of cout.
#include <iostream>
using namespace std;
// main Code
int main()
{
// Print standard output
// on the screen
cout << "Welcome to C++ Programming";
Examples
1. Write a program that print your name?
// as output
#include <iostream>
int main()
return 0;
2. Write a program that print your roll no, name ,class and age?
#include <iostream>
int main() {
return 0;
Practice Questions
1. Write a program that print pakistan?
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
int main() {
bool result;
cout << "(3 != 5) && (3 < 5) is " << result << endl;
return 0;
-- decreases it by 1
For example,
int num = 5;
// increment operator
++num; // 6
#include <iostream>
int main()
result_a = ++a;
result_b = --b;
return 0;
4. Write a Program to Find Size of int, float, double and char in Your System?
Solutions
1.
#include <iostream>
int main()
int number;
return 0;
2.
#include <iostream>
int main() {
// prints sum
cout << first_number << " + " << second_number << " = " << sum;
return 0;
3.
#include <iostream>
int main()
return 0;
4.
#include <iostream>
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>
int main()
cout << "a = " << a << ", b = " << b <<
cout << "a = " << a << ", b = " << b <<
endl; return 0;
• 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.
• 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.
if (condition)
// body of if statement
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.
if (condition)
{
// block of code if condition is true
}
else
{
• Here, we enter 4. So, the condition is true. Hence, the statement inside the body of if is
executed.
Here,
Practice Questions
1. write a program to Check Whether Number is Even or Odd
4. Take input from user and Check the year is leap year or not using if else structure.
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.
#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)
{
#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;
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
• 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.
#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
#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);
#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;
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++)
{
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;
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;
#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;
}
break;
#include <iostream>
int main() {
// break condition
if (i == 3) {
break;
return 0;
continue;
#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;
}
switch (expression)
{
case constant1:
// code to be executed if
// take score
cout << "Enter score(0-100): ";
cin >> score;
// display grade
cout << "Grade = " << grade << endl;
return 0;
}
Output:-
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:
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
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
Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
Types of function
There are two types of function:
A user-defined function groups code to perform a specific task and that group of code is given a
name (identifier).
// function body
// function declaration
void greet() {
Here,
Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function,
we need to call it.
int main() {
// calling a function
greet();
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
return 0;
}
int main() {
int n = 7;
printNum(n);
return 0;
#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() {
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
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,
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.
#include <iostream>
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
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
// function definition
void add(int a, int b) {
cout << (a + b);
}
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.
#include <iostream>
// function prototype
int add(int, int);
int main() {
int sum;
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.
Functions make the program easier as each small task is divided into a function.
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.
#include <iostream>
int main() {
double number, squareRoot;
number = 25.0;
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 .
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;
}
if (flag == 1)
{
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.";
}
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;
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
// 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)
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 main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
if(flag == 1)
cout << num << " is not a prime number.";
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.
Overloading
C++ Function Overloading
In C++, two functions can have the same name if the number and/or type of arguments passed
is different.
For example:
int test() { }
int test(int a) { }
float test(double a) { }
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) { }
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
int main() {
Absolute value of -5 = 5
#include <iostream>
using namespace std;
int main() {
int a = 5;
double b = 5.5;
return 0;
}
Output
Integer number: 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.
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++.
However, if arguments are passed while calling the function, the default arguments are
ignored.
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.
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.
int main() {
int count = 5;
return 0;
}
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.
int main() {
int count = 5;
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);
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.
void test();
int main()
{
// local variable to main()
test();
void test()
{
// local variable to test()
int var1;
var1 = 6;
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
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.
void test();
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
Output
13
14
This variable is visible to both functions main() and test() in the above program.
This variable is visible to both functions main() and test() in the above program
int main()
static float a;
... .. ...
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.
void test()
{
// var is a static variable
static int var = 0;
++var;
int main()
{
test();
test();
return 0;
}
Output
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.
During second function call, no new variable var is created. The same var is increased by 1 and then
displayed to the screen.
C++ Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.
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.
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Output
Factorial of 4 = 24
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.
Output
#include
<iostream> using
namespace std;
// global
variable int
num;
// function
declaration int&
test();
int main() {
cout <<
num;
return 0;
}
// function definition
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.
#include <iostream>
int main()
char str[100];
return 0;
Output
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.
#include <iostream>
int main()
char str[100];
cin.get(str, 100);
return 0;
Output
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.
int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);
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.
#include <iostream>
int main()
{
string str1;
char str[100];
display(str1);
display(str);
return 0;
void display(string s)
{
cout << "Entered string is: " << s << endl;
}
Output
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.
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.
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,
stack<int> integer_stack;
stack<string> string_stack;
#include <stack>
int main() {
languages.push("C++");
languages.push("Java");
languages.push("Python");
return 0;
Output
Python
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
#include <iostream>
#include <stack>
int main() {
stack<string> colors;
colors.push("Red");
colors.push("Orange");
while(!colors.empty()) {
colors.pop();
return 0;
Output
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.
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"}.
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.
We can remove an element from the stack using the pop() method. For example,
#include <iostream>
#include <stack>
int main() {
stack<string> colors;
colors.push("Red");
colors.push("Blue");
display_stack(colors);
colors.pop();
display_stack(colors);
return 0;
while(!st.empty()) {
st.pop();
Output
In the above example, we have used the pop() method to remove an element from the stack.
colors.pop()
This removes the element at the top of the stack i.e. the element inserted last, which is "Blue".
We access the element at the top of the stack using the top() method. For example,
#include <iostream>
#include <stack>
int main() {
stack<string> colors;
colors.push("Red");
colors.push("Orange");
colors.push("Blue");
return 0;
Output
We have then used the top() method to access the top element:
We use the size() method to get the number of elements in the stack. For example,
#include <iostream>
#include <stack>
int main() {
stack<int> prime_nums;
prime_nums.push(2);
prime_nums.push(3);
prime_nums.push(5);
return 0;
Output
Then we have used the size() method to find the number of elements in the stack:
prime_nums.size();
We use the empty() method to check if the stack is empty. This method returns:
For example,
#include <iostream>
#include <stack>
int main() {
stack<double> nums;
if (nums.empty()) {
else {
nums.push(2.3);
nums.push(9.7);
if (nums.empty()) {
else {
return 0;
Output
Pushing elements...
In the above example, we have used the empty() method to determine if the stack is empty,
else {
Again, we use nums.empty() to determine if the stack is empty. This time, it returns false.
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.
For example,
int x[6];
Here,
Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.
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.
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.
Examples
Example 1: Displaying Array Elements
#include <iostream>
int main() {
Output
The numbers are: 7 5 6 12 35
int main() {
int numbers[5];
return 0;
}
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
double sum = 0;
double count = 0;
double average;
sum += n;
++count;
return 0;
int x[3][4];
We can think of this array as a table with 3 rows and each row has 4 columns as shown below.
float x[2][4][3];
We can find out the total number of elements in the array simply by multiplying its dimensions:
2 x 4 x 3 = 24
The above method is not preferred. A better way to initialize this array with the same array
elements is given below:
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3
elements each.
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] = {
};
The first dimension has the value 2. So, the two elements comprising the first dimension are:
Example
Example 1: Two Dimensional Array
#include
<iostream> using
#include
<iostream> using
namespace std;
int main() {
int numbers[2][3];
return 0;
}
int main() {
// This array can store upto 12 elements (2x3x2) int test[2][3][2] = {
{
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
// code
// code
Examples
Example 1: Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
cout << "Student " << i + 1 << ": " << m[i] << endl;
int main() {
display(marks);
return 0;
#include <iostream>
// define a function
cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
int main() {
// initialize 2d array
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
Address in C++
If we have a variable var in our program, &var will give us its address in the memory. For
example,
Example 1: Printing Variable Addresses in C++
#include <iostream>
using namespace std;
int main()
{
// declare variables
int var1 = 3;
int *pointVar;
int* pointVar, p;
Note: The * operator is used after the data type to declare pointers.
var = 5;
pointVar = &var;
int main() {
int var = 5;
int* pointVar;
pointVar = &var;
cout << "Address of var (&var) = " << &var << endl
<< endl;
cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar << endl;
return 0;
Here, pointVar and &var have the same address, the value of var will also be changed
when *pointVar is changed.
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl;
return 0;
}
int *ptr;
int arr[5];
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.
int *ptr;
int arr[5];
ptr = &arr[0];
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;
Similarly, we can access the elements using the single pointer. For example,
*ptr == arr[0];
#include <iostream>
using namespace std;
int main()
{
float arr[3];
// ptr = &arr[0]
ptr = arr;
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;
return 0;
}
int main() {
int num = 5;
// pass by
value
func1(num);
// pass by
reference
func2(num);
int main() {
// initialize variables
int a = 1, b = 2;
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.
int main() {
// initialize variables
int a = 1, b = 2;
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,
int* pointVar;
*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
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.
delete pointerVariable;
int* pointVar;
*pointVar = 45;
delete pointVar;
Examples:
Example 1: C++ Dynamic Memory Allocation
#include
<iostream> using
namespace std;
int main() {
// declare an int
pointer int*
pointInt;
// dynamically allocate
memory pointInt = new int;
pointFloat = new float;
// deallocate the
memory delete
pointInt;
#include
<iostream> using
namespace std;
int
main()
{ int
num;
cout << "Enter total number of students: ";
cin >>
num;
float*
ptr;
We can access various file handling methods in C++ by importing the <fstream> class.
#include <fstream>
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.
std::ofstream my_file("example.txt");
Here,
open. Note: We can also use the open() function to open a file. For
Closing a File
Once we're done working with a file, we need to close it using the close() function.
my_file.close();
#include <iostream>
#include <fstream>
int main() {
ofstream my_file("example.txt");
my_file.close();
return 0;
Note: If there's no such file to open, ofstream my_file("example.txt"); will instead create a new
file named example.txt.
ofstream my_file("example.txt");
properly if (!my_file) {
return 1;
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.
ofstream my_file("example.txt");
if (!my_file.is_open()) {
return 1;
ofstream my_file("example.txt");
if (my_file.fail()) {
return 1;
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.
false - if the file pointer doesn't point to the end of the file
For example,
string line;
while (!my_file.eof()) {
getline(my_file, line);
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.
#include <fstream>
int main() {
ifstream my_file("example.txt");
errors if(!my_file) {
return 1;
string line;
while (!my_file.eof()) {
getline(my_file, line);
my_file.close();
return 0;
Contents of example.txt
Hello, World!
Write to a File
We use the ofstream class to write to a file. For example,
ofstream my_file("example.txt");
#include <iostream>
#include <fstream>
int main() {
ofstream my_file("example.txt");
errors if(!my_file) {
return 1;
my_file.close();
return 0;
In file handling, we just replace cout with the file object to write to the file instead of the
console.
Line1
Line2
Line3
Note: Writing to an existing file will overwrite the existing contents of the file.
In C++, you can achieve this by using the ios::app flag when opening the file:
Now, let's add some more text to the existing content of example.txt:
#include <iostream>
#include <fstream>
int main() {
if(!my_file) {
cout << "Failed to open the file for appending." << endl;
my_file.close();
return 0;
Line 4
Line 5
Line 6
The constructor for fstream allows you to specify the file name and the mode for file operations.
Mode Description
ios::app Opens the file and appends new content to itat the end.
#include <iostream>
#include <fstream>
int main() {
if (my_file) {
my_file.close();
else {
return 1;
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 {
return 1;
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 {
return 1;
return 0;
Output
If we look at the file after running the program, we will find the following contents:
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.