0% found this document useful (0 votes)
58 views165 pages

PF - Lab - Manual - Template 2024

Uploaded by

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

PF - Lab - Manual - Template 2024

Uploaded by

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

Lab Manual Programming Fundmental with C++

IQRA University, Islamabad


Department of Computer Science,
Software Engineering & AI
Lab Manual
Programming Fundamental with C++

Prepared By:

1
Lab Manual Programming Fundmental with C++

List of Experiments

Week Topics
No.
1 Installation of Code Block, first program in C++,Compiling and Executing the
program.
2 Variable declaration and initialization, Assignment Operator
3 Arithmetic Operators, Input gathering, Operators Precedence
4 Decision making statements, if, if else and nested if else statements, Logical and
Conditional Operatrs
5 Using switch and break statements, enum
6 Loops, While Loop
6 Do-while loop, Difference between while and do while loop
7 For Loop (Basic Examples)
8 For Loop (Advanced Examples)
Mid Term Exams
9 Functions, Functions Declaration and Definition, Function Calling
9 Parameters of Functions, Argument Passing
10 Return Type, Return Value, Inline Functions, Local and GlobalVariables
11 Pointers, Pointers of Arrays, Pointer constants and pointer variables,
12 Passingpointers asarguments, Pointer and functions, Basic concept of Pass by
reference
13 Basic concepts of arrays, Traversing arrays
14 Arrays (Advanced Examples)
15 Strings and their oprations
16 File Handling in C++

2
Lab Manual Programming Fundmental with C++

Week 1 Task with C++


Contents Covered: Installation of Basic features of Code Block, first program in C++,Compiling
and Executing the program.

Installation Code Blocks for C++ on Windows:

Follow the below steps to install Code Blocks for C++ on windows:

Step 1: Open Your Web Browser

Step 2: Go to the Search Panel and Search for “Code Blocks”

Step 3: Click on the First Result shown on the Search Engine or click on this link.

3
Lab Manual Programming Fundmental with C++

Step 4: Click on the “Downloads” Section.

Step 5: Click On “Download the binary release”.

Step 6: As per this Date, the Latest Version of Code Blocks is 20.03. Now here you’ll find several
download options

1. codeblocks-20.03-setup.exe : It is a standard executable file that is easier to install.


2. codeblocks-20.03-nosetup.zip : It is a zip file which you do not have to install , you can just
unzip and run it.

4
Lab Manual Programming Fundmental with C++

I’ll suggest you download the file with MinGW written on it (“codeblocks-20.03mingw-setup.exe”) as
MinGW is a Compiler that is needed to run the Program. If you download the normal setup file then you
have to download The compiler separately.

Step 7: Click on Sourceforge.net under the Download Section of your desired file.

Step 8: then Download should begin within some seconds.

Step 9: When the download is completed, Open Your Code Blocks Setup File.

Step 10: Click on Next.

5
Lab Manual Programming Fundmental with C++

Step 11: Click on I agree.

Step 12: Click On Next ( you need to have at least 600 MB free storage on your drive for the
installation).

6
Lab Manual Programming Fundmental with C++

Step 13: Select your Destination and Click on Install

7
Lab Manual Programming Fundmental with C++

Step 14: Once Installation gets completed, click on Next and then Click on Finish

Now You Code Blocks have been installed.

To Set the Environment Path of GCC compiler

8
Lab Manual Programming Fundmental with C++

Step 1: Go to your Code Blocks MinGW installation folder location ( For me it is C:\Program
Files\CodeBlocks\MinGW\bin) and copy the address

Step 2: Go to Search Panel and type “Edit System environment variables”

Step 3: Click On Environment Variables

Step 4: Under System variables, Click on Path and Select Edit

9
Lab Manual Programming Fundmental with C++

Step 5: Click on New and Paste the Address into it and click on OK

10
Lab Manual Programming Fundmental with C++

Now Code Blocks will automatically detect GCC Compiler.

11
Lab Manual Programming Fundmental with C++

12
Lab Manual Programming Fundmental with C++

13
Lab Manual Programming Fundmental with C++

Week 2 Task with C++


Contents Covered: Variable declaration and initialization, Assignment Operator

Lab Objective:
Variable declaration and initialization, Assignment Operator

Lab Description:

Data Types:

A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific
type, which determines the size and layout of the variable's memory, this type is known as data type of that variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either
a letter or an underscore. Upper and lowercase letters are distinct because C++ is case- sensitive

Figure 1 Basic data types

Variable Declaration in C++


A variable declaration provides assurance to the compiler that there is one variable existing
with thegiven type and name so that compiler proceed for further compilation.

int a;
char b;
float c;

Variable Initialization in C++

14
Lab Manual Programming Fundmental with C++

A variable can be initialized at the time of declaration or even after that. Basically initialization
means storing some actual meaningful data inside the variable.
int a=2;
char b=’x’;
float c=2.907

Constants
Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Defining Constants
There are two simple ways in C++ to define constants:
Using #define preprocessor

#define LENGTH 10

#define WIDTH 5 const int LENGTH = 10;


Using const keyword
const int WIDTH = 5;

Legal Identifiers:

Regardless of which style you adopt, be consistent and make your variable names as
sensible as possible. Here are some specific rules that must be followed with all
identifiers.
• The first character must be one of the letters a through z, A through Z, or
an underscore character (_).
• After the first character you may use the letters a through z or A through Z, the
digits 0 through 9, or underscores.
• Uppercase and lowercase characters are distinct. This means ItemsOrdered is
not the same as itemsordered.
Escape Sequence:

cout << "\t";

15
Lab Manual Programming Fundmental with C++

Fundamental Arithmetic Operators:

Assignment Operator:
C++ provides several assignment operators for abbreviating assignment expressions.
Any statement of the form

variable = variable operator expression;

in which the same variable appears on both sides of the assignment operator and operator is one of the
binary operators +, -, *, /, or % , can be written in the form
variable operator= expression;

Thus the statement c = c + 3 which adds 3 to c can be written as c += 3

16
Lab Manual Programming Fundmental with C++

Above are examples of how the assignment operator is applied in code and works

17
Lab Manual Programming Fundmental with C++

Output is:

LAB Task
Task-1:
Type and save the following programs in Visual Studio. Run these programs and observe theiroutput.

Task2:
Take two integers as input from the user apply athematic operations on them(+,-,*,/) as printthem on screen.

Task3:

Write the output of the following code

Task 4:
1. Calculate the Area of a Circle (area = PI * r2)
18
Lab Manual Programming Fundmental with C++

2. Calculate the Area of a Rectangle (area = length * width)


3. Calculate the Area of a Triangle (area = base * height * .5)

Home Tasks:
Task 1:

Exchange Write a program that reads in two variables and swaps the value of these variables. For example
if a variable ‘var1’ contains 10 and variable ‘var2’ contains 20, after the swap operation the variable ‘var1’
contains 20 (value of var2) and variable ‘var2’ contains 10 (value of var1).
Task 2:

Make Upper Write a program that prompts the user to enter an alphabet in small caps (a, b,c, … … … z)
and display the entered alphabet into its upper caps (A, B, C, … … … Z). (hint ASCII)
Task 3:
Write a C++ program to calculate the distance between the two points. Note: x1, y1, x2, y2 are all double
values.

Formula:

19
Lab Manual Programming Fundmental with C++

Task 4:

Total Purchase A customer in a store is purchasing five items. The prices of the five items are: Price of item
1 = $12.95
Price of item 2 = $24.95Price of item 3 = $6.95 Price of item 4 = $14.95Price of item 5 = $3.95
Write a program that holds the prices of the five items in five variables. Display each items price, the
subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6%.
Bonus Task:

Break Number:
Write a program that inputs a five-digit integer, separates the integer into its individual digits and prints the
digits separated from one another by three spaces each

20
Lab Manual Programming Fundmental with C++

Week 3 Task with C++


Contents Covered: Arithmetic Operators, Input gathering, Operators
Precedence, coercion, random numbers

Lab Description:

Operators’ precedence

Two operator characteristics determine how operands group with operators: precedence and
associativity. Precedence is the priority for grouping different types of operators with their
operands. Associativity is the left-to-right or right-to-left order for grouping operands to
operators that have the same precedence. An operator's precedence is meaningful only if other
operators with higher or lower precedence are present. Expressions with higher-precedence
operators are evaluated first. The grouping of operands can be forced by using parentheses.

Example:

Evaluate the following:


Y = 2*5*5+3*5+7;

Sample evaluation:

21
Lab Manual Programming Fundmental with C++

Implicit conversion (coercion)

Implicit conversions are automatically performed when a value is copied to a compatible


type. For example

Short a= 2000;Int b; b=a;


When an operator works with two values of different data types, the lower-ranking value is
promoted to the type of the higher-ranking value.
When the final value of an expression is assigned to a variable, it will be converted to the
data type of that variable.
Type casting

C++ is a strong-typed language. Many conversions, specially those that imply a


different interpretation of the value, require an explicit conversion, known in C++
as type-casting. There exist two main syntaxes for generic type-casting: functional
and c-like:

double x =
10.3; int y;
y = int (x); // functional
notation

22
Lab Manual Programming Fundmental with C++

y = (int) x; // c-like cast


notation

Expressions:

Multiplication, mode and division have higher precedence than addition and subtraction.

Associativity: left to right.

Random Function:
rand() function is an inbuilt function in C++ STL, which is defined in header file

<cstdlib>. rand() is used to generate a series of random numbers. The random number

is generated by using an algorithm that gives a series of non-related numbers whenever

this function is called.

Cout << rand(); Library used <cstdlib>

Output:

1804289383 846930886 1681692777 1714636915 1957747793

23
Lab Manual Programming Fundmental with C++

Using Rand() with Modulus operator:


The following code uses modulus operator to confine the output to a certain aspect

Output:

83 86 77 15 93

Formatting:

The following table represents various formatting operators used in C++ for output
manipulation

Example:

24
Lab Manual Programming Fundmental with C++

// C++ code to demonstrate

// the working of setw() function

#include <iomanip>

#include <ios>

#include <iostream>

using namespace std;

int main()

// Initializing the integer

int num = 50;

cout << "Before setting the width: \n" << num << endl;

// Using setw()

cout << "Setting the width"

<< " using setw to 5: \n"

<< setw(5);

cout << num;

return 0;

Output
Before setting the width:
50
Setting the width using setw to 5:
50

25
Lab Manual Programming Fundmental with C++

In the above example, we have used setw() to add padding to the integer output. We can use setw() for
many such cases.

LAB:
Task 1:

Assume that the following variables are defined: int age;


double pay; char section;
Write a single cin statement that will read input into each of these variables.

Task 2:

Complete the following table by writing the value of each expression in the Value column
according C++ language rules.

Task 3:

Assume a program has the following variable definitions:


int units; float mass;
double weight; weight = mass * units;
Which automatic data type conversion will take place?
A. mass is demoted to an int, units remains an int, and the result of mass * units is an int.
B. units is promoted to a float, mass remains a float, and the result of mass * units is a float.
C. units is promoted to a float, mass remains a float, and the result of mass * units is a double.

26
Lab Manual Programming Fundmental with C++

Task 4:

Assume a program has the following variable definitions:

int a, b = 2; float c = 4.2;

and the following statement: a = b * c; What value will be stored in a?


A. 8.4 B. 8 C. 0 D. None of the above

Task 5:

Assume that qty and salesReps are both integers. Use a type cast expression to rewrite the
following statement so it will no longer perform integer division.
unitsEach = qty / salesReps;

Home Tasks:
Task 1:

Each of the following programs has some errors. Locate as many as you can.

