Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views

Programming Fundamentals-SEPF-121 - Lab Manual

Uploaded by

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

Programming Fundamentals-SEPF-121 - Lab Manual

Uploaded by

shagufta yaseen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

LAB MANUAL

Programming Fundamentals
SEPF-121

DEPARTMENT OF SOFTWARE ENGINEERING


FACULTY OF ENGINEERING & COMPUTING
NATIONAL UNIVERSITY OF MODERN LANGUAGES
ISLAMABAD
BS (Software Engineering) 2023

Preface
The Programming Fundamentals Lab Manual is designed to help students learn C++
programming in a simple and effective way. It provides step-by-step instructions and practical
examples to build their coding skills and logical thinking. This manual is aims helping students
become better programmers by mastering the fundamentals of C++. By focusing on logical
reasoning, problem-solving, and programming techniques, it paves the way for a strong
programming foundation. Along with basic programming concepts, it also provides
comprehensive guidance on functions, arrays, and pointers, ensuring that students are well-
versed in these fundamental aspects of programming.

Tools/ Technologies
• C++
• Microsoft Visual Studio

2
BS (Software Engineering) 2023

TABLE OF CONTENTS

Preface ....................................................................................................................................... 2
Tools/ Technologies .................................................................................................................. 2
LAB 1: Orientation to Microsoft Visual Studio .................................................................... 4
LAB 2: Output, Arithmetic Operators and Variables ......................................................... 6
LAB 3: Input and Datatypes ................................................................................................... 9
LAB 4: Decision Making (Conditions) ................................................................................. 11
LAB 5: Nested Conditions and Switch Statements ............................................................. 15
LAB 6: While Loop ................................................................................................................ 19
LAB 7: Do-While Loop.......................................................................................................... 21
LAB 8: For Loop (Basics)...................................................................................................... 24
LAB 9: For Loop (Advanced) and Nested Loops ................................................................ 26
LAB 10: Functions – Declaration, Definition and Calling ................................................. 29
LAB 11: Function Parameters and Arguments .................................................................. 29
LAB 12: Arrays (Basic Concepts) ........................................................................................ 37
LAB 13: Arrays (Advanced Concepts and Examples) ....................................................... 39
LAB 14: Referencing and Dereferencing (Use of Pointers) ............................................... 42

3
BS (Software Engineering) 2023

LAB 1: Orientation to Microsoft Visual Studio

Objectives
The objective of this lab is to provide a basic orientation to Microsoft Visual Studio in
connection to using C++ as programming language.

Theoretical Description
This lab focuses on demystifying the essential elements of Visual Studio, tailored to the needs
of building C++ programmers. The students will get an idea of Solution Explorer, as the control
center for organizing projects and files. The lab will explore the Editor, used to craft the code
with syntax highlighting and intelligent suggestions.

Lab Task
Task 1: Navigating Solution Explorer

1. Launch Visual Studio and open a C++ project or create a new one.
2. Take a few moments to acquaint yourself with the Solution Explorer. It's like your
project's command center.
3. Explore the hierarchy of your project. You'll find files, resources, and various
elements neatly organized.
4. Try adding a new item to your project using Solution Explorer. Observe how it
reflects in your project's structure.

Task 2: The Code Editor

1. Within your project, open a C++ source code file using the Editor in Visual Studio.
2. Take note of the code highlighting. Visual Studio makes your code more readable by
using different colors for different elements.
3. Try typing a few lines of C++ code. Notice how Visual Studio provides auto-
completion suggestions and helps catch syntax errors.
4. Save your file through the Editor. Observe how it updates in the Solution Explorer.

4
BS (Software Engineering) 2023

Task 3: Understanding the Output Window

1. Write a simple C++ program in your code file.


2. Now, intentionally introduce an error into your code.
3. Build and run your program. As expected, there will be an error.
4. Explore the Output Window. It provides detailed information about the build process,
errors, warnings, and program output.
5. Use the error message to locate the issue in your code. Correct the error and run the
program again.
6. Note how the Output Window helps in diagnosing and fixing problems.