Program-1
using namespace std; void main ()
{

double number1, number2, sum; cout << "Enter a number: ";


Cin << number1;

cout << "Enter another number: "; cin << number2;


number1 + number2 = sum;

cout "The sum of the two numbers is " << sum

Program-2

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


{

int number1, number2; float quotient;


cout << "Enter two numbers and I will divide\n";cout << "the first by the second for you.\n";
cin >> number1, number2;

quotient= float<static_cast>(number1) / number2; cout << quotient

27
Lab Manual Programming Fundmental with C++

Task 2:
Average of Values to get the average of a series of values, you add the values up and then divide the sum by the
number of values. Write a program that stores the following values in five different variables: 28, 32, 37, 24, and
33. The program should first calculate the sum of these five variables and store the result in a separate variable
named sum. Then, the program should divide the sum variable by 5 to get the average. Display the average on the
screen.

28
Lab Manual Programming Fundmental with C++

Week 4 Task with C++


Contents Covered: 1. C-style Casting in c++,
2. Formatting
3. Decision making statements, if, if else and nested if else statements.

1. C-Style Casting:
A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.

The most general cast supported by most of the C++ compilers is as follows

Example: 1

#include <iostream>
using namespace std;

main() {

double num_a = 21.09399;


float num_b = 10.20;
int num_c;

num_c = (int)num_a;
cout << "Line 1 - Value of (int) num_a is :" << num_c << endl; // 21

num_c = (int)num_b;
cout << "Line 2 - Value of (int) num_b is :" << num_c << endl; //

return 0;
return 0;
}

29
Lab Manual Programming Fundmental with C++

Example: 2

#include <iostream>
using namespace std;

main()
{

double num_a = 21.09399;


float num_b;
int num_c = 10;

num_b = (float)num_a;
cout << num_b << endl;

num_b = (float)num_c;

cout << num_b << endl;

return 0;

Example: 3

#include <iostream>
using namespace std;

main() {

double num_a;
float num_b= 22.1;;
int num_c = 10;

num_a = (double)num_b;
cout << num_a << endl;

num_a = (double)num_c;
cout << num_a << endl;

return 0;
}

30
Lab Manual Programming Fundmental with C++

Example: 4

#include <iostream>
using namespace std;

int main()
{ //ASCII NOs
char alp = 'C';
int num_c = 45;

num_c = (int)alp;
cout << num_c << endl;

alp = (char)num_c;
cout << alp << endl;

return 0;

TASK
• Take Birthday month, Day and Year as an Input from user and convert it into floating
point.
• Find the ASCII code of ‘A’, ‘e’, ‘i’, ‘O’, ‘U’
• Create Encryption Decrypion Model where Convert the word ‘H’, ‘e’, ‘L’, ‘p’ into
ASCII code and than convert back to Char.

31
Lab Manual Programming Fundmental with C++

2. Formatting
Formatting program output is an essential part of any serious application.

Example:1
#include<iostream>

using std::cout;
using std::endl;

int main()
{
cout << "Hello world 1" << endl;
cout << "Hello world 2\n";

return 0;
}

OUTPUT:
Hello world 1
Hello world 2

Example: 2

Important Point
The setw() manipulator only affects the next value to be printed.
The setw() manipulator takes an integer argument which is the minimum field width for the value to be
printed.

#include <iostream>
#include <iomanip>

using std::cout;
using std::endl;
using std::setw;

int main()
{
// A test of setw()

cout << "*" << -17 << "*" << endl;


cout << "*" << setw(6) << -17 << "*" << endl << endl;

cout << "*" << "Hi there!" << "*" << endl;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
cout << "*" << setw(3) << "Hi there!" << "*" << endl;

return 0;
}
OUTPUT

*-17*
* -17*

*Hi there!*
32
Lab Manual Programming Fundmental with C++

* Hi there!*
*Hi there!*

Example: 3
Important Point

Left: Left-align all values in their fields.

Right: Right-align all values in their fields. This is the default alignment value.

#include <iostream>
#include <iomanip>

using std::cout;
using std::endl;
using std::setw;
using std::left;
using std::right;

int main()
{
cout << "*" << -17 << "*" << endl;
cout << "*" << setw(6) << -17 << "*" << endl;
cout << left;
cout << "*" << setw(6) << -17 << "*" << endl << endl;

cout << "*" << "Hi there!" << "*" << endl;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
cout << right;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;

return 0;
}

Output:

*-17*
* -17*
*-17 *

*Hi there!*
*Hi there! *
* Hi there!*

Example:4

33
Lab Manual Programming Fundmental with C++

Internal: Internally aligns numeric values in their fields. Internal alignment separates the sign of a
number from its digits. The sign is left-aligned and the digits are right-aligned. This is a useful format in
accounting and business programs, but is rarely used in other applications.

Setfill: Sets the specified character as the stream's fill character. The fill character is the character used
by output insertion functions to fill spaces when padding results to the field width.

#include <iostream>
#include <iomanip>

using std::cout;
using std::endl;
using std::setw;
using std::internal;

int main()
{
cout << setw(9) << -3.25 << endl;
cout << setfill('0');
cout << internal << setw(9) << -3.25 << endl;
cout << setfill(' ');
cout << internal << setw(9) << -3.25 << endl;

return 0;
}

OUTPUT

-3.25
-00003.25
- 3.25

Example: 5

fixed and scientific

The manipulator fixed will set up the output stream for displaying floating-point values in fixed
format.

The scientific manipulator forces all floating point values to be displayed in scientific notation.

#include <iostream>

using std::cout;
using std::endl;
using std::scientific;
using std::fixed;
using std::ios;

int main()
{
float small = 3.1415926535897932384626;
float large = 6.0234567e17;
float whole = 2.000000000;

cout << "Some values in general format" << endl;


34
Lab Manual Programming Fundmental with C++

cout << "small: " << small << endl;


cout << "large: " << large << endl;
cout << "whole: " << whole << endl << endl;

cout << scientific;

cout << "The values in scientific format" << endl;


cout << "small: " << small << endl;
cout << "large: " << large << endl;
cout << "whole: " << whole << endl << endl;

cout << fixed;

cout << "The same values in fixed format" << endl;


cout << "small: " << small << endl;
cout << "large: " << large << endl;
cout << "whole: " << whole << endl << endl;

return 0;
}

Output

Some values in general format


small: 3.14159
large: 6.02346e+17
whole: 2

The values in scientific format


small: 3.141593e+00
large: 6.023457e+17
whole: 2.000000e+00

The same values in fixed format


small: 3.141593
large: 602345661202956288.000000
whole: 2.000000

Task

• Take 3 numbers from the user one by one and Perform Setfill with Internal method.
• Take double type no# from the user and apply Scientific format and right method.

3. Decision making statements, if, if else and nested if else statements.

35
Lab Manual Programming Fundmental with C++

Types of Conditional Statements

Examples:
// C program to illustrate If statement
#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
cout<<("10 is greater than 15");
}

Cout<<("I am Not in if");


}

OutPut:
I am Not in if

Exmaple

#include <iostream>
using namespace std;

36
Lab Manual Programming Fundmental with C++

int main () {
// local variable declaration:
int a = 10;

// check the boolean condition


if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −

a is less than 20;


value of a is : 10

Example

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
int a = 100;

// check the boolean condition


if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −

a is not less than 20;


value of a is : 100

Example

#include <iostream>
using namespace std;

37
Lab Manual Programming Fundmental with C++

int main () {
// local variable declaration:
int a = 100;

// check the boolean condition


if( a == 10 ) {
// if condition is true then print the following
cout << "Value of a is 10" << endl;
} else if( a == 20 ) {
// if else if condition is true
cout << "Value of a is 20" << endl;
} else if( a == 30 ) {
// if else if condition is true
cout << "Value of a is 30" << endl;
} else {
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −

Value of a is not matching


Exact value of a is : 100

Example

/ C program to illustrate nested-if statement


#include <iostream>
using namespace std;

int main()
{
int i = 20;

if (i == 10)
cout << ("i is 10");
else if (i == 15)
cout << ("i is 15");
else if (i == 20)
cout << ("i is 20");
else
cout << ("i is not present");
}
Output
i is 20
Eample

#include <iostream>
using namespace std;

int main() {

38
Lab Manual Programming Fundmental with C++

// Project: Metric to US Standard

double cm=0.3937;
double m=1.0936;
double km=0.6214;
double num;
char menu_char;

//Menu
cout << "Press c for Centimeters to Inches\n";
cout << "Press m for Meters to Yards\n";
cout << "Press k for Kilometers to Miles\n";

//enter c, m, or k
cin >> menu_char;

if(menu_char == 'c') {

cout << "\nType in a number in Centimeters ";

cin >> num;

cout << "\nNumber of Inches in " << num;

cout << " Centimeters equals " << num * cm << " Inches";
}

else if(menu_char == 'm') {

cout << "\nType in a number in Meters ";

cin >> num;

cout << "\nNumber of Yards in " << num;

cout << " Meters equals " << num * m << " Yards";
}

else if(menu_char == 'k') {

cout << "\nType in a number in Kilometers ";

cin >> num;

cout << "\nNumber of Miles in " << num;

cout << " Kilometers equals " << num * km << " Miles";
}

else

cout << "\nError...choose c, m, or k";

return 0;
}
Find Output:

39
Lab Manual Programming Fundmental with C++

Example: Nested

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
int a = 100;
int b = 200;

// check the boolean condition


if( a == 100 ) {
// if condition is true then check the following
if( b == 200 ) {
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;

return 0;}

Example
// 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;

40
Lab Manual Programming Fundmental with C++

Output 1

Enter an integer: 35
The number is positive.
This line is always printed.

Output 2

Enter an integer: -35


The number is negative.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.

Example

// C program to illustrate nested-if statement


#include <iostream>
using namespace std;
int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
cout<<("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
cout<< ("i is smaller than 12 too\n");
else
cout<< ("i is greater than 15");
}

return 0;
}
Output
i is smaller than 15
i is smaller than 12 too

Example
41
Lab Manual Programming Fundmental with C++

Example of Conditional Operator

// C Program to illustrate the use of conditional operator


#include <iostream>
using namespace std;

// driver code
int main()
{

int var;
int flag = 0;

// using conditional operator to assign the value to var


// according to the value of flag
var = flag == 0 ? 25 : -25;
cout<<("Value of var when flag is 0: %d\n", var);

// changing the value of flag


flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
cout<< (“Value of var when flag is NOT 0: %d”, var);

return 0;
}
Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25

Example

// C Program to Calculate Grade According to marks


// using the if else if ladder
#include <iostream>
using namespace std;
int main()
{
int marks = 91;
if (marks <= 100 && marks >= 90)
cout<< ("A+ Grade");
else if (marks < 90 && marks >= 80)
cout<< ("A Grade");
else if (marks < 80 && marks >= 70)
cout<< ("B Grade");
else if (marks < 70 && marks >= 60)
cout<< ("C Grade");
else if (marks < 60 && marks >= 50)
cout<< ("D Grade");
else
cout<<("F Failed");
return 0;
}
Output
A+ Grade
42
Lab Manual Programming Fundmental with C++

Example
#include <bits/stdc++.h>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

if (n % 2 == 0) {
cout << "Even" << endl;
}
else {
cout << "Odd" << endl;
}

return 0;
}

Output
Enter a number: Even

Example Ternary operator

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

int main() {
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
return 0;
}

Output
Good Evening

Example Nested Ternary Operators

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

int main() {
int number = 0;
string result;

// nested ternary operator to find whether


43
Lab Manual Programming Fundmental with C++

// number is positive, negative, or zero


result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

cout << "Number is " << result;

return 0;
}

Output

Number is Zero

Example Logical Oprators

&& AND

The AND ( && ) operator can be used in a multiple conditional “if” statement. Note the parenthesis
used to make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;

if( (var1 < var2) && (var3 > var1) //if condition1 AND condition2 is true

cout << "do this"; //then do the cout statement

|| OR

The OR ( || ) operator can be used in a multiple conditional “if” statement. Note the parenthesis used to
make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;

if( (var1 < var2) || (var1 > var3) ) //if condition1 OR condition2 is true

cout << "do this"; //then do the cout statement

! NOT

The NOT ( ! ) operator isn’t used as much, but can still make itself useful. Note the parenthesis used to
make each condition more clear to the programmer.

int var1=7;
int var2=11;
int var3=20;
bool status=false;

if( !status && (var3 > var2) ) //if status is NOT true AND condition is true

44
Lab Manual Programming Fundmental with C++

cout << "do this"; //then do the cout statement

Example
#include <iostream>
using namespace std;

int main()
{
int a = 1, b = 3, c = 2;

if (a == b) {

if (c > b)

cout << "c is Greater Than b";

else if ((a == b) && (b != c))

cout << "a equals b and b does not equal c";

else

cout << "The condition was false";


}

else

cout << "a does not equal b";


return 0;

}
Output
a does not equal b

Example Modified Code

#include <iostream>
using namespace std;

int main()
{
int no = 8;

(no & 1 && cout << "odd" )|| cout << "even";

return 0;
}
Output
45
Lab Manual Programming Fundmental with C++

even

Task
• Take no from User and Check Whether Number is Even or Odd using if else
• Check Whether Number is Even or Odd without using If-else keyword
• Check Vowel or a Consonant Manually (Five alphabets a, e, i, o and u are known as vowels. All
other alphabets except these 5 alphabets are known as consonants.)
• Find Largest Number Using if...else Statement ( In this program, the user is asked to enter three
numbers this program finds out the largest number among three numbers entered by user and
displays it with a proper message.)

Week 5 Task with C++

46
Lab Manual Programming Fundmental with C++

Contents Covered: 1. Using switch and break statements, enum

C++ switch..case Statement

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

You can do the same thing with the if...else statement. However, the syntax of the switch statement is
much easier to read and write.

switch (expression) {
case constant1:
// code to be executed if
// 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

/ C++ program to demonstrate syntax of switch


#include <iostream>
using namespace std;

// Driver Code
int main()
{
// switch variable
char x = 'A';

// switch statements
switch (x) {
case 'A':
cout << "Choice is A";
break;
case 'B':
cout << "Choice is B";
break;
case 'C':
cout << "Choice is C";
break;
default:
cout << "Choice other than A, B and C";
break;
}
return 0;
}
47
Lab Manual Programming Fundmental with C++

Output
Choice is A

Example

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
char grade = 'D';

switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}

This would produce the following result −

You passed
Your grade is D

Example

// C Program to demonstrate the behaviour of switch case


// without break
#include <stdio.h>

int main()
{

int var = 2;

// switch case without break


switch (var) {

48
Lab Manual Programming Fundmental with C++

case 1:
printf("Case 1 is executed.\n");
case 2:
printf("Case 2 is executed.\n");
case 3:
printf("Case 3 is executed.\n");
case 4:
printf("Case 4 is executed.");
}
return 0;
}
Output
Case 2 is executed.
Case 3 is executed.
Case 4 is executed.

Example

/ C program to illustrate the use of nested switch


#include <iostream>
using namespace std;

int main()
{

int var1 = 1;
int var2 = 0;

// outer switch
switch (var1) {
case 0:
cout << "Outer Switch Case 0\n";
break;
case 1:
cout << "Outer Switch Case 1\n";
// inner switch
switch (var2) {
case 0:
cout << "Inner Switch Case 0\n";
break;
}
break;
default:
cout << "Default Case of Outer Loop";
break;
}

return 0;
}
Output
Outer Switch Case 1
Inner Switch Case 0

Example Enum

#include <iostream>
using namespace std;

49
Lab Manual Programming Fundmental with C++

int main()
{
enum color {RED, GREEN, BLUE};
switch (RED)
{
case RED:
cout << "red\n";
break;
case GREEN:
cout << "green\n";
break;
case BLUE:
cout << "blue\n";
break;
}

return 0;

Output

red

Example

#include <iostream>

using namespace std;

int main()
{
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";

enum level {easy = 1, normal, hard};


int choice;

cout << "Choice: ";


cin >> choice;

switch (choice)
{
case easy:
cout << "You picked Easy." << endl;
break;
case normal:
cout << "You picked Normal." << endl;
break;
case hard:
cout << "You picked Hard." << endl;
break;
default:
cout << "You made an illegal choice." << endl;
}
50
Lab Manual Programming Fundmental with C++

cout << "Press ENTER to continue...";

system("pause");

return 0;
}

Find output

Task

• Whats ths Issue with this code and how to correct it

#include <iostream>
using namespace std;

int main()
{
char marks;

cout << "Enter your Marks: " << endl;

cin >> marks;

switch (marks) {

case 'marks<=100 && marks>=90':

cout << "Your Grade Is A" << endl;

break;

case'marks<90 && marks>=75':

cout << "Your Grade Is B" << endl;

break;

case'marks<75 && marks>=50':

cout << "Your Grade Is C" << endl;

break;

case'marks<50 && marks>=0':

cout << "You Failed!" << endl;

break;

default:

cout << "Invalid number" << endl;

51
Lab Manual Programming Fundmental with C++

return 0;

• Program to build a simple calculator using switch Statement

According to the Output

Output 1

Enter an operator (+, -, *, /): +


Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *


Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Week 6 Task with C++


Contents Covered: Loops, While Loop
52
Lab Manual Programming Fundmental with C++

In Previous labs we have seen the use of conditional statements, now getting one step forward, sometimes
there is a need to perform some operation more than once or (say) n number of times. Loops come into
use when we need to repeatedly execute a block of statements. For example: Suppose we want to print
“Hello World” 10 times. This can be done in two ways as shown below:

Manual Method (Iterative Method):

Manually we have to write cout for the C++ statement 10 times. Let’s say you have to write it 20 times
(it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it
would be really hectic to re-write the same statement again and again. So, here loops have their role. This
is represented by the code written as follows.

// C++ program for printing Hello World Manually

#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}

Using Loops:

In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below. In computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached. That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.

// C++ program for printing Hello World using LOOP

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

53
Lab Manual Programming Fundmental with C++

There are 3 types of loops in C++.

1. for loop
2. while loop
3. do...while loop

C++ While Loop:

In this Lab, we will learn the syntax of while loop in C++, its algorithm, flowchart, then some examples
illustrating the usage of it. Later we shall go through Infinite While Loop and Nested While Loop.
A while loop statement repeatedly executes the code block within as long as the condition is true. The
moment the condition becomes false, the program will exit the loop. While Loop in C++ is used in
situations where we do not know the exact number of iterations of the loop beforehand.

Note: The while loop might not ever run. If the condition is initially false, the code block will be skipped.

Syntax of While Loop:

Following is the syntax of while loop in C++.

while (condition) {
// statement(s)
}

At the start of while loop execution, the condition is checked. If the condition is true, statement(s) inside
while block are executed. The condition is checked again. If it evaluates to true, the statement(s) inside
the while loop are executed. This cycle goes on. If at all, the condition evaluates to false, execution comes
out of while loop, meaning while loop is completed. And the program continues with the execution of
statements after while loop if any. This working is shown in the figure below:

54
Lab Manual Programming Fundmental with C++

Algorithm for While Loop:

Following would be the algorithm of while loop.


1. Start.
2. Check the condition. If the condition is false, go to step 4.
3. Execute statement(s). Go to step 2.
4. Stop.

You have to take care of the initialization and update of the variables present in condition. And make
sure that the condition would break after a definite number of iterations. If the condition is never going
to be false, then the while loop is going to execute indefinitely.

Flow Diagram for While Loop:

Following is the flow chart of flow diagram of while loop in C++.

Infinite Loop

An infinite loop in C++ is a loop that continues to execute indefinitely. This often occurs when the loop's
termination condition is never met. Here's an example of an infinite loop in C++ using a while loop:

#include <iostream>
using namespace std;
int main() {
while (true) {
cout << "This is an infinite loop!" << endl;
}
// The code below the loop will never be reached
cout << "This code is unreachable." << endl;
return 0;
}
55
Lab Manual Programming Fundmental with C++

In this example, the while (true) statement creates an infinite loop because the condition is always true.
The loop will continue to print "This is an infinite loop!" to the console without ever terminating.

Output:

This is an infinite loop!


This is an infinite loop!
This is an infinite loop!
...

The code below the loop will never be executed because the loop is infinite.

It's important to avoid unintentional infinite loops in your code as they can lead to programs that don't
behave as expected and may become unresponsive. Always ensure that your loops have appropriate
termination conditions.

Example 1: Printing 1 to 5 numbers

In this example, we shall write a while loop that prints numbers from 1 to 5 . The while loop contains
statement to print a number, and the condition checks if the number is within the limits.

C++ Code:

#include <iostream>
using namespace std;
int main() {
int n = 5;
int i = 1;
while (i<=n) {
cout << i << "\n";
i++;
}
}

Output:

1
2
3
4
5

Example 2: While Loop to Compute Factorial

In this example, we shall use while loop to compute factorial of a number.

C++ Code:
56
Lab Manual Programming Fundmental with C++

#include <iostream>
using namespace std;
int main() {
int n = 5;
int factorial = 1;
int i = 1;
while (i<=n) {
factorial *= i;
i++;
}
cout << factorial;
}

Output:

120

Exercise 1.1

Write a C++ program to print all even numbers between 1 to 100 using while loop.
Sample output:
2
4
6
8
.
.
.
100

Solution:
#include <iostream>
using namespace std;
int main() {
int number = 1;

// Using a while loop to print even numbers between 1 to 100


while (number <= 100) {
if (number % 2 == 0) {
cout << number << endl;
}
number++; // Incrementing the number
}

return 0;
}
57
Lab Manual Programming Fundmental with C++

Exercise 1.2

Write a C++ program that asks the user to type 10 integers. The program must compute how many even
and odd numbers were entered along with numbers that are divisible by 7.
Sample output:
Enter 10 integers :
1
2
3
4
5
6
7
8
9
10
Number of even numbers: 5
Number of odd numbers: 5
Numbers divisible by 7: 1

Solution:
#include <iostream>
using namespace std;
int main() {
int number;
int evenCount = 0, oddCount = 0, divisibleBy7Count = 0;

cout << "Enter 10 integers:\n";

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


cin >> number;

// Checking if the number is even or odd


if (number % 2 == 0)
evenCount++;
else
oddCount++;

// Checking if the number is divisible by 7


if (number % 7 == 0)
divisibleBy7Count++;
}

cout << "Number of even numbers: " << evenCount << endl;
cout << "Number of odd numbers: " << oddCount << endl;
cout << "Numbers divisible by 7: " << divisibleBy7Count << endl;

return 0;
58
Lab Manual Programming Fundmental with C++

Exercise 1.3

Write a C++ program to print the Fibonacci sequence up to a specified number of terms entered by the
user using a while loop.

Sample output:
Enter the number of Fibonacci terms: 10
Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Solution:
#include <iostream>
using namespace std;
int main() {
int numTerms;

// Prompt the user to enter the number of terms


cout << "Enter the number of Fibonacci terms: ";
cin >> numTerms;

// Initialize variables for Fibonacci sequence


int first = 0, second = 1, next, count = 2;

// Start with the first two terms


// Print the first two terms of the Fibonacci sequence
cout << "Fibonacci Sequence: " << first << ", " << second;

// Generate and print subsequent terms using a while loop


while (count < numTerms) {
next = first + second;
cout << ", " << next;
first = second;
second = next;
++count;
}

cout << endl;

return 0;
}

Exercise 1.4

Develop a number guessing game in C++ where the program generates a random number between 1 and
100. The user then tries to guess the number. The program should provide hints like "too high" or "too
low" until the user guesses the correct number. Use a while loop to repeatedly prompt the user for guesses.

59
Lab Manual Programming Fundmental with C++

Sample output:
Welcome to the Number Guessing Game!
Try to guess the secret number between 1 and 100.
Enter your guess: 76
Too low! Try again.
Enter your guess: 80
Too low! Try again.
Enter your guess: 90
Too low! Try again.
Enter your guess: 96
Too low! Try again.
Enter your guess: 97
Too low! Try again.
Enter your guess: 99
Too high! Try again.
Enter your guess: 98
Congratulations! You guessed the correct number in 7 attempts.

Solution:
#include <iostream>
#include <cstdlib> // For rand() and srand() functions
#include <ctime> // For time()

using namespace std;

int main() {
// Seed the random number generator
srand(time(nullptr));

// Generate a random number between 1 and 100


int secretNumber = rand() % 100 + 1;

int guess;
int attempts = 0;

cout << "Welcome to the Number Guessing Game!\n";


cout << "Try to guess the secret number between 1 and 100.\n";

// Start the guessing loop


while (true) {
cout << "Enter your guess: ";
cin >> guess;
attempts++;

// Check if the guess is correct


if (guess == secretNumber)
{
cout << "Congratulations! You guessed the correct number in " <<
attempts << " attempts.\n";

break; // Exit the loop if the guess is correct


60
Lab Manual Programming Fundmental with C++

}
else if (guess < secretNumber)
{
cout << "Too low! Try again.\n";
}
else {
cout << "Too high! Try again.\n";
}
}

return 0;
}

Exercise 1.5

Write a C++ program that prompts the user to enter a positive integer. Use a while loop to print the
multiplication table for that number up to 10.

Sample output:
Enter a positive integer: -3
Please enter a positive integer: 3
Multiplication table for 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30

Solution:
#include <iostream>
using namespace std;
int main() {
int number;

// Prompting the user to enter a positive integer


cout << "Enter a positive integer: ";
cin >> number;

// Checking if the input is valid


while (number <= 0) {
cout << "Please enter a positive integer: ";
cin >> number;
61
Lab Manual Programming Fundmental with C++

// Printing the multiplication table


int i = 1;
cout << "Multiplication table for " << number << ":" << endl;
while (i <= 10) {
cout << number << " x " << i << " = " << number * i << endl;
i++;
}

return 0;
}

Exercise 1.6

Write a program that prompts the user for a number and then determines if the number is prime using a
while loop. (Hint: A prime number has exactly two factors: 1 and itself).
Sample output 1:
Enter a number: 3
3 is a prime number.

Sample output 2:
Enter a number: 34
34 is not a prime number.

Solution:
#include <iostream>
using namespace std;
int main() {
int number;
bool isPrime = true;

// Prompting the user to enter a number


cout << "Enter a number: ";
cin >> number;

// Checking if the number is less than 2


if (number < 2)
{
isPrime = false;
}
else
{
// Starting from 2, check if the number is divisible by any number
up to its square root

int i = 2;
while (i * i <= number)
{
62
Lab Manual Programming Fundmental with C++

if (number % i == 0)
{
isPrime = false;
break;
}
i++;
}
}

// Output whether the number is prime or not


if (isPrime)
{
cout << number << " is a prime number." << endl;
}
else
{
cout << number << " is not a prime number." << endl;
}

return 0;
}

Exercise 1.6

Write a program that reads a list of integers from the user until they enter 0. Use a while loop to
calculate the average of the positive numbers entered.
Sample output:
Enter integers (enter 0 to stop):
3
2
4
5
6
0
Average of the positive numbers entered: 4

Solution:
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
int count = 0;

// Prompting the user to enter integers until they enter 0


cout << "Enter integers (enter 0 to stop):" << endl;
cin >> number;

// Calculating the sum and count of positive numbers


while (number != 0)

63
Lab Manual Programming Fundmental with C++

{
if (number > 0)
{
sum += number;
count++;
}
cin >> number; // Read the next number
}

// Calculating and displaying the average


if (count > 0)
{
double average = sum / count;
cout << "Average of the positive numbers entered: " << average <<
endl;
}
else
{
cout << "No positive numbers entered." << endl;
}

return 0;
}

Week 6 Task with C++


Contents Covered: Do while loop, difference between while and do while

In Previous labs we have seen the use of while loops, now the next loop in line is do…while loop.
The do…while in C++ is a loop statement used to repeat some part of the code till the given condition is
fulfilled. It is a form of an exit-controlled or post-tested loop where the test condition is checked after
executing the body of the loop. Due to this, the statements in the do…while loop will always be executed
at least once no matter what the condition is.

Syntax of do…While Loop:

Following is the syntax of do…while loop in C++.

do{
Statement(s)
}while(condition);
64
Lab Manual Programming Fundmental with C++

The body of the loop is executed first. Then the condition is evaluated. If the condition evaluates to true,
the body of the loop inside the do statement is executed again. The condition is evaluated once again. If
the condition evaluates to true, the body of the loop inside the do statement is executed again. This process
continues until the condition evaluates to false. Then the loop stops.

Note: Notice the semi – colon(“;”) in the end of loop.

Algorithm for do…While Loop:

Following would be the algorithm of while loop.


1. Control falls into the do-while loop.
2. The statements inside the body of the loop get executed.
3. Updation takes place.
4. The flow jumps to Condition
5. Condition is tested.
a. If the Condition yields true, go to Step 6.
b. If the Condition yields false, the flow goes outside the loop
6. The flow goes back to Step 2.
7. The do-while loop has been ended and flow has gone outside the loop.

Flow Diagram for do…While Loop:

Following is the flow chart of flow diagram of do…while loop in C++.

65
Lab Manual Programming Fundmental with C++

Difference between while and do…while loop

In C++ and many other programming languages, while and do...while loops are used for iteration, but
they have some differences in their behavior:
• Condition Evaluation:
In a while loop, the condition is evaluated before the loop body is executed. If the condition is false
initially, the loop body may never execute. In a do...while loop, the condition is evaluated after the loop
body is executed. This guarantees that the loop body will execute at least once, regardless of the
condition's initial value.
• Entry Control vs. Exit Control:
while loops are called entry-controlled loops because the condition is evaluated before entering the loop
body. If the condition is false initially, the loop body won't execute at all. do...while loops are exit-
controlled loops because the condition is evaluated after executing the loop body. This means that the
loop body will execute once before the condition is checked.

Syntax:
while loop syntax:
while (condition) {
// loop body
}
do...while loop syntax:
do {
// loop body
} while (condition);

• Use a while loop when you want to execute the loop body zero or more times, based on the condition.

66
Lab Manual Programming Fundmental with C++

• Use a do...while loop when you want to execute the loop body at least once, regardless of the condition,
and then continue execution as long as the condition is true.
Here's a basic example illustrating the difference:
#include <iostream>
using namespace std;
int main() {
int i = 5;

// while loop
while (i < 5) {
cout << "While loop: " << i << endl;
i++;
}

i = 5;
// do...while loop
do {
cout << "Do...While loop: " << i << endl;
i++;
} while (i < 5);

return 0;
}

In this example, the while loop doesn't execute because the condition (i < 5) is false initially. However,
the do...while loop executes once before checking the condition, so it prints "Do...While loop: 5" even
though the condition is false.

Example 1: Printing 1 to 5 numbers

In this example, we shall write a while loop that prints numbers from 1 to 5 . The do…while loop contains
statement to print a number, and the condition checks if the number is within the limits.

C++ Code:

#include <iostream>
using namespace std;
int main() {
int n = 5;
int i = 1;
do {
cout << i << "\n";
i++;
67
Lab Manual Programming Fundmental with C++

} while (i<=n);
}

Output:

1
2
3
4
5

Example 2: do…While Loop to Compute Factorial

In this example, we shall use while loop to compute factorial of a number.

C++ Code:

#include <iostream>
using namespace std;
int main() {
int number;
int factorial = 1;

// Prompting the user to enter a number


cout << "Enter a positive integer: ";
cin >> number;

// Checking if the input is valid


if (number < 0) {
cout << "Error: Please enter a positive integer." << endl;
return 1;
}

// Calculating factorial using a do-while loop


int i = 1;
do {
factorial *= i;
i++;
} while (i <= number);

// Displaying the factorial


cout << "Factorial of " << number << " is: " << factorial << endl;

return 0;
}
Output:

Enter a positive integer: 3


Factorial of 3 is: 6

68
Lab Manual Programming Fundmental with C++

Exercise 1.1

Write a program to print in the descending order first twenty natural numbers on the computer
screen by using “do-while” loop.

Sample output:
First twenty natural numbers in descending order:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Solution:
#include <iostream>
using namespace std;
int main() {
int number = 20; // Starting number

// Printing the first twenty natural numbers in descending order


cout << "First twenty natural numbers in descending order:" << endl;
do {
cout << number << " ";
number--;
} while (number > 0);

cout << endl;


return 0;
}

Exercise 1.2

Simulate a basic ATM with a do-while loop. The program starts with a specific balance (up to user).
The user can perform withdrawals (check for sufficient funds) or deposits. Use a do-while loop to keep
asking for transactions (withdrawal/deposit) until the user chooses to exit.
Sample output:
Welcome to the ATM!

Your current balance is: $1000


Enter 'W' for withdrawal, 'D' for deposit, or 'E' to exit: w
Enter the amount to withdraw: $100
Withdrawal successful. New balance: $900

Your current balance is: $900


Enter 'W' for withdrawal, 'D' for deposit, or 'E' to exit: d
Enter the amount to deposit: $10
Deposit successful. New balance: $910
69
Lab Manual Programming Fundmental with C++

Your current balance is: $910


Enter 'W' for withdrawal, 'D' for deposit, or 'E' to exit: e
Exiting. Thank you for using the ATM!

Solution:
#include <iostream>
using namespace std;
int main() {
double balance = 1000.0; // Starting balance
char choice;
double amount;

cout << "Welcome to the ATM!" << endl;

// Main loop for ATM transactions


do {
cout << "\nYour current balance is: $" << balance << endl;
cout << "Enter 'W' for withdrawal, 'D' for deposit, or 'E' to exit:
";
cin >> choice;

switch (choice) {
case 'W' | ‘w’:
cout << "Enter the amount to withdraw: $";
cin >> amount;
if (amount > balance)
{
cout << "Insufficient funds!" << endl;
}
else
{
balance -= amount;
cout << "Withdrawal successful. New balance: $" <<
balance << endl;
}
break;

case 'D' | 'd':


cout << "Enter the amount to deposit: $";
cin >> amount;
balance += amount;
cout << "Deposit successful. New balance: $" << balance <<
endl;
break;
case 'E' | 'e':

cout << "Exiting. Thank you for using the ATM!" << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 'E' && choice != 'e');

70
Lab Manual Programming Fundmental with C++

return 0;
}

Exercise 1.3

Write a program in C++ to find the perfect numbers between 1 and 500. (Hint: A perfect number is a
positive integer that is equal to the sum of its positive divisors, excluding the number itself1234. For
example, 6 is a perfect number because 1 + 2 + 3 = 6 )

Sample output:
Perfect numbers between 1 and 500:
6
28
496

Solution:
#include <iostream>
using namespace std;
int main() {
int number = 1;

cout << "Perfect numbers between 1 and 500:" << endl;


do {
int sum = 0;
int divisor = 1;

while (divisor < number) {


if (number % divisor == 0) {
sum += divisor;
}
divisor++;
}

if (sum == number) {
cout << number << endl;
}

number++;
} while (number <= 500);

return 0;
}

Exercise 1.4

Write a C++ program that prompts the user for a positive odd number. Use a do-while loop to find and
print the sum of all even numbers between 2 (inclusive) and the entered odd number (exclusive).

71
Lab Manual Programming Fundmental with C++

Sample output 1:
Enter a positive odd number: 45
Sum of all even numbers between 2 and 45 (exclusive): 506

Sample output 2:
Enter a positive odd number: 32
Invalid input! Please enter a positive odd number.
Enter a positive odd number: 11
Sum of all even numbers between 2 and 11 (exclusive): 30

Solution:
#include <iostream>
using namespace std;
int main() {
int oddNumber;

// Prompting the user for a positive odd number


do {
cout << "Enter a positive odd number: ";
cin >> oddNumber;

// Checking if the input is valid


if (oddNumber <= 0 || oddNumber % 2 == 0) {
cout << "Invalid input! Please enter a positive odd number." <<
endl;
}
} while (oddNumber <= 0 || oddNumber % 2 == 0);

// Finding and printing the sum of all even numbers between 2 and the
entered odd number
int sum = 0;
int evenNumber = 2;
while (evenNumber < oddNumber) {
sum += evenNumber;
evenNumber += 2;
}

cout << "Sum of all even numbers between 2 and " << oddNumber << "
(exclusive): " << sum << endl;

return 0;
}

Exercise 1.5

72
Lab Manual Programming Fundmental with C++

Write a program in C++ to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... +
(n*n).

Sample output:
Enter the value of n: 6
The sum of the series is: 91

Solution:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;

int sum = 0;
int i = 1;

do {
sum += i * i;
i++;
} while (i <= n);

cout << "The sum of the series is: " << sum << endl;

return 0;
}

Exercise 1.6

Write a C++ program to make such a pattern like a pyramid with numbers increased by 1.
Sample output:
Display such a pattern like a pyramid with numbers increased by 1:
-----------------------------------------------------------------------
Input number of rows: 4
1
2 3
4 5 6
7 8 9 10

Solution:
#include <iostream>
#include <string>

73
Lab Manual Programming Fundmental with C++

using namespace std;


int main() {
int i, j, spc, rows, k, t = 1;

cout << "\n\n Display such a pattern like a pyramid with numbers
increased by 1:\n";
cout << "---------------------------------------------------------------
--------\n";
cout << " Input number of rows: ";
cin >> rows;

spc = rows + 4 - 1;

i = 1;
do {
k = spc;
do {
cout << " ";
k--;
} while (k >= 1);

j = 1;
do {
cout << t++ << " ";
j++;
} while (j <= i);

cout << endl;


spc--;
i++;
} while (i <= rows);

return 0;
}

Exercise 1.7

Write a C++ program to display a pattern like a diamond.


Sample output:
Display the pattern like a diamond:
----------------------------------------
Input number of rows (half of the diamond): 5

*
***
*****
*******
*********
*******
*****
***
74
Lab Manual Programming Fundmental with C++

*
Solution:
#include <iostream>
using namespace std;
int main() {
int i, j, r;

cout << "\n\n Display the pattern like a diamond:\n";


cout << "----------------------------------------\n";
cout << " Input number of rows (half of the diamond): ";
cin >> r;

i = 0;
do {
j = 1;
do {
cout << " ";
j++;
} while (j <= r - i);

j = 1;
do {
cout << "*";
j++;
} while (j <= 2 * i - 1);

cout << endl;


i++;
} while (i <= r);

i = r - 1;
do {
j = 1;
do {
cout << " ";
j++;
} while (j <= r - i);

j = 1;
do {
cout << "*";
j++;
} while (j <= 2 * i - 1);

cout << endl;


i--;
} while (i >= 1);

return 0;
}

75
Lab Manual Programming Fundmental with C++

Week 7 For Loop (Basics)


Contents Covered: • Basic understandings of For loop
• Pre-condition for loop
• Different possible expression used in for loop

Exercise 1.1
Write a program in C++ to find the first 10 natural numbers
Note : Here, in this example you are required to print the first 10 natural numbers using a for loop.
Sample output:

76
Lab Manual Programming Fundmental with C++

Solution:

#include <iostream> // Preprocessor directive to include the input/output stream


header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int i; // Declare an integer variable 'i'

cout << "\n\n Find the first 10 natural numbers:\n"; // Display a message to
find the first 10 natural numbers
cout << "---------------------------------------\n"; // Display a separator
line
cout << " The natural numbers are: \n"; // Display a message indicating the
list of natural numbers

// Loop to print the first 10 natural numbers


for (i = 1; i <= 10; i++)
{
cout << i << " "; // Output each natural number followed by a space
}
cout << endl; // Move to the next line after printing the numbers
}
Exercise 1.2

Write a program in C++ to find the sum of the first 10 natural numbers.

Sample output:

77
Lab Manual Programming Fundmental with C++

Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int i, sum = 0; // Declare integer variables 'i' and 'sum' and initialize 'sum'
to 0

cout << "\n\n Find the first 10 natural numbers:\n"; // Display a message to
find the first 10 natural numbers
cout << "---------------------------------------\n"; // Display a separator
line
cout << " The natural numbers are: \n"; // Display a message indicating the
list of natural numbers

// Loop to print the first 10 natural numbers and calculate their sum
for (i = 1; i <= 10; i++)
{
cout << i << " "; // Output each natural number followed by a space
sum = sum + i; // Calculate the sum by adding the current number 'i' to
'sum'
}
cout << "\n The sum of first 10 natural numbers: " << sum << endl; // Display
the sum of the first 10 natural numbers
}

Exercise 1.3
Write a program in C++ to check whether a number is prime or not.

78
Lab Manual Programming Fundmental with C++

Sample output:

Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int num1, ctr = 0; // Declaration of integer variables 'num1' and 'ctr', 'ctr'
initialized to 0

cout << "\n\n Check whether a number is prime or not:\n"; // Display a message
indicating the purpose
cout << "--------------------------------------------\n"; // Display a
separator line
cout << " Input a number to check prime or not: "; // Prompting the user to
input a number
cin >> num1; // Reading the input number entered by the user

for (int a = 1; a <= num1; a++) // Start of a 'for' loop from 1 to the input
number 'num1'
{
if (num1 % a == 0) // Check if 'num1' is divisible by 'a' without any
remainder
{
ctr++; // Increment 'ctr' when 'num1' is divisible by 'a'
}

79
Lab Manual Programming Fundmental with C++

if (ctr == 2) // Check if 'ctr' is equal to 2 (prime numbers have only two


factors: 1 and the number itself)
{
cout << " The entered number is a prime number. \n"; // Display a message
indicating that the number is prime
}
else {
cout << " The number you entered is not a prime number. \n"; // Display a
message indicating that the number is not prime
}
}

Exercise 1.4
Write a program in C++ to find the factorial of a number.

Sample output:

Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{

int num1, factorial = 1; // Declaration of integer variables 'num1' and


'factorial' initialized to 1

cout << "\n\n Find the factorial of a number:\n"; // Display a message


indicating the purpose
80
Lab Manual Programming Fundmental with C++

cout << "------------------------------------\n"; // Display a separator line


cout << " Input a number to find the factorial: "; // Prompting the user to
input a number

cin >> num1; // Reading the number entered by the user

for (int a = 1; a <= num1; a++) // Loop to calculate the factorial

factorial = factorial * a; // Calculating factorial by multiplying


'factorial' with 'a'

cout << " The factorial of the given number is: " << factorial << endl; //
Displaying the factorial of the entered number

return 0; // Indicating successful completion of the program

Exercise 1.5:

Write a program in C++ to find the sum of the digits of a given number.

Sample output:

81
Lab Manual Programming Fundmental with C++

Solution:

#include <iostream> // Preprocessor directive to include the input/output stream


header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int num1, num2, r, sum = 0; // Declaration of integer variables 'num1', 'num2',
'r', and 'sum'

// Display a message to find the sum of digits of a given number


cout << "\n\n Find the sum of digits of a given number:\n";
cout << "----------------------------------------------\n";

// Prompt the user to input a number


cout << " Input a number: ";
cin >> num1; // Reading the number entered by the user

num2 = num1; // Store the original number in 'num2' for displaying later

// Loop to extract each digit and calculate their sum


while (num1 > 0)
{
r = num1 % 10; // Extract the rightmost digit of 'num1'
num1 = num1 / 10; // Remove the rightmost digit from 'num1'
sum = sum + r; // Add the extracted digit to the 'sum' variable
}

// Display the sum of digits of the original number 'num2'


cout << " The sum of digits of " << num2 << " is: " << sum << endl;

return 0; // Indicating successful completion of the program


}

82
Lab Manual Programming Fundmental with C++

Test Exercise

Q1: Write a program in C++ to find the natural numbers between 90 to 100 and print them in reverse
order.
Sample output:
The natural numbers are:
100 99 98 97 96 95 94 93 92 91 90

Q2: Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.
Sample Output:
Input the first number: 25
Input the second number: 15
The Greatest Common Divisor is: 5

Q3: Write a program in C++ to find the perfect numbers between 1 and 500.
The perfect numbers between 1 to 500 are:
6
28
496

Q4: Write a program in C++ to display n terms of natural numbers and their sum.
Sample Output:
Input a number of terms: 7
The natural numbers upto 7th terms are:
1234567
The sum of the natural numbers is: 28

Q5: Write a program that will print the table of the user choice number. For example, if the user has given
the number 5, then the output will be:
5x1=5
5 x 2 = 10

83
Lab Manual Programming Fundmental with C++

5 x 3 = 15
5 x 4 = 20

5 x 10 = 50

84
Lab Manual Programming Fundmental with C++

Week 8 For Loop (Advanced)


Contents Covered: • Pre-condition for loop
• Different possible expression used in for loop
• Nested for loops

Exercise 1.1
Write a program in C++ to print the half star pyramid using nested for loop

Sample output:

Solution:

#include <iostream>
using namespace std;
int main()
{
int i, j, n;
cout << "Enter number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
cout << "* ";
}
//Ending line after each row
cout << "\n";
}
return 0;
}
Exercise 1.2

Write a program in C++ to print the following pattern using for loop
85
Lab Manual Programming Fundmental with C++

Solution:
#include <iostream>
using namespace std;

int main()
{
int rows, columns, number = 1, n = 5;

// first for loop is used to identify number of rows


for (rows = 0; rows <= n; rows++) {

// second for loop is used to identify number of


// columns and here the values will be changed
// according to the first for loop
for (columns = 0; columns < rows; columns++) {

// printing number pattern based on the number


// of columns
cout << number << " ";

// incrementing number at each column to print


// the next number
number++;
}

// print the next line for each row


cout << "\n";
}
return 0;
}

Exercise 1.3
Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.

86
Lab Manual Programming Fundmental with C++

Sample output:

Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int num1, num2, gcd; // Declaration of integer variables 'num1', 'num2', and
'gcd'

// Display a message to find the Greatest Common Divisor (GCD) of two numbers
cout << "\n\n Find the Greatest Common Divisor of two numbers:\n";
cout << "-----------------------------------------------------\n";

// Prompt the user to input the first number


cout << " Input the first number: ";
cin >> num1; // Reading the first number entered by the user

// Prompt the user to input the second number


cout << " Input the second number: ";
cin >> num2; // Reading the second number entered by the user

// Loop to find the Greatest Common Divisor (GCD) of num1 and num2
for (int i = 1; i <= num1 && i <= num2; i++)
{
if (num1 % i == 0 && num2 % i == 0) // Check if 'i' divides both num1 and
num2 evenly
{
gcd = i; // Update the 'gcd' variable with the current common divisor
}
}
87
Lab Manual Programming Fundmental with C++

// Display the Greatest Common Divisor (GCD) of the entered numbers


cout << " The Greatest Common Divisor is: " << gcd << endl;

return 0; // Indicating successful completion of the program


}

Exercise 1.4
Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.-
4! = 1*2*3*4 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
Also,
1! = 1
0! = 0
Write a C++ program to calculate factorial of a number.

Solution:
#include <iostream>
int main()
{
using namespace std;
int j,number;
cout << "Enter number" << "\n";
cin >> number;
int fact = 1;
for (j=1;j<=number;j++){
fact = fact*j;
}
cout << fact << "\n";
return 0;
}

Exercise 1.5:

Write a program in C++ to calculate the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... +
(1+2+3+4+...+n).

Sample output:

88
Lab Manual Programming Fundmental with C++

Solution:

#include <iostream> // Including the input/output stream header file

using namespace std; // Using the standard namespace to avoid writing std::

int main() // Start of the main function


{
int i, j, n, sum = 0, tsum; // Declaration of integer variables 'i', 'j', 'n',
'sum', and 'tsum'

// Display a message to find the sum of the series (1) + (1+2) + (1+2+3) +
(1+2+3+4) + ... + (1+2+3+4+...+n)
cout << "\n\n Find the sum of the series (1) + (1+2) + (1+2+3) + (1+2+3+4) +
... + (1+2+3+4+...+n):\n";
cout << "----------------------------------------------------------------------
--------------------\n";

// Prompt the user to input the value for the nth term of the series
cout << " Input the value for nth term: ";
cin >> n; // Read the value entered by the user

for (i = 1; i <= n; i++) // Outer loop to iterate from 1 to 'n'


{
tsum = 0; // Initializing 'tsum' to 0 for each iteration of the outer loop

for (j = 1; j <= i; j++) // Inner loop to calculate the partial sums for
each term of the series
{
sum += j; // Add 'j' to 'sum'
tsum += j; // Add 'j' to 'tsum' for the current term

cout << j; // Display the current value of 'j'

if (j < i) // Condition to print '+' for all values of 'j' except the
last one in each term
{
cout << "+"; // Display '+'
}
}

cout << " = " << tsum << endl; // Display the calculated partial sum for
the current term
89
Lab Manual Programming Fundmental with C++

// Display the total sum of the series


cout << " The sum of the above series is: " << sum << endl;

return 0; // Indicating successful completion of the program


}

Test Exercise

Q1: Write a program in C++ to print the inverted star pattern by taking the number of rows from the
user as shown below

Sample output:

Q2: Write a C++ program to print the following patterns

Q3: Write a program in C++ to display the cube of the number up to an integer.
Sample Output:
Input the number of terms : 5

90
Lab Manual Programming Fundmental with C++

Number is : 1 and the cube of 1 is: 1


Number is : 2 and the cube of 2 is: 8
Number is : 3 and the cube of 3 is: 27
Number is : 4 and the cube of 4 is: 64
Number is : 5 and the cube of 5 is: 125
Q4: Write a C++ program that displays the sum of n odd natural numbers.
Sample Output:
Input number of terms: 5
The odd numbers are: 1 3 5 7 9
The Sum of odd Natural Numbers upto 5 terms: 25
Q5: Write a C++ program to make such a pattern, like a pyramid, with a repeating number.
Sample Output:
Input number of rows: 5
1
22
333
4444
55555
Q6: Write a C++ program that prints all ASCII characters with their values.
Sample Output:
Input the starting value for ASCII characters: 65
Input the ending value for ASCII characters: 74
The ASCII characters:
65 --> A
66 --> B
67 --> C
68 --> D
69 --> E
70 --> F
71 --> G
91
Lab Manual Programming Fundmental with C++

72 --> H
73 --> I
74 --> J

92
Lab Manual Programming Fundmental with C++

Week 9 Task with C++


Contents Covered: Functions,
Functions Declaration and Definition, and
Function Calling

Functions:
A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main(), and all the most trivial programs can define additional functions. You can
divide up your code into separate functions. How you divide up your code among different functions is
up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function. The C++ standard library provides numerous built-in
functions that your program can call. For example, function strcat() to concatenate two strings, function
memcpy() to copy one memory location to another location and many more functions.
A function is knows as with various names like a method or a sub-routine or a procedure etc.

Defining a Function:
The general form of a C++ function definition is as follows:

A C++ function definition consists of a function header and a function body. Here are all the parts of a
function:
• Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
• Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the
function does.

Calling a Function:

While creating a C++ function, you give a definition of what the function has to do. To use a function,
you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when its return statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.

93
Lab Manual Programming Fundmental with C++

To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value.

Exercise 1.1
Write a C++ program that defines a function max to find and return the maximum value
between two integers.
Sample output:
Max value is : 200

Solution:
#include <iostream>

using namespace std;

// function returning the max between two numbers

int max(int num1, int num2)


{
// local variable declaration

int result;
if (num1 > num2)

result = num1;

else

result = num2;
return result;

int main ()
{
// local variable declaration:

int a = 100;

int b = 200;
int ret;
// calling a function to get max value.

ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;

}
94
Lab Manual Programming Fundmental with C++

Exercise 1.2
Write a C++ function calculatePolynomial that evaluates a polynomial expression of the form
ax^2 + bx + c given the values of a, b, c, and x. The function should take four parameters: the
coefficients a, b, and c, and the value of x. Demonstrate the usage of this function by calling it with
different sets of coefficients and x values.
Sample Output 1:
Enter the coefficient a: 3

Enter the coefficient b: 9


Enter the coefficient c: 7

Enter the value of x: 2

Result of the polynomial expression: 37

Sample Output 2:
Enter the coefficient a: 3

Enter the coefficient b: 7

Enter the coefficient c: 2


Enter the value of x: 3
Result of the polynomial expression: 50

Solution:
#include <iostream>
using namespace std;

// Function to calculate polynomial expression


double calculatePolynomial(double a, double b, double c, double x) {

return a * x * x + b * x + c;

int main() {

double a, b, c, x;

// Prompt the user to enter coefficients a, b, c, and value of x


cout << "Enter the coefficient a: ";

95
Lab Manual Programming Fundmental with C++

cin >> a;
cout << "Enter the coefficient b: ";

cin >> b;

cout << "Enter the coefficient c: ";

cin >> c;
cout << "Enter the value of x: ";

cin >> x;

// Evaluate polynomial expression using the function

double result = calculatePolynomial(a, b, c, x);

// Display the result


cout << "Result of the polynomial expression: " << result <<endl;

return 0;

Exercise 1.3
Write a C++ program that defines a function named isPrime which takes an integer as a parameter
and returns true if the number is prime and false otherwise.

Sample output 1:
Enter a number: 12
12 is not a prime number.
Sample output 2:
Enter a number: 11
11 is a prime number.

Solution:
#include <iostream>
using namespace std;

bool isPrime(int num) {

if (num <= 1) {

96
Lab Manual Programming Fundmental with C++

return false; // Numbers less than or equal to 1 are not prime


}

// Check for divisibility from 2 to the square root of the number


for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) {
return false; // If the number is divisible by any number, it's not
prime
}
}

return true; // If no divisor is found, the number is prime


}

int main() {
int number;

// Prompt the user to enter a number


cout << "Enter a number: ";
cin >> number;

// Check if the number is prime using the isPrime function


if (isPrime(number)) {
cout << number << " is a prime number." << std::endl;
} else {
cout << number << " is not a prime number." << std::endl;
}

return 0;
}

Test Exercise

1. Write a C++ program that defines a function named reverseString which takes a string as a parameter
and returns the reverse of the input string.

Sample output:
Enter a string: ProgrammingFundamentals
Reversed string: slatnemadnuFgnimmargorP

2. Develop a C++ program that defines a function named isPalindrome which takes a string as a
parameter and returns true if the string is a palindrome (reads the same backward as forward), otherwise
returns false.

Sample output 1:
Enter a string: Iqra
"Iqra" is not a palindrome.
Sample output 2:
Enter a string: karak
97
Lab Manual Programming Fundmental with C++

"karak" is a palindrome.

3. Write a program that defines a function named countOccurrences which takes a large number and a
single digit as parameters and returns the number of occurrences of that digit in the number.

Sample Output:
Enter a large number: 23729202
Enter a single digit: 2
Number of occurrences of digit 2 in 23729202: 4

98
Lab Manual Programming Fundmental with C++

Week 9 Task with C++


Contents Covered: Parameters of Functions,
Argument Passing

Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
Call by value This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument
Call by pointer This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
Call by reference This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.

Exercise 1.1:
Write a C++ program that defines a function sum to calculate the sum of two integers. The function
takes two parameters, a and b, where b has a default value. Demonstrate the usage of this function by
calling it twice in the main function: once with both parameters provided, and once with only a provided,
relying on the default value of b. Display the total value after each function call.
Sample output:
Total value is : 300

Total value is : 120

Solution:
#include <iostream>
using namespace std;

int sum(int a, int b=20)


{

99
Lab Manual Programming Fundmental with C++

int result;
result = a + b;

return (result);

int main ()

// local variable declaration:

int a = 100;
int b = 200;

int result;
// calling a function to add the values.

result = sum(a, b);

cout << "Total value is :" << result << endl;

// calling a function again as follows.

result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}

Exercise 1.2
Write a C++ program that defines a function named swap which swaps the values of two integers.
After swapping, the program should print the values of a and b before and after the swap.

Sample output :
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Call by Value:
100
Lab Manual Programming Fundmental with C++

Solution:
#include <iostream>
using namespace std;

// function declaration
void swap(int x, int y);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b); //call by value
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}

Call by Pointers:

#include <iostream>
using namespace std;

// function declaration

void swap(int *x, int *y);

101
Lab Manual Programming Fundmental with C++

int main ()

// local variable declaration:

int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values.

* &a indicates pointer to a ie. address of variable a and


* &b indicates pointer to b ie. address of variable b.

*/
swap(&a, &b); //call by pointers

cout << "After swap, value of a :" << a << endl;

cout << "After swap, value of b :" << b << endl;

return 0;
}

Call by Reference:

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


102
Lab Manual Programming Fundmental with C++

swap(a, b); //call by reference


cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}

Test Exercise

1. Raising a number to a power p is the same as multiplying n by itself p times. Write a function called
power that takes two arguments, a double value for n and an int value for p, and return the result as double
value. Use default argument of 2 for p, so that if this argument is omitted the number will be squared.
Write the main function that gets value from the user to test power function.
Sample Output:
Enter number : 5
Enter exponent : 4
Result is 625
Result without passing exponent is 25

2. Write a function called zero_small() that has two integer arguments being passed by reference and sets
the smaller of the two numbers to 0. Write the main program to access the function.
Sample Output 1:
Enter first number : 23
Enter second number : 6
First number is : 23
Second number is : 0

Sample Output 2:

Enter first number : 23


Enter second number : 56
First number is : 0
Second number is : 56

3. Create a C++ program that defines a function modifyNumber which takes an integer parameter by
reference and modifies it by doubling its value. Demonstrate the usage of this function by modifying and
printing the value of 5 different numbers.

Sample Output:
Enter three Numbers:
103
Lab Manual Programming Fundmental with C++

3 6 9
Before modification, num1: 3
After modification, num1: 6
Before modification, num2: 6
After modification, num2: 12
Before modification, num3: 9
After modification, num3: 18

104
Lab Manual Programming Fundmental with C++

Week 10 Task with C++


Contents Covered: Return Type and Return Value
Inline Functions
Local and Global Variables

Return Type:
In programming, a return type refers to the data type of the value that a function is expected to return after
it completes its execution. Every function in C++ has a return type, which is specified in its function
declaration. The return type indicates the type of data that the function will produce as output when it is
called.

In C++, the return type of a function is declared before the function name in its prototype and definition.
It can be any valid data type in C++, including fundamental data types (int, float, double, char, etc.), user-
defined data types (structures, classes, enums), or even void if the function does not return any value.
Example:
int add(int a, int b); // Function prototype with return type 'int'

float calculateAverage(int arr[], int size); // Function prototype with return type 'float'

void greetUser(); // Function prototype with return type 'void'


Return Value:

A return value is the actual data that a function sends back to the caller after its execution is complete. It
represents the output or result produced by the function based on its computation or processing. The
return value is determined by the expression specified in the return statement within the function body.

When a function is called, it executes its statements and may produce a result that needs to be sent back
to the calling code. This result is conveyed through the return statement, which contains the value to be
returned. The return value is then received and used by the calling code to perform further operations or
assignments.

In C++, the return statement is used to explicitly specify the return value of a function. The return
statement typically includes an expression whose value is the return value of the function. If the return
type of the function is void, the return statement is optional, and the function may terminate without
returning a value.

Example:
int add(int a, int b) {
return a + b; // Return statement with the sum of 'a' and 'b' as the return value
}

float calculateAverage(int arr[], int size) {


float sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}
return sum / size; // Return statement with the average of elements as the return value
}
105
Lab Manual Programming Fundmental with C++

void greetUser() {
cout << "Hello, User!" << endl;
// No return statement needed in a void function
}

Exercise 1.1
Write a function which calculates & returns area of the circle. Take appropriate data types.
Sample output: Enter the radius of the circle: 5
The area of the circle with radius 5 is: 78.5397
Solution:
#include <iostream>
using namespace std;

// Function to calculate the area of a circle


double calculateArea(double radius) {
const double pi = 3.14159; // Define the value of pi
double area = pi * radius * radius; // Calculate the area using the formula: pi
* radius^2
return area; // Return the calculated area
}

int main() {
double radius;
cout << "Enter the radius of the circle: ";
cin >> radius;

// Call the calculateArea function with the radius as the argument and store
the return value
double circleArea = calculateArea(radius);

cout << "The area of the circle with radius " << radius << " is: " <<
circleArea << endl;

return 0;
}

Inline Function:
C++ provides inline functions to reduce the function call overhead. An inline function is a function that is
expanded in line when it is called. When the inline function is called whole code of the inline function gets
inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler
at compile time. An inline function may increase efficiency if it is small.

Example
inline return-type function-name(parameters)
{
// function code
}

106
Lab Manual Programming Fundmental with C++

When the program executes the function call instruction the CPU stores the memory address of the
instruction following the function call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes the function code, stores the function
return value in a predefined memory location/register, and returns control to the calling function. This
can become overhead if the execution time of the function is less than the switching time from the caller
function to called function (callee).