5
BS (Software Engineering) 2023

LAB 2: Output, Arithmetic Operators and Variables


Objectives
This lab is designed to familiarize you with the basics of C++ programming, focusing on
output, arithmetic operators, and escape sequences.

Theoretical Description
Output Basics: You will start by learning how to use the cout statement to display text and
variables on the console. By the end of this section, you will be able to create simple output
messages.

Arithmetic Operations: In this section, you will explore arithmetic operators such as addition,
subtraction, multiplication, and division. You will practice performing calculations and
displaying the results.

Variables: Variables are fundamental for storing and manipulating data in any programming
language. You will explore how to declare and initialize variables,

Lab Task
Task 1: Create a “Hello World” program

#include <iostream>

using namespace std;

int main() {

cout << "Hello, World!" << endl;

Task 2: Using Comments in the Program

// It is a C++ Program

#include <iostream>

using namespace std;

int main() //main function

6
BS (Software Engineering) 2023

/* These lines are the part of comments and will not execute

*/

cout<<"We are studying C++";

Task 3: Defining and using Integer Variables

#include <iostream>

using namespace std;

int main()

int a;

int b;

a = 10;

b = a + 5;

cout<<"A is "<<a <<endl;

cout<<"B is "<<b <<endl;

#include <iostream>

using namespace std;

int main()

int a,b;

a = 10; b = a + 5;

cout<<"A is "<<a <<" and B is "<<b;

cout<<"Press any key to finish";

Task 4: Using Escape Sequences in the Program

#include <iostream>

using namespace std;

int main()

7
BS (Software Engineering) 2023

cout<<"Hello\nHow\nAre\nYou\n";

cout<<”Hello\n\tHow\n\t\tAre\n\t\t\tYou\n”;

Escape Sequences
\ is considered an escape sequence character that causes and escape from the normal
interpretation of a string so that the next character is recognized as having a special meaning.
Following are the escape sequence characters along with their usage.
Escape Sequence Characters
\a Audible Alert
\b Backspace
\f Form feed
\n New Line (Carriage Return + Line Feed)
\r Return
\t Tab
\\ Backslash
\’ Single quotation
\” Double quotation
\xDD \xDB Hexadecimal Representation

Task 6:
• Write a program to print a salutation.
• Write a program to perform basic mathematical operations on numbers.
• Write a program to print a message using escape sequences.

8
BS (Software Engineering) 2023

LAB 3: Input and Datatypes


Objectives
This lab aims to introduce you to input handling in C++. You will learn how to receive user
input from the console, store it in variables, and perform various operations based on that input.
This fundamental skill is crucial for creating interactive and dynamic programs.

Theoretical Description
Input Basics: You will start by understanding how to receive input from the user using the cin
statement. You'll learn how to prompt users for input and store it in variables.

Data Types: This section will cover different data types in C++ and how to handle user input
for each type, including integers, floating-point numbers, characters, and strings.

Lab Task
Task 1: Develop a C++ program that:

• Asks the user to enter two numbers (integers).


• Reads these numbers from the console.
• Calculates and displays their sum, difference and product.

int main() {

int num1, num2;

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

int sum = num1 + num2;

int difference = num1 - num2;

int product = num1 * num2;

9
BS (Software Engineering) 2023

Task 2: Develop a C++ program that:


• Requests the user to input the following information:
• Their age (an integer).
• Their height in meters (a floating-point number).
• Their favorite letter or symbol (a character).
• Reads these inputs.
• Displays the entered values along with their data types.

• Ensure the program can handle unexpected input without crashing and provides clear
information about the data types used.

int main() {

int age;

float height;

char favoriteSymbol;

cout << "Enter your age: ";

cin >> age;

cout << "Enter your height in meters: ";

cin >> height;

cout << "Enter your favorite letter or symbol: ";

cin >> favoriteSymbol;

cout << "You entered the following information:" << endl;

cout << "Age: " << age << " (int)" << endl;

cout << "Height: " << height << " (float)" << endl;

cout << "Favorite Symbol: " << favoriteSymbol << " (char)" << endl;

10
BS (Software Engineering) 2023

LAB 4: Decision Making (Conditions)


Objectives
The purpose of this lab is to make sure that the students learn about the concept of decision
statements which includes (if-else) and conditional statements.

Theoretical Description
Decision-making allows a program to execute different code blocks based on specified
conditions. You will learn about conditional statements, logical operators, and how to control
the flow of your program using if, else if, and else statements.

Lab Task

Task 1: The if Statement


In this task, you will learn how to use the 'if' statement to make decisions in your C++ program.
The program prompts you to enter a number, and it checks whether the number is positive,
negative, or zero. Depending on the condition, it will display an appropriate message.

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

if (number > 0) {

cout << "The number is positive." << endl;

} else if (number < 0) {

cout << "The number is negative." << endl;

} else {

cout << "The number is zero." << endl;

11
BS (Software Engineering) 2023

Task 2: The 'if-else' Statement


In this task, you will explore the 'if-else' statement. You'll enter a number, and the program will
determine whether the number is even or odd. This demonstrates how 'if-else' statements can
be used to execute different code blocks based on conditions.

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

if (number % 2 == 0) {

cout << "The number is even." << endl;

} else {

cout << "The number is odd." << endl;

Task 3: Nested 'if' Statements


This task introduces nested 'if' statements, which are 'if' statements within other 'if' statements.
You'll enter an exam score, and the program will assign a grade based on a grading scale. This
demonstrates how to use multiple 'if' and 'else if' statements to handle various conditions.

int main() {

int score;

cout << "Enter your exam score: ";

cin >> score;

if (score >= 90) {

cout << "Grade: A" << endl;

} else if (score >= 80) {

cout << "Grade: B" << endl;

12
BS (Software Engineering) 2023

} else if (score >= 70) {

cout << "Grade: C" << endl;

} else if (score >= 60) {

cout << "Grade: D" << endl;

} else {

cout << "Grade: F" << endl;

Task 4: 'else if' Statements


In this task, you'll work with 'else if' statements. The program calculates a discount based on a
purchase amount. Depending on the purchase amount, it will apply different discount rates.
This showcases how 'else if' statements help you choose from multiple conditions.

int main() {

double purchaseAmount, discount = 0;

cout << "Enter the purchase amount: $";

cin >> purchaseAmount;

if (purchaseAmount >= 500) {

discount = 0.1 * purchaseAmount;

} else if (purchaseAmount >= 200) {

discount = 0.05 * purchaseAmount;

cout << "Discount: $" << discount << endl;

cout << "Total cost: $" << purchaseAmount - discount << endl;

Task 5: Logical Operators


int main() {

int number;

13
BS (Software Engineering) 2023

cout << "Enter a number between 10 and 20: ";

cin >> number;

if (number >= 10 && number <= 20) {

cout << "The number is within the specified range." << endl;

} else {

cout << "The number is outside the specified range." << endl;

14
BS (Software Engineering) 2023

LAB 5: Nested Conditions and Switch Statements


Objectives
In this lab, you will explore the usage of nested if statements and the switch statement in C++.
These control flow structures are fundamental in decision-making within programs.

Theoretical Description
Nested 'if' Statements: Nested ‘if’ allows programmers to create intricate decision-making
structures within their code. A nested 'if' statement is an 'if' statement within another 'if'
statement. This hierarchical approach enables the handling of complex conditions and multiple
scenarios. Students will apply this concept to practical exercises that involve multi-level
decision-making.

'Switch-Case' Statements: The 'switch' statement evaluates a variable and jumps to the
appropriate 'case' label based on its value. This eliminates the need for numerous 'if-else if'
statements, making code more efficient and readable. Students will create programs that
leverage 'switch-case' statements to solve problems with various options or choices.

Lab Task

Lab Task 1: Nested 'if' Statements

In this task, you will use nested if statements to determine if a student has passed or failed a
course based on their scores in two exams. Additionally, you will check if the student's scores
are within valid ranges (0-100). Implement the following pseudocode into C++ code:

int main() {

int exam1, exam2;

cout << "Enter score for Exam 1: ";

cin >> exam1;

cout << "Enter score for Exam 2: ";

15
BS (Software Engineering) 2023

cin >> exam2;

if (exam1 >= 0 && exam1 <= 100 && exam2 >= 0 && exam2 <= 100) {

if (exam1 >= 50 && exam2 >= 50) {

cout << "Student has passed." << endl;

} else {

cout << "Student has failed." << endl;

} else {

cout << "Invalid score input. Scores must be between 0 and 100." << endl;

Lab Task 2: 'switch' Statement for Day of the Week

Description: In this task, you will use a switch statement to determine the day of the week
based on a user's input (1-7). Implement the following pseudocode into C++ code:

int main() {

int day;

cout << "Enter a number (1-7) representing a day of the week: ";

cin >> day;

switch (day) {

case 1:

cout << "Monday" << endl;

break;

case 2:

cout << "Tuesday" << endl;

break;

case 3:

16
BS (Software Engineering) 2023

cout << "Wednesday" << endl;

break;

case 4:

cout << "Thursday" << endl;

break;

case 5:

cout << "Friday" << endl;

break;

case 6:

cout << "Saturday" << endl;

break;

case 7:

cout << "Sunday" << endl;

break;

default:

cout << "Invalid input. Please enter a number between 1 and 7." <<
endl;

Lab Task 3: Program for calculating discounts

Description: In this task, you will use nested if statements to categorize and provide discounts
for customers based on their total purchase amount.

int main() {

double totalPurchase;

char isMember;

cout << "Enter total purchase amount: $";

cin >> totalPurchase;

if (totalPurchase >= 500) {

cout << "Are you a member? (Y/N): ";

17
BS (Software Engineering) 2023

cin >> isMember;

if (isMember == 'Y' || isMember == 'y') {

totalPurchase -= (totalPurchase * 0.10); // 10% discount for members

} else {

totalPurchase -= (totalPurchase * 0.05); // 5% discount for non-


members

cout << "Total purchase amount after discount: $" << totalPurchase << endl;

18
BS (Software Engineering) 2023

LAB 6: While Loop


Objectives
The objective of this lab is to introduce students to the 'while' loop, a fundamental control
structure in C++ programming. Students will learn how to use 'while' loops for repetitive tasks,
making their programs more efficient and flexible.

Theoretical Description
A 'while' loop is used to repeatedly execute a block of code as long as a specified condition
remains true. It's an essential tool for automating repetitive tasks and iterating through data
structures like arrays. In this lab, students will understand the syntax of 'while' loops, how to
set up loop conditions, and how to prevent infinite loops. They will also learn about the 'do-
while' loop, a variant of the 'while' loop.

Lab Task

Task 1: User-Defined Repetition


Description: Write a program that asks the user to enter a number 'n' and then prints "Hello!"
'n' times using a 'while' loop.

int main() {

int n;

cout << "Enter a number: ";

cin >> n;

int count = 1;

while (count <= n) {

cout << "Hello! ";

count++;

return 0;

19
BS (Software Engineering) 2023

Task 2: Sum of Even Numbers


Description: Write a C++ program to calculate and print the sum of even numbers from 2 to
100 using a 'while' loop.

int main() {

int sum = 0;

int number = 2;

while (number <= 100) {

sum += number;

number += 2;

cout << "Sum of even numbers from 2 to 100: " << sum;

20
BS (Software Engineering) 2023

LAB 7: Do-While Loop


Objectives
The objective of this lab is to familiarize students with the 'do-while' loop, a control structure
in C++ that ensures a block of code is executed at least once, regardless of the initial condition.
Students will learn how to use 'do-while' loops effectively in programming.

Theoretical Description
The 'do-while' loop is similar to the 'while' loop, with one key difference: it executes its block
of code at least once before checking the loop condition. This makes it useful when you want
to ensure that a specific task is performed before considering whether to continue looping. In
this lab, students will learn about 'do-while' loop syntax, how to create exit conditions, and how
to avoid infinite loops.

Lab Task

Task 1: Greetings with a Do-While Loop

Description: Create a C++ program that uses a 'do-while' loop to ask the user for their name
and greet them. Continue to ask for their name until they enter "exit."

int main() {

string name;

do {

cout << "Enter your name (or 'exit' to quit): ";

cin >> name;

cout << "Hello, " << name << "!" << endl;

} while (name != "exit");

Task 2: Sum of Numbers

Description: Write a program that calculates the sum of all numbers entered by the user until
they enter a negative number. Use a 'do-while' loop for this task.
21
BS (Software Engineering) 2023

int main() {

int number, sum = 0;

do {

cout << "Enter a number (negative to exit): ";

cin >> number;

if (number >= 0) {

sum += number;

} while (number >= 0);

cout << "Sum of entered numbers: " << sum;

Task 3: Password Checker

Description: Create a program that asks the user to enter a password. If the entered password
is not "secure123," keep asking until the correct password is provided. Use a 'do-while' loop
for password validation.

int main() {

string password;

do {

cout << "Enter the password: ";

cin >> password;

} while (password != "secure123");

cout << "Access granted!";

Task 4: Factorial Calculation

Description: Write a C++ program to calculate the factorial of a positive integer entered by
the user. Use a 'do-while' loop to ensure a valid positive number is entered.

22
BS (Software Engineering) 2023

int main() {

int number;

do {

cout << "Enter a positive integer: ";

cin >> number;

} while (number < 1);

int factorial = 1;

int i = 1;

do {

factorial *= i;

i++;

} while (i <= number);

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

23
BS (Software Engineering) 2023

LAB 8: For Loops (Basics)


Objectives
The objective of this lab is to introduce students to the 'for' loop, a powerful control structure
in C++. Students will learn the basic syntax and functionality of 'for' loops and apply them to
simple programming tasks.

Theoretical Description
The 'for' loop in C++ is used for repetitive tasks where the number of iterations is known. It
consists of three components: initialization, condition, and increment/decrement, all enclosed
in parentheses. In this lab, students will learn the fundamentals of 'for' loops, including how to
set up loop counters, define exit conditions, and control the loop flow.

Lab Task
Task 1: Counting to Ten
Description: Write a C++ program that uses a 'for' loop to count from 1 to 10 and display each
number.

int main() {

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

cout << i << " ";

Task 2: Even Numbers


Description: Create a program that prints all even numbers between 20 and 40 using a 'for'
loop.

int main() {

for (int i = 20; i <= 40; i += 2) {

cout << i << " ";

24
BS (Software Engineering) 2023

Task 3: Multiplication Table

Description: Write a program that takes an integer input from the user and prints its
multiplication table from 1 to 10 using a 'for' loop.

int main() {

int number;

cout << "Enter an integer: ";

cin >> number;

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

cout << number << " x " << i << " = " << (number * i) << endl;

25
BS (Software Engineering) 2023

LAB 9: For Loop (Advanced) and Nested Loops


Objectives
This lab aims to challenge students with more complex programming tasks involving 'for'
loops. They will explore nested loops, manipulate patterns, and solve intricate problems using
this powerful control structure.

Theoretical Description
Building on the basics of 'for' loops, this lab delves into advanced applications. Students will
learn how to create nested 'for' loops, control loop flow, and tackle complex problems that
require iteration. The lab tasks will help students enhance their problem-solving skills and
algorithmic thinking.

Lab Task
Task 1: Prime Number Checker
Description: Create a program that checks whether a given number is prime or not. Use a 'for'
loop to iterate through possible divisors.

int main() {

int number;

cout << "Enter an integer: ";

cin >> number;

bool isPrime = true;

for (int i = 2; i <= number / 2; i++) {

if (number % i == 0) {

isPrime = false;

break;

if (isPrime) {

cout << number << " is a prime number.";

26
BS (Software Engineering) 2023

} else {

cout << number << " is not a prime number.";

Task 2: Pattern Printing


Description: Write a C++ program to print the following pattern using nested 'for' loops:

1
22
333
4444
55555

int main() {

int rows;

cout << "Enter the number of rows: ";

cin >> rows;

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

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

cout << i;

cout << endl;

Task 4: Reversed Triangle


Description: Create a program that uses nested 'for' loops to print a reversed triangle pattern of
asterisks.

27
BS (Software Engineering) 2023

int main() {

int rows;

cout << "Enter the number of rows: ";

cin >> rows;

for (int i = rows; i >= 1; i--) {

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

cout << "* ";

cout << endl;

28
BS (Software Engineering) 2023

LAB 10: Functions – Declaration, Definition and Calling


Objectives
The objective of this lab is to introduce students to the concept of functions in C++. Students
will learn how to declare, define, and call functions without parameters. This lab focuses on
the fundamental structure of functions.

Theoretical Description
Functions are essential in C++ programming for modularizing code and promoting reusability.
In this lab, students will start with the basics of functions, including declaration, definition, and
function calls. They will create functions that perform specific tasks and understand the flow
of control in a program with functions.

Lab Task
Task 1:
Declare a function named greetUser that doesn't take any parameters. The function should have
a return type of void. This function will print a greeting message when called.

// Function declaration

void greetUser();

int main() {

// Call the greetUser function

greetUser();

// Function definition

void greetUser() {

cout << "Hello! Welcome to the C++ functions lab." << endl;

Task 2:

29
BS (Software Engineering) 2023

Define the showInfo function, which doesn't take any parameters and doesn't return anything
(void). This function should display information about a topic of your choice when called.

// Function declaration

void showInfo();

int main() {

// Call the showInfo function

showInfo();

// Function definition

void showInfo() {

cout << "This is a sample information message." << endl;

cout << "You can customize it for different topics." << endl;

Task 3:
Create a program that defines a function printNumbers without parameters. This function
should print the numbers from 1 to 5 when called. Call this function from the main function.

// Function declaration

void printNumbers();

int main() {

// Call the printNumbers function

printNumbers();

// Function definition

void printNumbers() {

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

30
BS (Software Engineering) 2023

cout << i << " ";

cout << endl;

31
BS (Software Engineering) 2023

LAB 11: Function Parameters and Arguments


Objectives
The objective of this lab is to introduce students to the concept of function parameters and
arguments in C++. Students will learn how to declare and define functions that accept
parameters and pass arguments to them.

Theoretical Description
Functions become even more powerful when they can accept input values through parameters
and return results. In this lab, students will explore the use of function parameters and
arguments to make functions more versatile and adaptable to different situations.

Lab Task

Task 1: Function with Parameters


Description: Create a function named sum that takes two integer parameters, num1 and num2.
The function should return the sum of these two numbers. Call the function from the main
function with different values and display the results.

// Function declaration

int sum(int num1, int num2);

int main() {

int a = 5, b = 7;

int result1 = sum(a, b);

cout << "Sum of " << a << " and " << b << " is: " << result1 << endl;

int x = 10, y = 20;

int result2 = sum(x, y);

cout << "Sum of " << x << " and " << y << " is: " << result2 << endl;

// Function definition

int sum(int num1, int num2) {

return num1 + num2;

32
BS (Software Engineering) 2023

Task 2: Function with Multiple Parameters


Description: Define a function named calculateArea that takes three parameters: length, width,
and height (all of type double). This function should calculate and return the volume of a
rectangular box using the formula volume = length * width * height. Call the function from the
main function with different values and display the results.

// Function declaration

double calculateVolume(double length, double width, double height);

int main() {

double l1 = 3.5, w1 = 2.0, h1 = 4.0;

double volume1 = calculateVolume(l1, w1, h1);

cout << "Volume of the first box is: " << volume1 << endl;

double l2 = 5.0, w2 = 3.0, h2 = 2.5;

double volume2 = calculateVolume(l2, w2, h2);

cout << "Volume of the second box is: " << volume2 << endl;

return 0;

// Function definition

double calculateVolume(double length, double width, double height) {

return length * width * height;

Task 3: Function with Different Data Types

Description: Create a function named calculateAverage that accepts three parameters of


different data types: int, double, and float. This function should calculate and return the average
of these three values. Call the function from the main function with different values and display
the results.

33
BS (Software Engineering) 2023

// Function declaration

double calculateAverage(int num1, double num2, float num3);

int main() {

int a = 5;

double b = 7.5;

float c = 3.2;

double average = calculateAverage(a, b, c);

cout << "Average of " << a << ", " << b << ", and " << c << " is: " << average
<< endl;

// Function definition

double calculateAverage(int num1, double num2, float num3) {

return (num1 + num2 + num3) / 3.0;

Task 4: Custom Function with Parameters


Description: Define a custom function named calculateInterest that accepts two parameters:
principalAmount (of type double) and interestRate (of type float). This function should
calculate and return the simple interest using the formula interest = (principalAmount *
interestRate) / 100. Call the function from the main function with different values and display
the results.

// Function declaration

double calculateInterest(double principalAmount, float interestRate);

int main() {

double principal1 = 1000.0;

float rate1 = 5.0;

double interest1 = calculateInterest(principal1, rate1);

34
BS (Software Engineering) 2023

cout << "Simple Interest: $" << interest1 << endl;

double principal2 = 2500.0;

float rate2 = 3.5;

Task 5: Function Overloading


Description: In this task, you will explore the concept of function overloading, which allows
you to define multiple functions with the same name but different parameters. This is a
powerful feature in C++ that enhances code readability and reusability.

Instructions:

Declare a function calculateArea() that takes the radius of a circle as an argument and returns
its area. Implement the function to calculate and return the area of the circle using the formula:
area = π * radius * radius.

Overload the calculateArea() function by declaring another version of it that takes the length
and width of a rectangle as arguments and returns its area. Implement this version of the
function to calculate and return the area of the rectangle using the formula: area = length *
width.

In the main() function, call the calculateArea() function with different arguments to calculate
the area of a circle and a rectangle. Display the results.

// Function to calculate the area of a circle

double calculateArea(double radius) {

const double pi = 3.14159265359;

return pi * radius * radius;

// Overloaded function to calculate the area of a rectangle

double calculateArea(double length, double width) {

return length * width;

35
BS (Software Engineering) 2023

int main() {

double circleRadius = 5.0;

double rectangleLength = 4.0;

double rectangleWidth = 6.0;

// Calculate the area of a circle

double circleArea = calculateArea(circleRadius);

// Calculate the area of a rectangle

double rectangleArea = calculateArea(rectangleLength, rectangleWidth);

// Display the results

cout << "Area of the circle with radius " << circleRadius << " is: " <<
circleArea << endl;

cout << "Area of the rectangle with length " << rectangleLength << " and width
" << rectangleWidth << " is: " << rectangleArea << endl;

36
BS (Software Engineering) 2023

LAB 12: Arrays (Basic Concepts)


Objectives
The aim is to learn the fundamentals of arrays, including declaration, initialization, and basic
operations.

Theoretical Description
An array is a collection of elements of the same data type stored in contiguous memory
locations. Understanding arrays is essential for managing and manipulating data efficiently.

Lab Task
Task 1: Declare and Initialize an Array
Declare an integer array of size 5 and initialize it with values 10, 20, 30, 40, and 50. Print the
elements.

int main() {

int arr[5] = {10, 20, 30, 40, 50};

cout << "Elements of the array: ";

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

cout << arr[i] << " ";

Task 2: Access Array Elements


Create an array of integers and assign values to it. Access and print the third element of the
array.

int main() {

int arr[] = {5, 10, 15, 20, 25};

cout << "Third element of the array: " << arr[2] << endl;

37
BS (Software Engineering) 2023

Task 3: Modify Array Elements


Declare an array of floats and initialize it with some values. Modify the second element to a
new value and print the updated array.

int main() {

float arr[] = {1.5, 2.5, 3.5, 4.5};

// Modify the second element

arr[1] = 7.5;

cout << "Updated array: ";

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

cout << arr[i] << " ";

38
BS (Software Engineering) 2023

LAB 13: Arrays (Advanced Concepts and Examples)


Objectives
Explore advanced array concepts, including multi-dimensional arrays, dynamic arrays, and
array manipulation.

Theoretical Description
Advanced array concepts are crucial for solving complex problems and optimizing memory
usage.

Lab Task
Task 1: Multi-Dimensional Array
Create a 2D integer array to represent a 3x3 matrix. Initialize it with values, and print the
matrix.

int main() {

int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

cout << "Matrix elements:" << endl;

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

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

cout << matrix[i][j] << " ";

cout << endl;

Task 2: Dynamic Arrays


Create a dynamic integer array to store user-input values. Prompt the user for the array size and
elements, then print the array.

int main() {

int size;

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

39
BS (Software Engineering) 2023

cin >> size;

int* arr = new int[size];

cout << "Enter " << size << " elements: ";

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

cin >> arr[i];

cout << "Array elements: ";

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

cout << arr[i] << " ";

delete[] arr;

Task 3: Array Manipulation

Create an array of integers and perform array manipulation operations, such as sorting, finding
the maximum and minimum values, and calculating the average.

int main() {

int arr[] = {35, 12, 48, 9, 21};

int size = sizeof(arr) / sizeof(arr[0]);

// Sort the array

sort(arr, arr + size);

cout << "Sorted array: ";

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

cout << arr[i] << " ";

40
BS (Software Engineering) 2023

// Find maximum and minimum

int maxVal = *max_element(arr, arr + size);

int minVal = *min_element(arr, arr + size);

cout << "\nMaximum value: " << maxVal << endl;

cout << "Minimum value: " << minVal << endl;

// Calculate average

int sum = 0;

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

sum += arr[i];

double average = static_cast<double>(sum) / size;

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

41
BS (Software Engineering) 2023

LAB 14: Referencing and Dereferencing (Use of Pointers)


Objectives
Learn how to use pointers to reference memory addresses and dereference them to access
values.

Theoretical Description
Pointers are variables that store memory addresses. Understanding referencing and
dereferencing is crucial for memory management and efficient data manipulation.

Lab Task

Task 1: Create and Use Pointers


Declare an integer variable and initialize it with a value. Create a pointer variable that
references the memory address of the integer variable. Print both the value of the integer
variable and the value obtained by dereferencing the pointer.

int main() {

int num = 42;

int* ptr = &num;

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

cout << "Value using pointer: " << *ptr << endl;

Task 2: Modify Value through Pointers


Declare a float variable and assign a value to it. Create a pointer variable that references the
memory address of the float variable. Modify the value of the float variable through the pointer
and print the updated value.

int main() {

float salary = 3500.0;

float* ptrSalary = &salary;

// Modify salary through pointer

*ptrSalary = 4000.0;

42
BS (Software Engineering) 2023

cout << "Updated salary: " << salary << endl;

Task 3: Use Pointers for Array Elements


Create an array of integers and initialize it with values. Use pointers to access and print each
element of the array.

int main() {

int numbers[] = {10, 20, 30, 40, 50};

int* ptrNumbers = numbers;

cout << "Array elements using pointers:" << endl;

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

cout << "Element " << i + 1 << ": " << *(ptrNumbers + i) << endl;

Task 4: Function Using Pointers

Write a function that takes two integer pointers as arguments and swaps the values they point
to. Call the function to swap values of two integers and print the swapped values.

void swapValues(int* a, int* b) {

int temp = *a;

*a = *b;

*b = temp;

int main() {

int x = 5, y = 10;

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

swapValues(&x, &y);

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

43

You might also like