For functions that are large and/or perform complex tasks, the overhead of the function call is usually
insignificant compared to the amount of time the function takes to run. However, for small, commonly-
used functions, the time needed to make the function call is often a lot more than the time needed to
actually execute the function’s code. This overhead occurs for small functions because the execution
time of a small function is less than the switching time.

Exercise 1.2
Write a C++ program to calculate sqare of circle using inline function.
Sample Output 1:
Square of 5 is: 25

Solution:
#include <iostream>

// Inline function to calculate the square of a number

inline int square(int x) {


return x * x;

int main() {

int num = 5;
int squared = square(num); // The function call is replaced with the actual
code of the function

std::cout << "Square of " << num << " is: " << squared << std::endl;

return 0;
}

Local Variables

Variables defined within a function or block are said to be local to those functions.

107
Lab Manual Programming Fundmental with C++

• Anything between ‘{‘ and ‘}’ is said to inside a block.


• Local variables do not exist outside the block in which they are declared, i.e. they can not be
accessed or used outside that block.
• Declaring local variables: Local variables are declared inside a block.

Example:
Sample output: Age is: 18
// CPP program to illustrate
// usage of local variables
#include<iostream>
using namespace std;

void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
cout<<age;
}

int main()
{
cout<<"Age is: ";
func();

return 0;
}
Global Variables

As the name suggests, Global Variables can be accessed from any part of the program.

• They are available through out the life time of a program.


• They are declared at the top of the program outside all of the functions or blocks.
• Declaring global variables: Global variables are usually declared outside of all of the functions
and blocks, at the top of the program. They can be accessed from any portion of the program.

Example:
Sample Output:
5
10

// CPP program to illustrate


// usage of global variables
#include<iostream>
using namespace std;

// global variable
108
Lab Manual Programming Fundmental with C++

int global = 5;

// global variable accessed from


// within a function
void display()
{
cout<<global<<endl;
}

// main function
int main()
{
display();

// changing value of global


// variable from main function
global = 10;
display();
}

Test Exercise

1. Write a funcDon that receives integer base and exponent as funcDon arguments and
calculates the result of the expression and return results to main funcDon and display on console.
result=Base^exponent

2. Develop a C++ program C++ program that demonstrates the usage of an inline function to calculate the area
of a rectangle.

3. Develop a C++ program in C++ to simulate tracking a pet's age. The program should utilize local and
global variables effectively.

109
Lab Manual Programming Fundmental with C++

Week 11 and 12 Task with C++


Contents Covered: Pointers, Pointers of Arrays, Pointer constants and pointer variables,
Passing pointers asarguments, Pointer and functions, Basic concept of Pass
by reference

Exercise 11.1
Write a C++ program that demonstrates the use of pointers by declaring an integer variable 'num',
a pointer 'ptr' that points to the address of 'num', and a pointer 'ptr1' that points to the address of 'ptr'. The
program should display the value of 'num', the value pointed to by 'ptr', and the value pointed to by 'ptr1'.
Additionally, it should show both the actual memory addresses and the memory addresses accessed
through references. Explain the significance of each output in terms of memory management.
Sample output 1:
Value of Num: 34
Value of Ptr: 34
Value of Ptr1: 34
Actual Memory Address of Num: 0x61ff0c
Actual Memory Address of Ptr: 0x61ff08
Actual Memory Address of Ptr1: 0x61ff04
Memory Address of Num: 0x61ff0c
Reference Memory Address of Ptr: 0x61ff0c
Reference Memory Address of Ptr1: 0x61ff0c
Solution:
#include <iostream>

using namespace std;

int main() {
int num = 34;
int *ptr = &num;
int **ptr1 = &ptr;

cout << "Value of Num: " << num << endl;


cout << "Value of Ptr: " << *ptr << endl;
cout << "Value of Ptr1: " << **ptr1 << endl;

cout << "Actual Memory Address of Num: " << &num << endl;
cout << "Actual Memory Address of Ptr: " << &ptr << endl;
cout << "Actual Memory Address of Ptr1: " << &ptr1 << endl;

cout << "Memory Address of Num: " << &num << endl;
cout << "Reference Memory Address of Ptr: " << &*ptr << endl;
cout << "Reference Memory Address of Ptr1: " << &**ptr1 << endl;

return 0;
}

110
Lab Manual Programming Fundmental with C++

Exercise 11.2

Write a C++ program to swap the values of two integers using pointers. Take input for the integers
from the user, perform the swap operation using pointers, and display the swapped values. Explain how
pointers are utilized in this program.
Sample output 1:
Enter the value of x: 45
Enter the value of y: 65
Before swapping: x = 45, y = 65
After swapping: x = 65, y = 45
Sample output 2:
Enter the value of x: 10
Enter the value of y: 20
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
Solution:
#include <iostream>
using namespace std;

int main() {

int x, y;
cout << "Enter the value of x: ";
cin >> x;
cout << "Enter the value of y: ";
cin >> y;

cout << "Before swapping: x = " << x << ", y = " << y << endl;

int* ptrX = &x;


int* ptrY = &y;

*ptrX = *ptrX + *ptrY;


*ptrY = *ptrX - *ptrY;
*ptrX = *ptrX - *ptrY;
111
Lab Manual Programming Fundmental with C++

cout << "After swapping: x = " << x << ", y = " << y << endl;

return 0;
}

Exercise 11.3
Write a C++ program that prompts the user to enter the number of subjects they have. For each
subject, the program should request the user to input the marks obtained. After receiving the marks
for all subjects, the program should calculate and display the sum and average of total marks.
Sample output 1:
Enter the number of Subjects: 3
Enter marks for 3 subjects:
Enter Marks of Subject 1: 66
Enter Marks of Subject 2: 78
Enter Marks of Subject 3: 75
Sum of marks: 219
Average of marks: 73
Sample output 2:
Enter the number of Subjects: 5
Enter marks for 5 subjects:
Enter Marks of Subject 1: 80
Enter Marks of Subject 2: 78
Enter Marks of Subject 3: 76
Enter Marks of Subject 4: 60
Enter Marks of Subject 5: 65
Sum of marks: 359
Average of marks: 71.8
Solution:
#include <iostream>
using namespace std;

int main() {

int subjects;
cout << "Enter the number of Subjects: ";
cin >> subjects;

if (subjects <= 0) {
cout << "Invalid number entered. Exiting program." << endl;
112
Lab Manual Programming Fundmental with C++

return 1;
}

int* marks = new int[subjects];


int sum = 0;

cout << "Enter marks for " << subjects << " subjects:" << endl;
for (int i = 0; i < subjects; i++) {
cout << "Enter Marks of Subject " << i + 1 << ": ";
cin >> *(marks + i);
sum += *(marks + i);
}

double average = 0.0;


for (int i = 0; i < subjects; i++) {
average += *(marks + i);
}
average /= subjects;

cout << "Sum of marks: " << sum << endl;


cout << "Average of marks: " << average << endl;

delete[] marks;

return 0;
}

Exercise 11.4
Create a C++ program that sorts an array of double values using the bubble sort algorithm with
pointers. After sorting, the program prompts the user to continue or exit. If continuing, the process
repeats for a new array; otherwise, the program ends.
Sample output 1:
Enter the size of the array: 5
Enter 5 double values:
Enter value 1: 5.7
Enter value 2: 4.7
Enter value 3: 3.2
Enter value 4: 3.9
Enter value 5: 5.3

Array before sorting:

113
Lab Manual Programming Fundmental with C++

5.7 4.7 3.2 3.9 5.3

Array after sorting:


3.2 3.9 4.7 5.3 5.7

Do you want to continue? (y/n): n


Solution:
#include <iostream>
using namespace std;

int main() {
char choice;

do {
int size;
cout << "Enter the size of the array: ";
cin >> size;

if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;
return 1;
}

double* arr = new double[size];

cout << "Enter " << size << " double values:" << endl;
for (int i = 0; i < size; ++i) {
cout << "Enter value " << i + 1 << ": ";
cin >> *(arr + i);
}

cout << "\nArray before sorting:" << endl;


for (int i = 0; i < size; ++i) {
cout << *(arr + i) << " ";
}
cout << endl;

for (int i = 0; i < size - 1; ++i) {


for (int j = 0; j < size - i - 1; ++j) {
if (*(arr + j) > *(arr + j + 1)) {
double temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}

cout << "\nArray after sorting:" << endl;


for (int i = 0; i < size; ++i) {
cout << *(arr + i) << " ";
}
cout << endl;

delete[] arr;

cout << "\nDo you want to continue? (y/n): ";


cin >> choice;
} while (choice == 'y' || choice == 'Y');
114
Lab Manual Programming Fundmental with C++

cout << "Program terminated. Goodbye!" << endl;

return 0;
}

Exercise 11.5:

Write a program that demonstrates the difference between pointer constants and pointer variables.
Sample output:
Pointer to constant - before modification: 10
Pointer to variable - before modification: 20
Pointer to variable - after modification: 30
Pointer to variable - after reassignment: 40

Solution:

#include <iostream>
using namespace std;

int main() {
const int* constPointer;
int constantValue = 10;
constPointer = &constantValue;
cout << "Pointer to constant - before modification: " << *constPointer << endl;

*constPointer = 20; // Uncommenting this line will result in a compilation


error

int* variablePointer;
int variableValue = 20;
variablePointer = &variableValue;
cout << "Pointer to variable - before modification: " << *variablePointer <<
endl;

*variablePointer = 30;

115
Lab Manual Programming Fundmental with C++

cout << "Pointer to variable - after modification: " << *variablePointer <<
endl;

int newValue = 40;


variablePointer = &newValue;
cout << "Pointer to variable - after reassignment: " << *variablePointer <<
endl;

return 0;
}

Output after commenting //*constPointer = 20;

Exercise 11.6:
Write a C++ program demonstrating "passing pointers as arguments." The program dynamically
allocates memory for an array of integers based on user input. It then calculates the sum of the
entered values, displaying them before printing the sum. Ensure proper handling of invalid inputs.
Sample output 1:
Enter the size of the array: 4
Enter 4 integers:
Enter value 1: 4
Enter value 2: 5
Enter value 3: 6
Enter value 4: 4
Your entered values:
4 | 5 | 6 | 4 |
Sum of elements: 19
Solution:

#include <iostream>
using namespace std;

int calculateSum(int* arr, int size) {


int sum = 0;
for (int i = 0; i < size; ++i) {
sum += *(arr + i);

116
Lab Manual Programming Fundmental with C++

}
return sum;
}

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;
return 1;
}

int* arr = new int[size];


cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; ++i) {
cout << "Enter value " << i + 1 << ": ";
cin >> *(arr + i);
}

cout<< "Your entered values: " << endl;


for(int j = 0; j < size; j++){
cout << *(arr + j) << " | " << endl;
}
int sum = calculateSum(arr, size);

cout << "Sum of elements: " << sum << endl;


delete[] arr;
return 0;
}
Output

Exercise 11.7:

Write a program showcasing the utilization of pointers within functions to identify the three largest
elements in an array. The program should acquire input from the user and emphasize the utilization

117
Lab Manual Programming Fundmental with C++

of pointers and functions. Ensure that the program enforces a requirement where the size of the
array the user provides cannot be less than 3.
Solution:

#include <iostream>
using namespace std;

void findLargestThree(int* arr, int size) {

int largest1 = arr[0], largest2 = arr[0], largest3 = arr[0];

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


if (arr[i] > largest1) {
largest3 = largest2;
largest2 = largest1;
largest1 = arr[i];
} else if (arr[i] > largest2) {
largest3 = largest2;
largest2 = arr[i];
} else if (arr[i] > largest3) {
largest3 = arr[i];
}
}

cout << "Largest three elements in the array: " << largest1 << ", " << largest2
<< ", " << largest3 << endl;
}

int main() {
int size;

do {
cout << "Enter the size of the array (must be at least 3): ";
cin >> size;
} while (size < 3);

int* arr = new int[size];

// Input values into the array


cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; ++i) {
cout << "Enter value " << i + 1 << ": ";
cin >> *(arr + i);
}
findLargestThree(arr, size);
delete[] arr;

return 0;
}

Output:

118
Lab Manual Programming Fundmental with C++

Exercise 11.8:

Write a program demonstrating "Pointer and functions." It allows the user to input an array size
and elements. The program doubles each element using a function and displays both original and
doubled elements. Ensure proper handling of invalid input.
Solution:
#include <iostream>

using namespace std;


void doubleArray(int* arr, int size) {

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

*(arr + i) *= 2;

int main() {

int size;

cout << "Enter the size of the array: ";

cin >> size;

if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;

return 1;

int* arr = new int[size];

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

cout << "Enter value " << i + 1 << ": ";

cin >> *(arr + i);

119
Lab Manual Programming Fundmental with C++

}
cout<<"\nYour Entered Values: ";

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

cout << *(arr + i) << " | ";

}
doubleArray(arr, size);

cout << "\nDoubled array elements: ";

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

cout << *(arr + i) << " | ";

}
cout << endl;

delete[] arr;
return 0;

Sample output:

Exercise 11.9:
Create a C++ program to manage student information. The program should prompt the user to
input the number of students and their details, including name, age, and CGPA. It should then
display the entered information for each student.
Sample output:
Enter the number of students: 1
Enter details for student 1:
Name: Zia
Age: 26
CGPA: 3.56

Student Information:
Student 1:
Name: Zia
120
Lab Manual Programming Fundmental with C++

Age: 26
CGPA: 3.56
Solution:
#include <iostream>
#include <cstring>
using namespace std;

void displayStudentInfo(char** names, int* ages, float* cgpas, int numStudents) {


for (int i = 0; i < numStudents; ++i) {
cout << "Student " << i + 1 << ":\n";
cout << "Name: " << names[i] << endl;
cout << "Age: " << ages[i] << endl;
cout << "CGPA: " << cgpas[i] << endl;
}
}

int main() {
int numStudents;
cout << "Enter the number of students: ";
cin >> numStudents;

char** names = new char*[numStudents];


int* ages = new int[numStudents];
float* cgpas = new float[numStudents];

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


cin.ignore(); // Clear the input buffer
cout << "\nEnter details for student " << i + 1 << ":\n";
names[i] = new char[50];
cout << "Name: ";
cin.getline(names[i], 50);
cout << "Age: ";
cin >> ages[i];
cout << "CGPA: ";
cin >> cgpas[i];
}

cout << "\nStudent Information:\n";


displayStudentInfo(names, ages, cgpas, numStudents);

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


delete[] names[i];
}
delete[] names;
delete[] ages;
delete[] cgpas;

return 0;
}
121
Lab Manual Programming Fundmental with C++

Exercise 11.10:

Create a program for a student enrollment system using arrays and functions with pointers. The
program should allow administrators to register new students, update student information, and
display student details. Utilize functions with pointers to manage student data and ensure seamless
enrollment processes efficiently.

Sample output 1:
Menu:
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Zia
Enter student age: 34
Enter student CGPA: 3.2 …
Solution:
#include <iostream>
#include <cstring>
using namespace std;

const int MAX_STUDENTS = 100;

void addStudent(char** names, int* ages, float* cgpas, int& numStudents) {


if (numStudents >= MAX_STUDENTS) {
cout << "Cannot add more students. Maximum limit reached." << endl;
return;
}
cout << "Enter student name: ";
cin.ignore(); // Clear input buffer
names[numStudents] = new char[50];
cin.getline(names[numStudents], 50);
cout << "Enter student age: ";
cin >> ages[numStudents];
cout << "Enter student CGPA: ";
cin >> cgpas[numStudents];
122
Lab Manual Programming Fundmental with C++

numStudents++;
}
void updateStudent(char** names, int* ages, float* cgpas, int numStudents) {
if (numStudents == 0) {
cout << "No students to update." << endl;
return;
}

char searchName[50];
cout << "Enter the name of the student to update: ";
cin.ignore();
cin.getline(searchName, 50);

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


if (strcmp(names[i], searchName) == 0) {
cout << "Enter new age for student " << names[i] << ": ";
cin >> ages[i];
cout << "Enter new CGPA for student " << names[i] << ": ";
cin >> cgpas[i];
return;
}
}

cout << "Student not found." << endl;


}
void displayStudents(char** names, int* ages, float* cgpas, int numStudents) {
if (numStudents == 0) {
cout << "No students to display." << endl;
return;
}
cout << "Student Details:" << endl;
for (int i = 0; i < numStudents; ++i) {
cout << "Name: " << names[i] << ", Age: " << ages[i] << ", CGPA: " <<
cgpas[i] << endl;
}
}
void deleteMemory(char** names, int* ages, float* cgpas, int numStudents) {
for (int i = 0; i < numStudents; ++i) {
delete[] names[i];
}
delete[] names;
delete[] ages;
delete[] cgpas;
}
int main() {
char** names = new char*[MAX_STUDENTS];
int* ages = new int[MAX_STUDENTS];
float* cgpas = new float[MAX_STUDENTS];
int numStudents = 0;
char choice;

do {
cout << "\nMenu:\n1. Add Student\n2. Update Student\n3. Display
Students\n4. Exit\nEnter your choice: ";
cin >> choice;
switch (choice) {
case '1':
addStudent(names, ages, cgpas, numStudents);
break;

123
Lab Manual Programming Fundmental with C++

case '2':
updateStudent(names, ages, cgpas, numStudents);
break;
case '3':
displayStudents(names, ages, cgpas, numStudents);
break;
case '4':
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != '4');
deleteMemory(names, ages, cgpas, numStudents);
return 0;
}
Output:

124
Lab Manual Programming Fundmental with C++

Test Exercise

1. Write a program to manage a library system using arrays and functions with pointers. The program
should allow users to add books, display all books, and search for books by title or author. Utilize
functions with pointers to handle book data efficiently.
2. Write a program to simulate a student grading system using arrays and functions with pointers. The
program should enable instructors to input grades for multiple students, calculate their average scores,
and display the highest and lowest scores. Implement functions with pointers to manipulate student data.
3. Create a program for a retail store, employing arrays and functions with pointers. The program should
enable employees to add new products, update quantities, and display the current inventory. Utilize
functions with pointers to manage product data efficiently.
4. Develop a C++ application for a banking system that handles customer accounts using arrays and
functions with pointers. The program should allow bankers to add new accounts, deposit or withdraw
funds, and display account details. Employ functions with pointers to manage account data effectively.
5. Design a C++ program to track sales performance for a sales team using arrays and functions with
pointers. The program should enable managers to input sales figures for each team member, calculate
total sales, and display the highest and lowest-performing salesperson. Utilize functions with pointers to
handle sales data efficientl

125
Lab Manual Programming Fundmental with C++

Week 13 Task with C++


Contents Covered: Basic concepts of arrays, Traversing arrays

1. Background:
So far we have talked about a variable as a single location in the computer’s memory. It is possible to
have a collection of memory locations, all of which have the same data type, grouped together under
one name. Such a collection is called an array. Like every variable, an array must be defined so that the
computer can “reserve” the appropriate amount of memory. This amount is based upon the type of data
to be stored and the number of locations, i.e., size of the array, each of which is given in the definition.
Each element of an array, consisting of a particular memory location within the group, is accessed by
giving the name of the array and a position with the array (subscript). In C++ the subscript, sometimes
referred to as index, is enclosed in square brackets. The numbering of the subscripts always begins at 0
and ends with one less than the total number of locations.
The best way to show you what an array is and how powerful it can be is to go through an example.

1.1. Programming without Arrays


To find the average grade of a class of students, assume that there are only ten students in the class. To
work out the average of a set of numbers, you add them all together and then divide by how many there
are (in this case, 10)

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

{
int grade = 0; // Stores a grade

int count = 10; // Number of values to be read


long sum = 0; // Sum of the grades

float average = 0.0; // Average of the grades

// Read the ten grades to be averaged


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

{
cout<<"Enter a grade: ";
cin>>grade; // Read a grade
sum += grade; // Add it to sum

average = (float)sum / count; // Calculate the average


cout<<"\nAverage of the ten grades entered is: %f\n"<<average<<endl;

return 0;

}
126
Lab Manual Programming Fundmental with C++

If you’re interested only in the average, then you don’t have to remember what the previous grades
were. You accumulate the sum of all the values, which you then divide by count, which has the value
10. This program uses a single variable, grade, to store each grade as it is entered within the loop. The
loop repeats for values of i from 0 to 9 so there are ten iterations.
Let’s assume you want to develop this into a more sophisticated program in which you need to store the
values entered. Perhaps you want to output each person’s grade, with the average grade next to it. In the
previous program, you had only one variable. Each time you add a grade, the old value is overwritten,
and you can’t get it back.

So how can you store all the grades? You could declare ten integer variables to store the grades, but
then you can’t use a loop to enter the values. You must include code that will read the values
individually.
This works, but it’s quite tiresome:

127
Lab Manual Programming Fundmental with C++

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

{
int grade0 = 0, grade1 = 0, grade2 = 0, grade3 = 0, grade4 = 0;

int grade5 = 0, grade6 = 0, grade7 = 0, grade8 = 0, grade9 = 0;

long sum = 0; // Sum of the grades

float average = 0.0; // Average of the grades

// Read the ten grades to be averaged


cout<<"Enter the first five grades,\n";
cin >> grade0;

cin >> grade1;


cin >> grade2;
cin >> grade3;
cin >> grade4;

cout<<"Enter the last five numbers in the same manner.\n";


cin >> grade5;

cin >> grade6;


cin >> grade7;
cin >> grade8;
cin >> grade9;

// Now we have the ten grades, we can calculate the average


sum = grade0 + grade1 + grade2 + grade3 + grade4 +

grade5 + grade6 + grade7 + grade8 + grade9;


average = (float)sum / 10.0f;

cout << "\nAverage of the ten grades entered is: " << average <<
This is more or less okay for ten students, but what if your class has 30 students, or 100, or 1,000? How
endl;
can you do it then? This approach would become wholly impractical, and an alternative mechanism is
essential.return 0;
}

128
Lab Manual Programming Fundmental with C++

2. What is an Array?
• An array is a fixed number of data items that are all of the same type.
• The data items in an array are referred to as elements Look at the following statement:
long numbers[10];
The number between square brackets defines how many elements the array contains and is called the
array dimension.
Each of the data items stored in an array is accessed by the same name; in the previous statement the
array name is numbers. You select a particular element by using an index value between square brackets
following the array name.
Index values are sequential integers that start from zero, and 0 is the index value for the first array
element. The index values for the elements in the numbers array run from 0 to 9, so the index value 0
refers to the first element and the index value 9 refers to the last element. Therefore, you access the
elements in the numbers array as numbers[0], numbers[1], numbers[2], and so on, up to numbers[9].
You can see this in the following figure:

1. Initialization:
To initialize the elements of an array, you just specify the list of initial values between braces and
separate them by commas in the declaration. For example:
double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
To initialize the whole array, there must be one value for each element. If there are fewer initializing
values than elements, the elements without initializing values will be set to 0. Thus, if you write:
double values[5] = { 1.5, 2.5, 3.5 };
The first three elements will be initialized with the values between braces, and the last two elements will
be initialized with 0.
Knowing that the compiler will supply zeroes for elements for which you don’t provide, an initial value
offers an easy way to initialize an entire array to zero. You just need to supply one element with the
value of 0:
double values[5] = {0.0};

The entire array will then be initialized with 0.0.


If you put more initializing values than there are array elements, you’ll get an error message from the
compiler. However, you can omit the size of the array when you specify a list of initial values. In this
case, the compiler will assume that the number of elements is the number of values in the list:

int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};


The size of the array is determined by the number of initial values in the list, so the primes array will
have ten elements.

129
Lab Manual Programming Fundmental with C++

2. Using an Array:
Let’s put what you’ve just learned about arrays into practice in calculating average grades.
You can use an array to store all the scores you want to average. This means that all the values will be
saved, and you’ll be able to reuse them. You can now rewrite the program to average ten scores:

2.1. Storing Values in Array:

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

{
int grades[10]; // Array storing 10 values
int count = 10; // Number of values to be read
long sum = 0; // Sum of the numbers

float average = 0.0; // Average of the numbers


cout<<"\nEnter the 10 grades:\n"; // Prompt for the input

// Read the ten numbers to be averaged


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

cout<<i + 1<<">";
cin>>grades[i]; // Read a grade

sum += grades[i]; // Add it to sum

average = (float)sum / count; // Calculate the average

cout << "\nAverage of the ten grades entered is: " << average << endl;
Output: return 0;

130
Lab Manual Programming Fundmental with C++

Enter the ten grades:

1> 450

2> 765

3> 562

4> 700

5> 598

6> 635

7> 501

8> 720

9> 689

10> 527

Average of the ten grades entered is: 614.70

131
Lab Manual Programming Fundmental with C++

2.1. Using the Element Values:


Let’s expand the previous example to demonstrate one of the advantages of using an array. Add a minor
change to the original program (highlighted in the following code in bold), so the program displays all
the values that were typed in. having the values stored in an array means that you can access those
values whenever you want and process them in many different ways.
#include <iostream>
using namespace std;
int main(void)

{
int grades[10]; // Array storing 10 values
int count = 10; // Number of values to be read
long sum = 0; // Sum of the numbers

float average = 0.0; // Average of the numbers


cout << "\nEnter the 10 grades:\n"; // Prompt for the input

// Read the ten numbers to be averaged


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

{
cout << i + 1 << "> ";

cin >> grades[i]; // Read a grade


sum += grades[i]; // Add it to sum

}
average = (float)sum / count; // Calculate the average

// List the grades

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

cout << "\nGrade Number " << i + 1 << " is " << grades[i];

cout << "\nAverage of the ten grades entered is: " << average << endl;
return 0;

132
Lab Manual Programming Fundmental with C++

Output:
Enter the 10 grades: 1> 77
2> 87
3> 65
4> 98
5> 52
6> 74
7> 82
8> 88
9> 91
10> 71
Grade Number 1 is 77
Grade Number 2 is 87
Grade Number 3 is 65
Grade Number 4 is 98
Grade Number 5 is 52
Grade Number 6 is 74
Grade Number 7 is 82
Grade Number 8 is 88
Grade Number 9 is 91
Grade Number 10 is 71
Average of the ten grades entered is: 78.50

Arrays as Arguments:
Arrays can be passed as arguments (parameters) to functions. Although variables can be passed by value
or reference, arrays are always passed by pointer, which is similar to pass by reference, since it is not
efficient to make a “copy” of all elements of the array. Pass by pointer is discussed further in next Lab.
This means that arrays, like pass by reference parameters, can be altered by the calling function.
However, they NEVER have the & symbol between the data type and name, as pass by reference
parameters do. Sample Program given below illustrates how arrays are passed as arguments to
functions.

133
Lab Manual Programming Fundmental with C++

134
Lab Manual Programming Fundmental with C++

135
Lab Manual Programming Fundmental with C++

Notice that a set of empty brackets [ ] follows the parameter of an array which indicates that the data
type of this parameter is in fact an array. Notice also that no brackets appear in the call to the functions
that receive the array.
Since arrays in C++ are passed by pointer, which is similar to pass by reference, it allows the original
array to be altered, even though no & is used to designate this. The getData function is thus able to store
new values into the array. There may be times when we do not want the function to alter the values of
the array.
Inserting the word const before the data type on the formal parameter list prevents the function from
altering the array even though it is passed by pointer. This is why in the preceding sample program the
findAverage function and header had the word const in front of the data type of the array.

The variable numberOfGrades contains the number of elements in the array to be processed. In most
cases not every element of the array is used, which means the size of the array given in its definition and
the number of actual elements used are rarely the same. For that reason we often pass the actual number
of elements used in the array as a parameter to a procedure that uses the array. The variable
numberOfGrades is explicitly passed by reference (by using &) to the getData function where its
corresponding formal parameter is called sizeOfArray.
Prototypes can be written without named parameters. Function headers must include named parameters.
float findAverage (const int [], int); // prototype without named parameters
The use of brackets in function prototypes and headings can be avoided by declaring a programmer
defined data type. This is done in the global section with a typedef statement.
Example: typedef int GradeType[50];
This declares a data type, called GradeType, that is an array containing 50 integer memory locations.
Since GradeType is a data type, it can be used in defining variables. The following defines grades as an
integer array with 50 elements.
GradeType grades;
It has become a standard practice (although not a requirement) to use an uppercase letter to begin the
name of a data type. It is also helpful to include the word “type” in the name to indicate that it is a data
type and not a variable.
Sample Program given below shows the revised code (in bold) of Sample Program given above using
typedef.

136
Lab Manual Programming Fundmental with C++

137
Lab Manual Programming Fundmental with C++

138
Lab Manual Programming Fundmental with C++

Lab Tasks:
Exercise 1:
Write a program that will input temperatures for consecutive days.
The program will store these values into an array and call a function that will return the average of the
temperatures. It will also call a function that will return the highest temperature and a function that will
return the lowest temperature. The user will input the number of temperatures to be read. There will be
no more than 50 temperatures. Use typedef to declare the array type. The average should be displayed to
two decimal places.

Exercise 2:
Write a program that will input letter grades (A, B, C, D, F), the number of which is input by the user (a
maximum of 50 grades). The grades will be read into an array. A function will be called five times
(once for each letter grade) and will return the total number of grades in that category. The input to the
function will include the array, number of elements in the array and the letter category (A, B, C, D or
F). The program will print the number of grades that are A, B, etc.

139
Lab Manual Programming Fundamental with C++

140
Lab Manual Programming Fundamental with C++

Week 14 Task with C++


Contents Covered: Arrays (Advanced Examples)

Concept Map

Single-Dimensional Arrays
An array is basically a collection of data-items or values all based on same data-type. For example: A
student's marks in five courses in a semester: 78, 91, 83, 67, and 89; represent a collection of five int type
numbers where each value represents his/her marks in a certain course. An array is a structured data-type
(collection of values) of some fixed size (number of elements/values) where all values are of same type. To
define an array you have to mention its type, name and size (number of elements/values the array will
contain). For example:
int marks[5]

Above statements defines an int type array named marks, having size: 5 (capable of storing five
values).In the similar way, you can create array of any basic type, Examples:

float GPA[4]; //To store GPA of last 4 semesters


double area_of_circles[10]; //To store area of 10 circles
char student name[30]; //To store name of size 30 (maximum characters)

Individual array elements can be accessed using same name (array name) along its index. An index (which
must be an integer value) indicates relative position of an element/value within an array. In C++, array are
0-index based, it means that index of the starting/first element of an array is 0. For example: int marks[5];
defines an int-type array having five elements, where first value or element will be at index 0, second on
index 1, thirds element at index 2, fourth at index 3, and the fifth element at index 4. Examples:

cin>>marks[2]; //Gets marks from user and stores at 3rd position

As you have learned that array elements can be accessed using index values. Therefore, it is common
and a very convenient way to access array elements using loops (mainly for-loop). For example, below
shown code gets input from the user for all five elements of array marks.

for(int i=0;i<5;
i++) cin>>marks[i];

C++ language does not provide any boundary-check; it means C++ does not prohibit access of array
elements beyond the array size. Therefore, it is the responsibility of the programmer to access only valid
array elements (within the limit of array size) otherwise runtime errors or system crash may occur.

Similar to simple variables, arrays can also be initialized. To initialize an array, you have to provide a
comma ( , ) separated list of values (enclosed in braces "{" and "}" ). All values to be used in initialization
should belong to the same data-type the array processes. In the following example, an array named marks
(int type) is being initialized:
int marks[4] = {87, 90, 73, 91};
char country[9] = {'P','A','K','I','S','T','A','N','\0'};

141
Lab Manual Programming Fundamental with C++

4.1 Introduction to Multi-Dimensional Arrays


Until now, you have learnt that an array is a linear list (one dimensional list) of values of same data-type. In
C++, arrays can also have more than one dimension. For example an array can be declared having two
dimensions which represents set of values arranged in tabular form. For example, following code declares
a 2 Dimensional (2D) array or a table having 3 rows and 5 columns:
int marks of three students[3][5];

Above C++ code creates a two dimensional array having 3 rows (indexed from 0—2) and 5 columns
(indexed from 0—4). In a 2D array, accessing an array element requires two index values (one for row and
other for column). For examples:

//Prints value of the element at 2nd row and 4th column


cout<<marks of three students[1][3];

4.2 Sorting
Sorting data means arranging values in some pre-defined order based on their numerical value etc.
Sorting an array means to arrange array elements in a certain order (ascending or descending). In
ascending-order, values are arranged in an array such that smaller values are followed by the larger ones,
e.g., 11, 36, 56, 98, 201. In descending-order, values of an array are arranged such that larger values are
placed first then the smaller values e.g., 201, 98, 56, 36, 11. There are many ways (algorithms) to sort an
array, in this course you will learn to sort an array using bubble-sort algorithm.

Bubble-sort algorithm performs N-1 steps, to sort an array. Here N refers to the size of an array (number of
elements in the array). In each step, the complete array is traversedand comparisonsare made for pair of
adjacent values. Based on the element's value and the order to sort (either ascending or descending)
those values may be swapped.For more details, kindly review lecture 15.

4.3 Summary
• Arrays are very useful data-structure that helps to process large amount of data of same-type.
Arrays simplify coding of the programs (processing large amount of similar data) using fewer code
lines as compared to the non-array based C++ program having same functionality.

• All array elements are accessed using same name, which helps to group related set of values
using same variable-name and results in improved code readability and maintainability.

• Sorting is the process of arranging data-items or values in a certain order. One of the main
advantages of using sorting is that it helps arranging data in a more meaningful way or desired
order (based on programmers need).

Task 1
Write a C++ program that reads marks of a class (having 5 students) from the user and places them in an
array of type float. After that, it should compute average marks obtained by the class. In the end, display
student number and their marks for all those students who got marks above average.

#include <iostream>

using namespace std;

142
Lab Manual Programming Fundamental with C++

int main() {

const int numStudents = 5;

float marks[numStudents];

float totalMarks = 0, averageMarks;

// Reading marks from the user

cout << "Enter marks of " << numStudents << " students:" << endl;

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

do {

cout << "Enter marks for student " << i + 1 << ": ";

cin >> marks[i];

if (marks[i] > 100) {

cout << "Marks cannot be greater than 100. Please enter again." << endl;

} while (marks[i] > 100);

totalMarks += marks[i];

// Calculating average marks

averageMarks = totalMarks / numStudents;

// Displaying marks above average

cout << "\nStudents who scored above average marks (" << averageMarks << "):" << endl;

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

if (marks[i] > averageMarks) {

143
Lab Manual Programming Fundamental with C++

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

return 0;

Q3 Write a program that creates and then reads a matrix of 4 rows and 4 columns of type int.
while reading; the program should not accept values greater than 100. For any entered value
greater than 100, the program should ask for input repeatedly. After reading all numbers, the
system should find the largest number in the matrix and its location or index of largest value.
The program should print the largest number and its location (row and column).

#include <iostream>
using namespace std;

int main() {
const int rows = 4;
const int cols = 4;
int matrix[rows][cols];

// Reading matrix elements


cout << "Enter matrix elements (values should not be greater than 100):\n";
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
do {
cout << "Enter element at position [" << i << "][" << j << "]: ";
cin >> matrix[i][j];
144
Lab Manual Programming Fundamental with C++

if (matrix[i][j] > 100) {


cout << "Value should not be greater than 100. Please enter again.\n";
}
} while (matrix[i][j] > 100);
}
}

// Finding the largest number and its location


int largest = matrix[0][0];
int largest_row = 0;
int largest_col = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] > largest) {
largest = matrix[i][j];
largest_row = i;
largest_col = j;
}
}
}

// Printing the largest number and its location


cout << "\nThe largest number in the matrix is " << largest << " at position [" << largest_row
<< "][" << largest_col << "].\n";

return 0;
}

Output:

145
Lab Manual Programming Fundamental with C++

Home Tasks:
Q1 Write a C++ program that creates a two 2D array having 4 rows and 4 columns of type int.
Calculate the sum of values of the arrays and store the result in third array.

Q2 Write c++ of program that creates char array of 5 elements of type char. The array contains 5
vowels a, e, i, o, u. Ask the user to enter characters of their choice until the user enters a vowel.
After user enters a vowel the program should stop taking inputs. And display all the entered
characters by user.

Q3 Write a program that creates and then reads a matrix of 4 rows and 4 columns of type int.
while reading; the program should not accept values greater than 100. For any entered value
greater than 100, the program should ask for input repeatedly. After reading all numbers, the
system should find the largest number in the matrix and its location or index of largest value.
The program should print the largest number and its location (row and column).

Q 4: Write a C++ program that creates two one dimensional arrays "A" and "B" of size 10 elements
each. The main program should get the input in the array "A" from the user and initialize array "B"
with values "0". Your program should calculates the square (number * number) of each element
of array "A" and should store in the square value in corresponding positions (index) in the array
"B". In the end, the main program (main function) prints the calculated values of array "B". Also
display the values in array B which are divisible by 3 (if any).

146
Lab Manual Programming Fundamental with C++

Week 15 Task with C++


Contents Covered: String Opration and its functions

C++ Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

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

int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
Output
Hello

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is
called concatenation:

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

int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
Output
John Doe

Append

A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, you can also concatenate strings with the append() function:

#include <iostream>
147
Lab Manual Programming Fundamental with C++

#include <string>
using namespace std;

int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
return 0;
}
Output :
John Doe

Adding Numbers and Strings

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

#include <iostream>

#include <string>

using namespace std;

int main () {

string x = "10";

string y = "20";

string z = x + y;

cout << z;

return 0;

Output
1020

Example:

#include <iostream>

#include <string>

148
Lab Manual Programming Fundamental with C++

using namespace std;

int main () {

int x = 10;

int y = 20;

int z = x + y;

cout << z;

return 0;

Output:

30

String Length

To get the length of a string, use the length() function:

#include <iostream>

#include <string>

using namespace std;

int main() {

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

cout << "The length of the txt string is: " << txt.length();

return 0;

Example:
#include <iostream>

#include <string>
using namespace std;

int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
return 0;
149
Lab Manual Programming Fundamental with C++

Output
The length of the txt string is: 26

You might see some C++ programs that use the size() function to get the length of a string. This
is just an alias of length(). It is completely up to you if you want to use length() or size():

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

int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
return 0;
}

Output
The length of the txt string is: 26

Access Strings

You can access the characters in a string by referring to its index number inside square brackets
[].

This example prints the first character in myString:

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

int main() {
string myString = "Hello";
cout << myString[0];
return 0;
}
Output
H

Example:

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

int main() {
string myString = "Hello";
150
Lab Manual Programming Fundamental with C++

cout << myString[1];


return 0;
}
Output:
E

Change String Characters

To change the value of a specific character in a string, refer to the index number, and use single
quotes:

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

int main() {
string myString = "Hello";
myString[0] = 'J';
cout << myString;
return 0;
}
Output
Jello

Strings - Special Characters

Because strings must be written within quotes, C++ will misunderstand this string, and generate
an error:

string txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

151
Lab Manual Programming Fundamental with C++

The sequence \" inserts a double quote in a string:

Example:

#include <iostream>
using namespace std;

int main() {
string txt = "We are the so-called \"Vikings\" from the north.";
cout << txt;
return 0;
}

Output
We are the so-called "Vikings" from the north.

Example:

#include <iostream>
using namespace std;

int main() {
string txt = "It\'s alright.";
cout << txt;
return 0;
}
Output

It's alright.

Example:

#include <iostream>
using namespace std;

int main() {
string txt = "The character \\ is called backslash.";
cout << txt;
return 0;
}
Output
The character \ is called backslash.

User Input Strings

152
Lab Manual Programming Fundamental with C++

It is possible to use the extraction operator >> on cin to store a string entered by a user:

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

int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
Output

C Style Strings

These strings are stored as the plain old array of characters terminated by a null character ‘\0’.
They are the type of strings that C++ inherited from C language.

Syntax:

char str[] = "Dexter";

Example:

// C++ Program to demonstrate strings


#include <iostream>
using namespace std;

int main()
{

char s[] = "GeeksforGeeks";


cout << s << endl;
return 0;
}
Output:
Dexter

One more way we can make strings that have the same character repeating again and
again.

153
Lab Manual Programming Fundamental with C++

Syntax:

std::string str(number,character);

Example:

#include <iostream>
using namespace std;

int main()
{
string str(5, 'g');
cout << str;
return 0;
}

Output:

ggggg

/ C++ Program to demonstrate use of string keyword


#include <iostream>
using namespace std;

int main()
{

string s = "dexter";
string str("dexter");

cout << "s = " << s << endl;


cout << "str = " << str << endl;

return 0;
}
Output
s = dexter
str = dexter

Example

// C++ Program to demonstrate C-style string declaration


#include <iostream>
using namespace std;

int main()
{

char s1[] = { 'g', 'f', 'g', '\0' };


char s2[4] = { 'g', 'f', 'g', '\0' };
char s3[4] = "gfg";

154
Lab Manual Programming Fundamental with C++

char s4[] = "gfg";

cout << "s1 = " << s1 << endl;


cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;

return 0;
}
Output
s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg

Example

/ C++ Program to demonstrate string input using cin


#include <iostream>
using namespace std;

int main() {

string s;

cout<<"Enter String"<<endl;
cin>>s;

cout<<"String is: "<<s<<endl;


return 0;
}
Output
Enter String
String is:

Output:

Enter String
Dexter
String is: Dexter

Example

// C++ Program to demonstrate use of getline function


#include <iostream>
using namespace std;

int main()
{

string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;

155
Lab Manual Programming Fundamental with C++

return 0;
}
Output
Enter String
String is:

Output:

Enter String
Dexter
String is: Dexter

Example

// C++ Program to demonstrate use of stringstream object


#include <iostream>
#include <sstream>
#include<string>

using namespace std;

int main()
{

string s = " Dexter to the Moon ";


stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}
Output
Dexter
to
the
Moon

Task
• Write a C++ program to reverse a given string.
• Write a C++ program to find the largest word in a given string.
• Write a C++ program to count all the vowels in a given string.
• Write a C++ program to count all the words in a given string.
• Write a C++ program to find the numbers in a given string and calculate the sum of all
numbers.

156
Lab Manual Programming Fundamental with C++

Week 16 Task with C++


Contents Covered: File Handling in C++
How to open, close, read and write in a file

So far, we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively. In this week wehave to
learn about how to read and write from a file.
This requires another standard C++ library called fstream, which defines three new data types:
Data Type Description
ofstream This data type represents the output file stream
and is used to create files and to write
information to files.
ifstream This data type represents the input file stream
and is used to read Information from files .
fstream This data type represents the file stream
generally, and has the capabilities of both
ofstream and ifstream which means it can
create files, write information to files, and read
information from files.

To perform file processing in C++, header files and must be included in your C++ source file.
Opening a File:
A file must be opened before you can read from it or write to it. Either the ofstream or fstream
object may be used to open a file for writing and ifstream object is used to open a file for reading
purpose only.
Following is the standard syntax for open function, which is a member of fstream, ifstream, and
ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open member function defines the mode in which the file should be opened.
Mode Flag Description
ios::app Append mode. All output to that file to be
appended to the end.
ios::ate Open a file for output and move the read/write
control to the end of the file
ios::in Open a file for reading.
ios::out Open a file for writing.

Closing a File

157
Lab Manual Programming Fundamental with C++

When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files.
But it is always a good practice that a programmer should close all the opened files before program
termination.
Following is the standard syntax for close function, which is a member of fstream, ifstream, and
ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator << just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction operator >> just
as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of the cin object.

Examples:
1. Writing to a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ofstream outfile("example.txt"); // Create/open the file for writing
if (!outfile.is_open()) {
cout << "Error opening file for writing!" << endl;
return 1;
}
// Write to the file
outfile << "Hello, world!" << endl;
outfile.close(); // Close the file
return 0;
}

158
Lab Manual Programming Fundamental with C++

Output:
(No output to the console, but a file named "example.txt" will be created with the content "Hello,
world!")
2. Reading from a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ifstream infile("example.txt"); // Open the file for reading
if (!infile.is_open()) {
cout << "Error opening file for reading!" << endl;
return 1;
}
// Read from the file
string line;
while (getline(infile, line)) {
cout << line << endl; // Print each line to the console
}
infile.close(); // Close the file
return 0;
}
Output:
Hello, world!

3. Appending to a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ofstream outfile("example.txt", ios_base::app); // Open the file for appending

159
Lab Manual Programming Fundamental with C++

if (!outfile.is_open()) {
cout << "Error opening file for appending!" << endl;
return 1;
}
// Append to the file
outfile << "Appending text!" << endl;
outfile.close(); // Close the file
return 0;
}
Output:
(No output to the console, but the file "example.txt" will be appended with the text "Appending
text!")

4. Checking for End-of-File (EOF):


#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ifstream infile("example.txt"); // Open the file for reading
if (!infile.is_open()) {
cout << "Error opening file for reading!" << endl;
return 1; }
// Read from the file until EOF
char ch;
while (infile >> noskipws >> ch) { // Read character by character
cout << ch; // Print each character to the console
}
infile.close(); // Close the file
return 0;
}

160
Lab Manual Programming Fundamental with C++

5. Get three integer values from user and store them into a file Integer.txt and also
display the contents of file Interger.txt

#include<fstream.h>
void main()
{
ofstream ofile; // decide and declare stream object
ofile.open("Integer.txt",ios::out); // link file
int x,y,z;
// processing
cout<<"Enter any three integer\n";
cin>>x>>y>>z;
ofile<<x<<" "<<y<<" "<<z;
ofile.close();
// read and display
ifstream ifile;
ifile.open("Integer.txt",ios::in);
cout<<"the three integer are:\n";
ifile>>x>>y>>z;//read from file
cout<<"the values are\n";
cout<<x<<endl<<y<<endl<<z;
ifile.close();
}
#include<fstream.h>
int main()
{
ofstream fout;
fout.open("abc.txt");
fout<<"This is my first program in file handling";
fout.close();
return 0;
}

6. To create a text file using strings I/O


#include<fstream.h> //header file for file operations
#include<stdio.h>
161
Lab Manual Programming Fundamental with C++

void main()
{
char s[80], ch;
ofstream file("myfile.txt"); //open myfile.txt in default output mode
do
{ cout<<"\n enter line of text";
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<"\n more input y/n ";
cin>>ch;
}while(ch=='y'||ch=='Y');
file.close();
} //end of main
7. To create a text file using characters I/O
#include<fstream.h> //header file for file operations
#include<stdio.h>
void main()
{
char ch;
ofstream file("myfile2.txt"); //open myfile.txt in default output mode
ch=getchar();
file<<ch; // write a character in text file ‘myfile.txt ‘
file.close();
} //end of main

8. Text files in input mode:


To read content of ‘myfile.txt’ and display it on monitor. #include<fstream.h> //header file
for file operations
void main()
{
char ch;
ifstream file(“myfile2.txt”); //open myfile.txt in default input mode
while(file)
{
file.get(ch) // read a character from text file ‘myfile.txt’
cout<<ch; // display a character from text file to screen
}
162
Lab Manual Programming Fundamental with C++

file.close();
} //end of main

9. Read & Write Example:


Following is the C++ program which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen:

163
Lab Manual Programming Fundamental with C++

When the above code is compiled and executed, it produces the following sample input and
output:

Note: Above examples, make use of additional functions from cin object, like getline function to
read the line from outside and ignore function to ignore the extra characters left by previous read
statement.

Exercise
Q: Write a function in a C++ to read the content of a text file “DELHI.TXT” and display
all those lines on screen, which are either starting with ‘D’ or starting with ‘M’.

void DispD_M()
{
ifstream File(“DELHI.TXT”) ; // by default in input mode
char str[80];
while(File.getline(str,80))
{
if(str[0] = =’D’ || str[0] = =’M’)
cout<<str<<endl;
}
File.close();
}

164
Lab Manual Programming Fundamental with C++

10. Write a function in a C++ to count the number of lowercase alphabets present in a text file
“BOOK.txt”

int countalpha()
{ ifstream Fin(“BOOK.txt”);
char ch;
int count=0;
while(!Fin.eof())
{Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}

165

You might also like