KEMBAR78
PPS Lab Manual | PDF | Programming | Computer Program
0% found this document useful (0 votes)
8 views75 pages

PPS Lab Manual

The document is a laboratory manual for a C++ programming course at Annasaheb Dange College of Engineering and Technology. It outlines various experiments aimed at teaching students programming concepts such as input/output operations, conditional statements, loops, functions, and error handling. Each experiment includes objectives, equipment requirements, theoretical background, procedures, and practice questions to enhance learning.

Uploaded by

Yogesh Kumbhar
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)
8 views75 pages

PPS Lab Manual

The document is a laboratory manual for a C++ programming course at Annasaheb Dange College of Engineering and Technology. It outlines various experiments aimed at teaching students programming concepts such as input/output operations, conditional statements, loops, functions, and error handling. Each experiment includes objectives, equipment requirements, theoretical background, procedures, and practice questions to enhance learning.

Uploaded by

Yogesh Kumbhar
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/ 75

Sant Dnyaneshwar Shikshan Sanstha's

Annasaheb Dange College of Engineering and Technology, Ashta


(An Empowered Autonomous Institute)

Department of Basic Sciences

LABORATORY MANUAL
of
PROGRAMMING FOR PROBLEM
SOLVING USING C++
(3AEES105)

Prepared by
Mr. Yogesh B. Kumbhar
Assistant Professor,
Department of Aeronautical Engineering
Contents

Sr. Page
Title / Topic of the Experiment
No. number

Write a C++ program to demonstrate input/output, use of variables, and


1 1
basic operators.

Write a program to use conditional statements (if, else, switch) for a simple
2 6
calculator or grading system.

Write a program using loops (for, while, do-while) to generate number 11


3
series and patterns.

Implement a function to compute factorial, sum of digits, or Fibonacci


4 16
series using function calls.

5 Demonstrate function overloading with different parameter types. 21

Write a program to perform basic array operations: search, insert, delete 26


6
(1D arrays).

Write a program to manipulate strings using character arrays and built-in


7 33
functions (strlen, strcpy, etc.).

Implement a program using pointers and arrays; show pointer arithmetic


8 39
and dynamic memory allocation.

Define a structure for student data and write a program to accept and 45
9
display student records.

Create a class data members and member functions; include constructors


10 52
and display details.

Demonstrate inheritance by creating base class Person and derived class


11 59
Student.

Write a program to perform file operations: write and read student records 66
12
using file streams.
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 1
Write a C++ program to demonstrate input/output, use of
Date Conducted:
variables, and basic operators.

Purpose:
To introduce students to the basic structure of a C++ program, demonstrate the use of variables,
basic operators (arithmetic, relational, logical, assignment), and input/output operations using
cin and cout, with basic error handling using conditional statements.

Objectives:

1. Understand the structure of a C++ program.


2. Declare and initialize variables of different data types (int, float, char, bool, string).
3. Perform operations using arithmetic, relational, logical, and assignment operators.
4. Implement input/output operations using cin and cout.
5. Use conditional statements to handle errors (e.g., division by zero).
6. Write a compilable C++ program with proper syntax and comments for readability.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module I: Introduction to C++ Programming and aligns with CO1
and CO2. A C++ program consists of a main() function, which serves as the entry point.
Variables store data of various types (e.g., int for integers, float for floating-point numbers,
char for characters, bool for true/false, string for text). Operators perform operations on
variables:

 Arithmetic: +, -, *, /, % (modulus).
 Relational: ==, !=, <, >, <=, >=.
 Logical: && (AND), || (OR), ! (NOT).
 Assignment: = and compound assignments (+=, -=, etc.).
Input/output operations are performed using cin (input) and cout (output), defined in
the <iostream> library. Comments (// or /* */) enhance code readability. Conditional
statements (e.g., if) are used to handle errors, such as preventing division by zero,
aligning with CO2.

Terminology:

 Variable: A named storage location for data.


 Data Type: Defines the type of data a variable can hold (e.g., int, float, string).
 Operator: Symbol performing a specific operation (e.g., + for addition).

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 1
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

 cin: Standard input stream object for reading user input.


 cout: Standard output stream object for displaying output.
 Namespace: A scope for identifiers to avoid naming conflicts (e.g., std).
 Conditional Statement: Control structure (e.g., if) to execute code based on
conditions.

Precautions:

1. Include <iostream> and using namespace std; for cin and cout.
2. Initialize variables before use to avoid undefined behavior.
3. Use correct data types to match input/output requirements.
4. Ensure proper syntax for operators and avoid division by zero using conditional checks.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment1.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Define the main() function as the program entry point.
o Declare variables of different data types (e.g., int, float, string).
o Use cin to take user input for variables.
o Perform operations using arithmetic, relational, logical, or assignment
operators.
o Use conditional statements (e.g., if) to handle errors like division by zero.
o Use cout to display the results.
o Add comments for clarity (e.g., // Input two numbers).
o Return 0 to indicate successful program execution.
3. Sample Problem 1:
Write a program to take two integers as input and perform arithmetic operations
(addition, subtraction, multiplication, division) with error handling for division by zero.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

int main() {
// Declare variables
int num1, num2;

// Input two numbers


cout << "Enter first number: ";

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 2
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

cin >> num1;


cout << "Enter second number: ";
cin >> num2;

// Arithmetic operations
cout << "Addition: " << num1 << " + " << num2 << " = " << (num1 +
num2) << endl;
cout << "Subtraction: " << num1 << " - " << num2 << " = " << (num1 -
num2) << endl;
cout << "Multiplication: " << num1 << " * " << num2 << " = " << (num1
* num2) << endl;

// Division with error handling


if (num2 != 0) {
cout << "Division: " << num1 << " / " << num2 << " = " << (num1
/ num2) << endl;
} else {
cout << "Division not possible (divide by zero error)." << endl;
}

return 0;
}

5. Sample Output 1:

Enter first number: 8


Enter second number: 4
Addition: 8 + 4 = 12
Subtraction: 8 - 4 = 4
Multiplication: 8 * 4 = 32
Division: 8 / 4 = 2

6. Sample Problem 2:
Write a program to take a string (name) and a float (temperature) as input, and display
a message with a relational check (e.g., temperature > 30).
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

int main() {
// Declare variables
string name;
float temp;
8.
// Input name and temperature
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter temperature (Celsius): ";
cin >> temp;

// Output with relational check


cout << "Hello, " << name << "!" << endl;
if (temp > 30) {
cout << "Temperature is hot" << endl;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 3
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

} else {
cout << "Temperature is normal" << endl;
}

return 0;
}

9. Sample Output 2:

Enter your name: First Name Last Name


Enter temperature (Celsius): 32
Hello, First Name Last Name!
Temperature is hot

10. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
11. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to take an integer input and display its square using the
multiplication operator.
2. Moderate: Write a program to take two float numbers and display their average using
arithmetic operators.
3. Slightly Difficult: Write a program to input a character and check if it is a vowel (a, e,
i, o, u) using relational and logical operators, then print the result.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is the purpose of the main() function in a C++ program? CO1 K1 (Remembering)
Explain the difference between int and float data types. CO1 K2 (Understanding)
How do cin and cout differ in their functionality? CO1 K2 (Understanding)
Why is using namespace std; used in a program? CO1 K1 (Remembering)
Show how to use the modulus operator (%) with an example. CO1 K3 (Applying)
What happens if a variable is used without initialization? CO1 K4 (Analyzing)
Compare relational and logical operators with an example. CO1 K4 (Analyzing)
How can you prevent a program from crashing due to division CO2 K5 (Evaluating)
by zero?

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 4
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO1 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing errors; barely due to structural
student name/URN as name/URN headers) but compiles. errors.
comment. Highly readable comment but partially works.
with comments. functional.
Variable Usage CO1 Declares and initializes Uses 2-3 data types Uses only one data Incorrect variable No variables or
multiple data types (e.g., correctly; minor type or has usage causing non-functional
int, float, string) correctly. issues. initialization errors. errors. usage.

Operator CO1 Correctly implements Uses at least two Uses only one Operators used No operators or
Implementation arithmetic, relational, and operator types operator type or has incorrectly; partial incorrect usage.
logical operators with clear correctly; minor errors. output.
output. errors.

Input/Output CO1 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout but incorrect cin/cout input/output; implemented.
output. functional. usage. unclear output.

Error Handling CO2 Implements conditional Basic error handling Error handling Minimal error No error handling
statement (e.g., if) to handle present but attempted but handling; program implemented.
errors like division by zero incomplete or minor incorrect or may crash on
effectively. issues. ineffective. invalid input.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 5
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 2
Write a C++ Program to Use Conditional Statements (if, else,
Date Conducted:
switch) for a Simple Calculator or Grading System

Purpose:
To enable students to implement conditional statements (if, if-else, switch-case) in C++ to
develop a program that performs calculations or assigns grades based on user input.

Objectives:

1. Understand the syntax and usage of if, if-else, and switch-case statements.
2. Apply conditional statements to make decisions based on user input.
3. Develop a simple calculator or grading system using conditional logic.
4. Write a compilable C++ program with proper syntax, comments, and error handling.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module II: Control Flow and Loops and aligns with CO2 (Develop
programs using conditional statements and loops). Conditional statements allow a program to
execute different code blocks based on specific conditions. The if statement checks a condition
and executes code if true. The if-else statement provides an alternative block if the condition
is false. Nested if statements allow multiple conditions to be checked hierarchically. The
switch-case statement is used for multiple discrete values of a variable, providing a cleaner
alternative to multiple if-else statements. These constructs are essential for decision-making in
applications like calculators or grading systems.

Terminology:

 Conditional Statement: A control structure that executes code based on a condition


(e.g., if, switch).
 if Statement: Executes a block of code if a condition evaluates to true.
 if-else Statement: Executes one block if a condition is true, another if false.
 switch-case: Selects a code block based on the value of a variable.
 break: Exits a switch case or loop to prevent fall-through.
 default: A switch case executed when no other case matches.

Precautions:

1. Include <iostream> and using namespace std; for cin and cout.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 6
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

2. Ensure valid input types to avoid runtime errors (e.g., expecting numbers but receiving
characters).
3. Use break in switch-case to prevent fall-through to unintended cases.
4. Validate input ranges (e.g., marks between 0 and 100 for grading).
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment2.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Define the main() function as the program entry point.
o Declare variables for input (e.g., numbers for a calculator, marks for a grading
system).
o Use cin to take user input (e.g., operation choice for calculator, marks for
grading).
o Implement conditional statements (if, if-else, or switch-case) to process input
and make decisions.
o Use cout to display the results.
o Add comments for clarity (e.g., // Select operation).
o Return 0 to indicate successful program execution.
3. Sample Problem 1:
Write a program to implement a simple calculator that performs addition, subtraction,
multiplication, or division based on user choice using switch-case.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

int main() {
// Declare variables
float num1, num2, result;
char operation;

// Input numbers and operation


cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Choose operation (+, -, *, /): ";
cin >> operation;

// Perform calculation using switch-case


switch (operation) {

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 7
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

case '+':
result = num1 + num2;
cout << num1 << " + " << num2 << " = " << result << endl;
break;
case '-':
result = num1 - num2;
cout << num1 << " - " << num2 << " = " << result << endl;
break;
case '*':
result = num1 * num2;
cout << num1 << " * " << num2 << " = " << result << endl;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
cout << num1 << " / " << num2 << " = " << result << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
default:
cout << "Invalid operation!" << endl;
}

return 0;
}

5. Sample Output 1:

Enter first number: 10


Enter second number: 5
Choose operation (+, -, *, /): +
10 + 5 = 15

6. Sample Problem 2:
Write a program to input a student’s marks (0–100) and assign a grade using if-else
statements (e.g., A for 90–100, B for 80–89, etc.).
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

int main() {
// Declare variable for marks
float marks;

// Input marks
cout << "Enter marks (0-100): ";
cin >> marks;

// Assign grade using if-else


if (marks >= 90 && marks <= 100) {
cout << "Grade: A" << endl;
} else if (marks >= 80 && marks < 90) {
cout << "Grade: B" << endl;
} else if (marks >= 70 && marks < 80) {

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 8
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

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


} else if (marks >= 60 && marks < 70) {
cout << "Grade: D" << endl;
} else if (marks >= 0 && marks < 60) {
cout << "Grade: F" << endl;
} else {
cout << "Invalid marks entered!" << endl;
}

return 0;
}

8. Sample Output 2:

Enter marks (0-100): 85


Grade: B

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to check if a number is positive, negative, or zero using if-
else.
2. Moderate: Write a program to determine if a year is a leap year using if-else (divisible
by 4, but not by 100 unless divisible by 400).
3. Slightly Difficult: Write a program to create a menu-driven calculator using switch-
case that supports addition, subtraction, multiplication, division, and modulus, with
error handling for division by zero.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is the purpose of an if statement in a C++ program? CO2 K1 (Remembering)
Explain the difference between if-else and switch-case. CO2 K2 (Understanding)
Why is the break statement used in a switch-case? CO2 K2 (Understanding)
Describe how a nested if statement works with an example. CO2 K2 (Understanding)
Write a code snippet to check if a number is even using if. CO2 K3 (Applying)
How would you handle invalid input in a switch-case CO2 K4 (Analyzing)
calculator?

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 9
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO2 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not
Structure using namespace std;, and structure or missing (e.g., missing headers) errors; barely compile due to
student name/URN as name/URN comment but partially works. compiles. structural errors.
comment. Highly but functional.
readable with comments.
Conditional Logic CO2 Correctly implements if- Uses conditional Partial Conditionals No or incorrect
Implementation else or switch-case with statements with minor implementation of implemented but conditional
accurate decision-making. logical errors. conditionals; incorrect non-functional. statements.
logic in some cases.

Input/Output CO2 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout but incorrect cin/cout input/output; implemented.
output for all cases. functional. usage. unclear output.

Error Handling CO2 Implements robust error Basic error handling Error handling Minimal error No error
handling (e.g., division by present but attempted but handling; handling
zero, invalid input) using incomplete. incorrect or program may implemented.
conditionals. ineffective. crash.

Code CO2 Code and output printed Code/output printed Code or output Only code or Neither code nor
Documentation and pasted in manual; but minor missing in manual; output provided; output
well-documented with documentation issues. limited comments. no comments. documented.
comments.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 10
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 3
Write a C++ Program Using Loops (for, while, do-while) to
Date Conducted:
Generate Number Series and Patterns

Purpose:
To enable students to implement looping constructs (for, while, do-while) in C++ to generate
number series (e.g., Fibonacci, arithmetic progression) and print patterns (e.g., star patterns),
while applying modular programming concepts.

Objectives:

1. Understand the syntax and usage of for, while, and do-while loops.
2. Apply loops to generate number series and patterns.
3. Use control statements like break and continue where appropriate.
4. Implement modular programming by structuring code logically.
5. Write a compilable C++ program with proper syntax, comments, and documentation.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module II: Control Flow and Loops (CO2) and Module III:
Functions, Arrays, and Strings (CO3). Loops allow repetitive execution of code blocks. The
for loop is used when the number of iterations is known, with initialization, condition, and
update in one line. The while loop executes as long as a condition is true, suitable for dynamic
iteration counts. The do-while loop executes at least once before checking the condition.
Control statements like break exit a loop, and continue skips to the next iteration. Loops can
be used to generate number series (e.g., 1, 2, 3, … or Fibonacci) and patterns (e.g., triangle of
stars). Modular programming (CO3) involves organizing code into reusable blocks, though this
experiment focuses primarily on loops.

Terminology:

 Loop: A control structure for repeating a block of code.


 for Loop: Executes a block for a fixed number of iterations.
 while Loop: Executes a block while a condition is true.
 do-while Loop: Executes a block at least once, then repeats while a condition is true.
 break: Terminates a loop prematurely.
 continue: Skips the current iteration and proceeds to the next.
 Number Series: A sequence of numbers following a specific rule (e.g., Fibonacci).
 Pattern: A visual arrangement of characters (e.g., star triangle).

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 11
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Precautions:

1. Include <iostream> and using namespace std; for cin and cout.
2. Ensure loop conditions prevent infinite loops (e.g., correct termination condition).
3. Validate user input to ensure it is within expected ranges (e.g., positive integers for
series length).
4. Use proper indentation and comments for readability.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment3.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Define the main() function as the program entry point.
o Declare variables for input (e.g., number of terms for a series, rows for a
pattern).
o Use cin to take user input.
o Implement loops (for, while, or do-while) to generate a number series or pattern.
o Use cout to display the results.
o Add comments for clarity (e.g., // Generate Fibonacci series).
o Return 0 to indicate successful program execution.
3. Sample Problem 1:
Write a program to generate the first n terms of the Fibonacci series using a for loop,
where n is user input.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

int main() {
// Declare variables
int n, first = 0, second = 1, next;

// Input number of terms


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

// Validate input
if (n <= 0) {
cout << "Please enter a positive number!" << endl;
return 1;
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 12
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Generate Fibonacci series


cout << "Fibonacci Series: ";
if (n >= 1) cout << first << " ";
if (n >= 2) cout << second << " ";

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


next = first + second;
cout << next << " ";
first = second;
second = next;
}
cout << endl;

return 0;
}

5. Sample Output 1:

Enter number of Fibonacci terms: 6


Fibonacci Series: 0 1 1 2 3 5

6. Sample Problem 2:
Write a program to print a right-angled triangle pattern of stars using nested for loops,
with the number of rows provided by the user.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

int main() {
// Declare variable for number of rows
int rows;

// Input number of rows


cout << "Enter number of rows for pattern: ";
cin >> rows;

// Validate input
if (rows <= 0) {
cout << "Please enter a positive number!" << endl;
return 1;
}

// Print right-angled triangle pattern


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}

return 0;
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 13
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

8. Sample Output 2:

Enter number of rows for pattern: 5


*
* *
* * *
* * * *
* * * *

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to print the first n natural numbers using a while loop.
2. Moderate: Write a program to generate an arithmetic progression (e.g., 2, 4, 6, …) for
n terms using a for loop, where n and the common difference are user inputs.
3. Slightly Difficult: Write a program to print a pyramid pattern of stars (centered
triangle) using nested for loops, with the number of rows provided by the user.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is the difference between for, while, and do-while CO2 K2 (Understanding)
loops?
Explain the role of the break statement in a loop. CO2 K2 (Understanding)
How does the continue statement affect a loop’s execution? CO2 K2 (Understanding)
Describe how nested loops are used to generate patterns. CO2 K2 (Understanding)
Write a code snippet to print the first 5 Fibonacci numbers CO2 K3 (Applying)
using a while loop.
Analyze why a do-while loop is suitable for menu-driven CO2 K4 (Analyzing)
programs.
How would you prevent an infinite loop in a while loop CO2 K4 (Analyzing)
program?
Design a loop structure to print a reverse triangle pattern and CO3 K5 (Evaluating)
justify your choice.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 14
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO2 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing headers) errors; barely due to structural
student name/URN as name/URN but partially works. compiles. errors.
comment. Highly readable comment but
with comments. functional.
Loop CO2 Correctly implements for, Uses loops with Partial loop Loops No or incorrect
Implementation while, or do-while loops to minor logical errors
implementation; implemented but loop usage.
generate series or patterns but produces
incorrect output in non-functional.
accurately. correct output. some cases.
Input/Output CO2 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout incorrect cin/cout input/output; implemented.
output for series/patterns. but functional. usage. unclear output.
Error Handling CO2 Implements robust error Basic error
Error handling Minimal error No error
handling (e.g., validates handling present
attempted but handling; handling
input to prevent invalid but incomplete. incorrect or program may implemented.
series length). ineffective. crash.
Code Modularity CO3 Code is well-organized with Code is functional Code is poorly Minimal No modularity;
clear logic and comments, but lacks some organized but partially organization; unreadable code.
promoting reusability. clarity or works. difficult to
modularity in follow.
structure.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 15
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 4
Implement a Function to Compute Factorial, Sum of Digits, or
Date Conducted:
Fibonacci Series Using Function Calls

Purpose:
To enable students to design and implement modular programs in C++ by creating functions
to compute mathematical operations like factorial, sum of digits, or Fibonacci series,
emphasizing function definition, declaration, and parameter passing.

Objectives:

1. Understand the concept of functions, including definition, declaration, and calling.


2. Implement functions to compute factorial, sum of digits, or Fibonacci series.
3. Apply parameter passing by value and reference where appropriate.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings and aligns with CO3
(Design modular programs using functions and arrays). Functions are reusable blocks of code
that perform specific tasks, improving modularity and readability. A function consists of a
return type, name, parameters, and body. Parameters can be passed by value (copy of data) or
by reference (direct access to data). Functions are declared before use (e.g., using a prototype)
and defined to specify their logic. This experiment focuses on implementing functions for
mathematical computations like factorial (n! = n × (n-1) × ... × 1), sum of digits (e.g., 123 = 1
+ 2 + 3 = 6), or Fibonacci series (0, 1, 1, 2, 3, …).

Terminology:

 Function: A named block of code that performs a specific task.


 Function Declaration: Specifies the function’s return type, name, and parameters (e.g.,
int factorial(int);).
 Function Definition: Implements the function’s logic.
 Parameter Passing: Passing data to functions by value (copy) or reference (address).
 Return Type: The data type of the value returned by a function (e.g., int, void).
 Scope: The region of the program where a variable or function is accessible.

Precautions:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 16
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

1. Include <iostream> and using namespace std; for cin and cout.
2. Declare functions before calling them, either via prototypes or by defining them before
main().
3. Validate input to avoid invalid results (e.g., negative numbers for factorial).
4. Ensure proper return types and parameter types match the function’s purpose.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment4.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Declare function prototypes (e.g., int factorial(int);) before main().
o Define the main() function as the program entry point.
o Declare variables for input (e.g., number for factorial or sum of digits).
o Use cin to take user input.
o Call the appropriate function (e.g., factorial, sum of digits) with input.
o Use cout to display the results.
o Define the function logic after main() or before it.
o Add comments for clarity (e.g., // Calculate factorial).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to compute the factorial of a number using a function with parameter
passing by value.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototype
long long factorial(int n);

int main() {
// Declare variable
int num;

// Input number
cout << "Enter a non-negative integer: ";
cin >> num;

// Validate input
if (num < 0) {
cout << "Factorial is not defined for negative numbers!" << endl;
return 1;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 17
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Call factorial function


cout << "Factorial of " << num << " is: " << factorial(num) << endl;

return 0;
}

// Function to compute factorial


long long factorial(int n) {
if (n == 0 || n == 1) return 1;
long long fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}

5. Sample Output 1:

Enter a non-negative integer: 5


Factorial of 5 is: 120

6. Sample Problem 2:
Write a program to compute the sum of digits of a number using a function with
parameter passing by value.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototype
int sumOfDigits(int num);

int main() {
// Declare variable
int num;

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

// Validate input
if (num < 0) {
cout << "Please enter a positive number!" << endl;
return 1;
}

// Call sumOfDigits function


cout << "Sum of digits of " << num << " is: " << sumOfDigits(num)
<< endl;

return 0;
}

// Function to compute sum of digits

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 18
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

int sumOfDigits(int num) {


int sum = 0;
while (num > 0) {
sum += num % 10; // Extract last digit
num /= 10; // Remove last digit
}
return sum;
}

8. Sample Output 2:

Enter a positive integer: 123


Sum of digits of 123 is: 6

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program with a function to compute the square of a number using
parameter passing by value.
2. Moderate: Write a program with a function to compute the sum of the first n natural
numbers, where n is user input.
3. Slightly Difficult: Write a program with a function to generate the nth Fibonacci
number using recursion and parameter passing by value.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is the purpose of a function in C++? CO3 K1 (Remembering)
Explain the difference between function declaration and CO3 K2 (Understanding)
definition.
How does passing by value differ from passing by reference? CO3 K2 (Understanding)
Why is a function prototype necessary in some programs? CO3 K2 (Understanding)
Write a function to compute the cube of a number. CO3 K3 (Applying)
Analyze the impact of using recursion versus iteration in a CO3 K4 (Analyzing)
factorial function.
How would you modify the sum of digits function to handle CO3 K4 (Analyzing)
negative numbers?

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 19
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing errors; barely due to structural
student name/URN as name/URN comment headers) but compiles. errors.
comment. Highly readable but functional. partially works.
with comments.
Function CO3 Correctly implementsFunction works but Function Function No or incorrect
Implementation function with proper
has minor logical or implemented but implemented but function
definition, declaration, and
syntax errors. produces incorrect non-functional. implementation.
logic. results in some
cases.
Parameter CO3 Correctly uses parameter Minor issues in Incorrect parameter Parameter No parameter
Passing passing (by value or parameter passing but passing causing passing passing or incorrect
reference) as per problem functional. partial errors. attempted but usage.
requirements. ineffective.

Input/Output CO3 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout but incorrect cin/cout input/output; implemented.
output for function results. functional. usage. unclear output.

Code CO3 Code and output printed Code/output printed Code or output Only code or Neither code nor
Documentation and pasted in manual; well- but minor missing in manual; output provided; output
documented with documentation issues. limited comments. no comments. documented.
comments.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 20
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 5
Demonstrate Function Overloading with Different Parameter
Date Conducted:
Types

Purpose:
To enable students to implement function overloading in C++ by creating multiple functions
with the same name but different parameter types or counts, emphasizing modular
programming and code reusability.

Objectives:

1. Understand the concept of function overloading in C++.


2. Implement overloaded functions with different parameter types (e.g., int, float, double)
or counts.
3. Demonstrate correct function calls based on input types.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings and aligns with CO3
(Design modular programs using functions and arrays). Function overloading allows multiple
functions to share the same name but differ in their parameter list (number, type, or order of
parameters). The compiler selects the appropriate function based on the arguments provided
during the call. This promotes code reusability and flexibility. For example, a function area can
be overloaded to calculate the area of a square (int), rectangle (int, int), or circle (double).
Overloaded functions must have distinct signatures, and the return type alone is not sufficient
for overloading.

Terminology:

 Function Overloading: Defining multiple functions with the same name but different
parameter lists.
 Function Signature: The combination of a function’s name and its parameter list (type,
number, order).
 Parameter: A variable passed to a function to perform operations.
 Return Type: The data type of the value returned by a function (e.g., int, float, void).
 Scope: The region of the program where a function or variable is accessible.
 Modularity: Organizing code into reusable, independent functions for better
maintenance.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 21
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Precautions:

1. Include <iostream> and using namespace std; for cin and cout.
2. Ensure function signatures are unique (differ in parameter type, number, or order).
3. Validate input types to match the expected parameter types of overloaded functions.
4. Use clear function names and comments to distinguish overloaded functions.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment5.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Declare prototypes for overloaded functions with different parameter types or
counts.
o Define the main() function as the program entry point.
o Declare variables for input (e.g., int, float, double).
o Use cin to take user input.
o Call the appropriate overloaded function based on input types or counts.
o Use cout to display the results.
o Define the overloaded functions’ logic after main() or before it.
o Add comments for clarity (e.g., // Overloaded function for int).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to overload a function area to calculate the area of a square (single int
parameter) and a rectangle (two int parameters).
4. Sample Code 1:
5. // Name: [Your Name], URN: [Your URN]
6. #include <iostream>
7. using namespace std;
8.
9. // Function prototypes for overloaded functions
10. int area(int side);
11. int area(int length, int breadth);
12.
13. int main() {
14. // Declare variables
15. int side, length, breadth;
16.
17. // Input for square
18. cout << "Enter side of square: ";
19. cin >> side;
20. cout << "Area of square: " << area(side) << endl;
21.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 22
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

22. // Input for rectangle


23. cout << "Enter length of rectangle: ";
24. cin >> length;
25. cout << "Enter breadth of rectangle: ";
26. cin >> breadth;
27. cout << "Area of rectangle: " << area(length, breadth) << endl;
28.
29. return 0;
30. }
31.
32. // Function to calculate area of square
33. int area(int side) {
34. return side * side;
35. }
36.
37. // Function to calculate area of rectangle
38. int area(int length, int breadth) {
39. return length * breadth;
}

40. Sample Output 1:


41. Enter side of square: 4
42. Area of square: 16
43. Enter length of rectangle: 5
44. Enter breadth of rectangle: 3
Area of rectangle: 15

45. Sample Problem 2:


Write a program to overload a function maxValue to find the maximum of two integers
or two doubles.
46. Sample Code 2:
47. // Name: [Your Name], URN: [Your URN]
48. #include <iostream>
49. using namespace std;
50.
51. // Function prototypes for overloaded functions
52. int maxValue(int a, int b);
53. double maxValue(double a, double b);
54.
55. int main() {
56. // Declare variables
57. int a, b;
58. double x, y;
59.
60. // Input for integers
61. cout << "Enter two integers: ";
62. cin >> a >> b;
63. cout << "Maximum of integers: " << maxValue(a, b) << endl;
64.
65. // Input for doubles
66. cout << "Enter two doubles: ";
67. cin >> x >> y;
68. cout << "Maximum of doubles: " << maxValue(x, y) << endl;
69.
70. return 0;
71. }
72.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 23
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

73. // Function to find maximum of two integers


74. int maxValue(int a, int b) {
75. return (a > b) ? a : b;
76. }
77.
78. // Function to find maximum of two doubles
79. double maxValue(double a, double b) {
80. return (a > b) ? a : b;
}

81. Sample Output 2:


82. Enter two integers: 7 12
83. Maximum of integers: 12
84. Enter two doubles: 3.5 9.2
Maximum of doubles: 9.2

85. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
86. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to overload a function square to compute the square of an
int and a float.
2. Moderate: Write a program to overload a function display to print a single int, a string,
or two int values.
3. Slightly Difficult: Write a program to overload a function volume to calculate the
volume of a cube (int), cylinder (double, double), and rectangular prism (int, int, int).

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question Bloom’s Taxonomy


CO
Level
What is function overloading in C++? CO3 K1 (Remembering)
Explain how the compiler distinguishes between CO3 K2 (Understanding)
overloaded functions.
Why can’t functions be overloaded based only on return CO3 K2 (Understanding)
type?
Describe the role of function signatures in overloading. CO3 K2 (Understanding)
Write a code snippet to overload a function multiply for two CO3 K3 (Applying)
int and two float inputs.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 24
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing errors; barely due to structural
student name/URN as name/URN comment headers) but compiles. errors.
comment. Highly readable but functional. partially works.
with comments.
Function CO3 Correctly implements Implements Partial Overloading No or incorrect
Overloading multiple overloaded overloading with overloading; some attempted but overloading
Implementation functions with distinct minor logical or functions incorrect non-functional. implementation.
parameter types/counts. syntax errors. or missing.
Function Calls CO3 Correctly calls overloaded Minor errors in Incorrect function Function calls No or incorrect
functions based on input function calls but calls causing attempted but function calls.
types/counts. functional. partial errors. ineffective.
Input/Output CO3 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout but incorrect cin/cout input/output; implemented.
output for function results. functional. usage. unclear output.
Code and output printed
Code/output printed Code or output Only code or
Code and pasted in manual; Neither code nor
CO3 but minor missing in manual; output provided;
Documentation well-documented with output documented.
documentation issues. limited comments. no comments.
comments.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 25
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 6
Write a C++ Program to Perform Basic Array Operations:
Date Conducted:
Search, Insert, Delete (1D Arrays)

Purpose:
To enable students to implement basic array operations (search, insert, delete) on one-
dimensional arrays in C++ using functions, and to demonstrate searching techniques, aligning
with modular programming and basic algorithm implementation.

Objectives:

1. Understand the concept and usage of one-dimensional arrays in C++.


2. Implement functions to perform search, insert, and delete operations on 1D arrays.
3. Apply linear search to locate an element in an array.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings (CO3) and Module VI:
Searching, Sorting, and File Handling (CO6). A one-dimensional array is a collection of
elements of the same data type stored in contiguous memory locations, accessed using indices
(0 to size-1). Array operations include:

 Search: Finding an element (e.g., using linear search, which checks each element
sequentially).
 Insert: Adding an element at a specified position, shifting subsequent elements.
 Delete: Removing an element from a specified position, shifting subsequent elements.
Functions enhance modularity (CO3) by encapsulating these operations. Linear search,
a basic algorithm (CO6), has a time complexity of O(n). Proper input validation ensures
robust array operations.

Terminology:

 Array: A data structure storing elements of the same type in contiguous memory.
 Index: A number used to access an array element (starts at 0).
 Linear Search: A search algorithm that checks each element sequentially.
 Insert: Adding an element to an array at a specific position.
 Delete: Removing an element from an array at a specific position.
 Function: A reusable block of code for specific tasks.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 26
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Precautions:

1. Include <iostream> and using namespace std; for cin and cout.
2. Validate array indices to prevent out-of-bounds errors (e.g., index < size).
3. Ensure array size is sufficient for insert operations to avoid overflow.
4. Check if an element exists before deletion.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment6.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Declare function prototypes for search, insert, and delete operations.
o Define the main() function as the program entry point.
o Declare a 1D array and variables for size, elements, and operation inputs.
o Use cin to take user input for array elements and operation details (e.g., element
to search, position for insert/delete).
o Call appropriate functions to perform search, insert, or delete operations.
o Use cout to display the array and operation results.
o Define the function logic for search, insert, and delete after main() or before it.
o Add comments for clarity (e.g., // Perform linear search).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to perform linear search on a 1D array using a function and display
whether the element is found.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototype
int linearSearch(int arr[], int size, int key);

int main() {
// Declare variables
int size, key;

// Input array size


cout << "Enter array size (max 100): ";
cin >> size;
if (size <= 0 || size > 100) {
cout << "Invalid size!" << endl;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 27
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

return 1;
}

// Declare array and input elements


int arr[100];
cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

// Input element to search


cout << "Enter element to search: ";
cin >> key;

// Perform linear search


int result = linearSearch(arr, size, key);
if (result != -1) {
cout << "Element " << key << " found at index " << result << endl;
} else {
cout << "Element " << key << " not found" << endl;
}

return 0;
}

// Function to perform linear search


int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

5. Sample Output 1:

Enter array size (max 100): 5


Enter 5 elements: 3 7 1 9 4
Enter element to search: 9
Element 9 found at index 3

6. Sample Problem 2:
Write a program to insert and delete an element in a 1D array using functions, with
proper array shifting.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototypes
void insertElement(int arr[], int& size, int maxSize, int pos, int value);
void deleteElement(int arr[], int& size, int pos);
void displayArray(int arr[], int size);

int main() {

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 28
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Declare variables
int size, maxSize = 100, pos, value;

// Input array size


cout << "Enter array size (max 100): ";
cin >> size;
if (size <= 0 || size > maxSize) {
cout << "Invalid size!" << endl;
return 1;
}

// Declare array and input elements


int arr[100];
cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

// Display original array


cout << "Original array: ";
displayArray(arr, size);

// Insert operation
cout << "Enter position (0 to " << size << ") and value to insert:
";
cin >> pos >> value;
insertElement(arr, size, maxSize, pos, value);
cout << "Array after insertion: ";
displayArray(arr, size);

// Delete operation
cout << "Enter position (0 to " << size-1 << ") to delete: ";
cin >> pos;
deleteElement(arr, size, pos);
cout << "Array after deletion: ";
displayArray(arr, size);

return 0;
}

// Function to insert element


void insertElement(int arr[], int& size, int maxSize, int pos, int value)
{
if (pos < 0 || pos > size || size >= maxSize) {
cout << "Invalid insertion position or array full!" << endl;
return;
}
for (int i = size; i > pos; i--) {
arr[i] = arr[i-1]; // Shift elements
}
arr[pos] = value;
size++;
}

// Function to delete element


void deleteElement(int arr[], int& size, int pos) {
if (pos < 0 || pos >= size) {
cout << "Invalid deletion position!" << endl;
return;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 29
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

}
for (int i = pos; i < size-1; i++) {
arr[i] = arr[i+1]; // Shift elements
}
size--;
}

// Function to display array


void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

8. Sample Output 2:

Enter array size (max 100): 5


Enter 5 elements: 1 2 3 4 5
Original array: 1 2 3 4 5
Enter position (0 to 5) and value to insert: 2 10
Array after insertion: 1 2 10 3 4 5
Enter position (0 to 5) to delete: 2
Array after deletion: 1 2 3 4 5

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program with a function to search for an element in a 1D array and
return its index using linear search.
2. Moderate: Write a program with a function to insert an element at the end of a 1D
array, with size validation.
3. Slightly Difficult: Write a program with functions to insert and delete elements in a 1D
array, ensuring the array remains sorted after each operation.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is a one-dimensional array in C++? CO3 K1 (Remembering)
Explain how linear search works on a 1D array. CO6 K2 (Understanding)
How does inserting an element affect an array’s elements? CO3 K2 (Understanding)
Describe the role of functions in array operations. CO3 K2 (Understanding)

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 30
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Write a function to count occurrences of an element in a 1D CO3 K3 (Applying)


array.
Analyze the time complexity of linear search in a 1D array. CO6 K4 (Analyzing)
How would you handle out-of-bounds errors in array CO3 K4 (Analyzing)
insertion?
Evaluate the trade-offs of using linear search versus CO6 K5 (Evaluating)
maintaining a sorted array for searching.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 31
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, structure or missing (e.g., missing errors; barely due to structural
and student name/URN name/URN headers) but partially compiles. errors.
as comment. Highly comment but works.
readable with comments. functional.
Array Operations CO6 Correctly implements Implements Partial Operations No or incorrect
Implementation search, insert, and delete operations with implementation; some attempted but operation
functions with accurate minor logical errors operations incorrect. non-functional. implementation.
logic. but functional.
Function CO3 Uses well-defined Functions Functions poorly Minimal No functions or
Modularity functions for each implemented but structured; partial function use; incorrect usage.
operation, promoting lack clarity or minor functionality. logic not
reusability. errors. modular.
Input/Output CO3 Uses cin/cout with clear Minor formatting Incomplete or Minimal No input/output
Operations prompts and formatted issues in cin/cout but incorrect cin/cout input/output; implemented.
output for array functional. usage. unclear output.
operations.
Implements robust error Error handling Minimal error
Basic error handling
handling (e.g., index attempted but handling; No error handling
Error Handling CO6 present but
bounds, array size) for all incorrect or program may implemented.
incomplete.
operations. ineffective. crash.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 32
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 7
Write a C++ Program to Manipulate Strings Using Character
Date Conducted:
Arrays and Built-in Functions (strlen, strcpy, etc.)

Purpose:
To enable students to manipulate strings using character arrays and built-in C-string functions
(e.g., strlen, strcpy, strcat, strcmp) in C++, emphasizing modular programming and string
handling.

Objectives:

1. Understand the use of character arrays for string manipulation in C++.


2. Implement built-in C-string functions (strlen, strcpy, strcat, strcmp) for string
operations.
3. Develop modular programs using functions to perform string manipulations.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings and aligns with CO3
(Design modular programs using functions and arrays). In C++, strings can be represented as
character arrays (null-terminated, e.g., char str[] = "hello";) or using the std::string class. This
experiment focuses on character arrays and C-style string functions from the <cstring> library:

 strlen: Returns the length of a string (excluding null terminator).


 strcpy: Copies one string to another.
 strcat: Concatenates two strings.
 strcmp: Compares two strings lexicographically.
Functions enhance modularity by encapsulating string operations, promoting code
reusability and clarity. Input validation ensures robust string handling.

Terminology:

 Character Array: An array of char type used to store a string, terminated by \0.
 Null Terminator: The character \0 marking the end of a C-string.
 strlen: Function to compute the length of a string.
 strcpy: Function to copy a source string to a destination.
 strcat: Function to append one string to another.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 33
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

 strcmp: Function to compare two strings (returns 0 if equal, positive/negative if


different).
 Modularity: Organizing code into reusable functions.

Precautions:

1. Include <iostream> and <cstring> for string functions and using namespace std;.
2. Ensure character arrays are large enough to hold input strings and null terminators.
3. Validate input to avoid buffer overflow or invalid string operations.
4. Use proper function calls for strcpy and strcat to avoid overwriting memory.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment7.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include necessary header files: #include <iostream> and #include <cstring>.
o Use using namespace std; to avoid prefixing std:: for cin, cout, and string
functions.
o Declare function prototypes for string operations (e.g., length, copy,
concatenate).
o Define the main() function as the program entry point.
o Declare character arrays for input strings and variables for operation results.
o Use cin or cin.getline to take string input (avoid buffer overflow).
o Call appropriate functions to perform string manipulations using strlen, strcpy,
strcat, or strcmp.
o Use cout to display the results.
o Define the function logic after main() or before it.
o Add comments for clarity (e.g., // Concatenate two strings).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to input two strings, compute their lengths using strlen, and compare
them using strcmp.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


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

// Function prototypes
void displayLength(char str[]);
void compareStrings(char str1[], char str2[]);

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 34
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

int main() {
// Declare character arrays
char str1[100], str2[100];

// Input strings
cout << "Enter first string: ";
cin.getline(str1, 100);
cout << "Enter second string: ";
cin.getline(str2, 100);

// Call functions to display lengths and compare


displayLength(str1);
displayLength(str2);
compareStrings(str1, str2);

return 0;
}

// Function to display string length


void displayLength(char str[]) {
cout << "Length of \"" << str << "\": " << strlen(str) << endl;
}

// Function to compare two strings


void compareStrings(char str1[], char str2[]) {
if (strcmp(str1, str2) == 0) {
cout << "Strings are equal" << endl;
} else {
cout << "Strings are not equal" << endl;
}
}

5. Sample Output 1:

Enter first string: hello


Enter second string: hello
Length of "hello": 5
Length of "hello": 5
Strings are equal

6. Sample Problem 2:
Write a program to copy one string to another using strcpy and concatenate two strings
using strcat.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

// Function prototypes
void copyString(char dest[], char src[]);
void concatenateStrings(char str1[], char str2[]);

int main() {
// Declare character arrays
char str1[100], str2[100], copy[100];

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 35
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Input strings
cout << "Enter first string: ";
cin.getline(str1, 100);
cout << "Enter second string: ";
cin.getline(str2, 100);

// Copy string
copyString(copy, str1);
cout << "Copied string: " << copy << endl;

// Concatenate strings
concatenateStrings(str1, str2);
cout << "Concatenated string: " << str1 << endl;

return 0;
}

// Function to copy string


void copyString(char dest[], char src[]) {
strcpy(dest, src);
}

// Function to concatenate strings


void concatenateStrings(char str1[], char str2[]) {
strcat(str1, str2);
}

8. Sample Output 2:

Enter first string: Hello


Enter second string: World
Copied string: Hello
Concatenated string: HelloWorld

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program with a function to compute the length of a string using
strlen.
2. Moderate: Write a program with a function to copy a string to another using strcpy and
display both strings.
3. Slightly Difficult: Write a program with a function to reverse a string using a character
array (without built-in functions) and verify it using strcmp.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 36
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is a character array in C++? CO3 K1 (Remembering)
Explain the role of the null terminator in a C-string. CO3 K2 (Understanding)
How does strcmp determine if two strings are equal? CO3 K2 (Understanding)
Describe the purpose of strcat and its effect on the CO3 K2 (Understanding)
destination string.
Write a function to concatenate two strings using strcat. CO3 K3 (Applying)
Analyze the risks of buffer overflow in string operations like CO3 K4 (Analyzing)
strcat.
How would you validate input to prevent errors in strcpy? CO3 K4 (Analyzing)
Evaluate the advantages of using std::string over character CO3 K5 (Evaluating)
arrays for string manipulation.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 37
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not
Structure using namespace std;, and structure or missing (e.g., missing errors; barely compile due to
student name/URN as name/URN headers) but partially compiles. structural errors.
comment. Highly readable comment but works.
with comments. functional.
String CO3 Correctly implements string Implements string Partial Operations No or incorrect
Manipulation operations using strlen, operations with implementation; attempted but string
Implementation strcpy, strcat, or strcmp. minor errors but some operations non-functional. operations.
functional. incorrect.
Function CO3 Uses well-defined functions Functions Functions poorly Minimal No functions or
Modularity for string operations, implemented but structured; partial function use; incorrect usage.
promoting reusability. lack clarity or minor functionality. logic not
errors. modular.
Input/Output CO3 Uses cin.getline/cout with Minor formatting Incomplete or Minimal No input/output
Operations clear prompts and formatted issues in incorrect input/output input/output; implemented.
output for string operations. input/output but usage. unclear output.
functional.
Error Handling CO3 Implements robust error Basic error handling Error handling Minimal error No error
handling (e.g., array size present but attempted but handling; handling
validation for strings). incomplete. incorrect or program may implemented.
ineffective. crash.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 38
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 8
Implement a Program Using Pointers and Arrays; Show Pointer
Date Conducted:
Arithmetic and Dynamic Memory Allocation

Purpose:
To enable students to implement C++ programs using pointers with arrays, demonstrate pointer
arithmetic, and utilize dynamic memory allocation for flexible array management, emphasizing
modular programming and pointer concepts.

Objectives:

1. Understand the concept of pointers and their use with arrays in C++.
2. Implement pointer arithmetic to access and manipulate array elements.
3. Use dynamic memory allocation (new and delete) for arrays.
4. Develop modular programs using functions to handle pointer-based operations.
5. Write a compilable C++ program with proper syntax, comments, and documentation.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings (CO3) and Module IV:
Pointers and Structures (CO4). A pointer is a variable that stores the memory address of another
variable. Pointers can be used with arrays to access elements via pointer arithmetic, where
incrementing a pointer moves it to the next memory location based on the data type (e.g., ptr +
1 moves by sizeof(int) for an int pointer). Dynamic memory allocation, using new and delete,
allows arrays to be created at runtime with flexible sizes. Functions enhance modularity (CO3)
by encapsulating pointer operations, while proper memory management (CO4) prevents
memory leaks.

Terminology:

 Pointer: A variable storing a memory address.


 Pointer Arithmetic: Operations (e.g., ptr++, ptr + n) to navigate memory locations.
 Dynamic Memory Allocation: Allocating memory at runtime using new.
 new: Allocates memory dynamically and returns a pointer.
 delete: Deallocates dynamically allocated memory to prevent leaks.
 Array: A collection of elements stored in contiguous memory, accessible via pointers.
 Modularity: Organizing code into reusable functions.

Precautions:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 39
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

1. Include <iostream> and using namespace std; for cin and cout.
2. Initialize pointers to avoid undefined behavior (e.g., set to nullptr or a valid address).
3. Ensure proper deallocation of dynamic memory using delete to prevent memory leaks.
4. Validate array indices and pointer operations to avoid accessing invalid memory.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment8.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include the necessary header file: #include <iostream>.
o Use using namespace std; to avoid prefixing std:: for cin and cout.
o Declare function prototypes for pointer-based operations (e.g., array traversal,
sum calculation).
o Define the main() function as the program entry point.
o Declare arrays and pointers, including dynamically allocated arrays using new.
o Use cin to take user input (e.g., array size, elements).
o Perform pointer arithmetic and dynamic memory operations via function calls.
o Use cout to display results.
o Define function logic for pointer operations after main() or before it.
o Deallocate dynamic memory using delete.
o Add comments for clarity (e.g., // Traverse array using pointer).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to traverse a 1D array using a pointer and compute the sum of elements
using pointer arithmetic.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototype
int sumArray(int* arr, int size);

int main() {
// Declare variables
int size;

// Input array size


cout << "Enter array size: ";
cin >> size;
if (size <= 0) {
cout << "Invalid size!" << endl;
return 1;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 40
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Declare array and pointer


int arr[100];
int* ptr = arr;

// Input array elements


cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> *(ptr + i); // Using pointer arithmetic
}

// Display array using pointer


cout << "Array elements: ";
for (int i = 0; i < size; i++) {
cout << *(ptr + i) << " ";
}
cout << endl;

// Compute sum using function


cout << "Sum of elements: " << sumArray(arr, size) << endl;

return 0;
}

// Function to compute sum using pointer


int sumArray(int* arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += *(arr + i); // Pointer arithmetic
}
return sum;
}

5. Sample Output 1:

Enter array size: 5


Enter 5 elements: 1 2 3 4 5
Array elements: 1 2 3 4 5
Sum of elements: 15

6. Sample Problem 2:
Write a program to dynamically allocate a 1D array, input elements, and reverse the
array using pointer arithmetic, then deallocate the memory.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


#include <iostream>
using namespace std;

// Function prototype
void reverseArray(int* arr, int size);

int main() {
// Declare variables
int size;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 41
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Input array size


cout << "Enter array size: ";
cin >> size;
if (size <= 0) {
cout << "Invalid size!" << endl;
return 1;
}

// Dynamically allocate array


int* arr = new int[size];
if (arr == nullptr) {
cout << "Memory allocation failed!" << endl;
return 1;
}

// Input array elements


cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

// Display original array


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

// Reverse array
reverseArray(arr, size);

// Display reversed array


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

// Deallocate memory
delete[] arr;

return 0;
}

// Function to reverse array using pointers


void reverseArray(int* arr, int size) {
int* start = arr;
int* end = arr + size - 1;
while (start < end) {
// Swap elements using pointer arithmetic
int temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 42
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

8. Sample Output 2:

Enter array size: 5


Enter 5 elements: 1 2 3 4 5
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to traverse a 1D array using a pointer and print its elements.
2. Moderate: Write a program to dynamically allocate a 1D array, input elements, and
find the maximum element using pointer arithmetic.
3. Slightly Difficult: Write a program to dynamically allocate a 1D array, sort it using
pointer arithmetic, and deallocate the memory.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question Bloom’s Taxonomy


CO
Level
What is a pointer in C++? CO4 K1 (Remembering)
Explain how pointer arithmetic works with arrays. CO4 K2 (Understanding)
What is the purpose of new and delete in dynamic memory CO4 K2 (Understanding)
allocation?
Describe the role of functions in pointer-based operations. CO3 K2 (Understanding)
Write a code snippet to swap two array elements using CO4 K3 (Applying)
pointers.
Analyze the risks of not deallocating dynamic memory. CO4 K4 (Analyzing)
How would you prevent invalid memory access in pointer CO4 K4 (Analyzing)
arithmetic?
Evaluate the benefits of dynamic memory allocation over CO3 K5 (Evaluating)
static arrays.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 43
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in structure or Incorrect structure Major Does not
Structure using namespace std;, and missing name/URN (e.g., missing structural compile due to
student name/URN as comment but functional. headers) but errors; barely structural errors.
comment. Highly readable partially works. compiles.
with comments.
Pointer CO4 Correctly implements
Minor errors in pointer Partial Pointer No or incorrect
Arithmetic pointer arithmetic to
arithmetic but functional. implementation; arithmetic pointer
Implementation access/manipulate array incorrect pointer attempted but arithmetic.
elements. operations in some non-
cases. functional.
Dynamic CO4 Correctly uses new and Minor errors in Incorrect or partial Minimal No or incorrect
Memory delete for dynamic array allocation/deallocation but use of new/delete; dynamic dynamic
Allocation management. functional. memory issues. memory use; memory
errors allocation.
present.
Function CO3 Uses well-defined Functions implemented but Functions poorly Minimal No functions or
Modularity functions for pointer lack clarity or minor errors. structured; partial function use; incorrect usage.
operations, promoting functionality. logic not
reusability. modular.
Error Handling CO4 Implements robust error Basic error handling Error handling Minimal error No error
handling (e.g., size present but incomplete. attempted but handling; handling
validation, null pointer incorrect or program may implemented.
checks). ineffective. crash.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 44
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 9
Define a Structure for Student Data and Write a Program to
Date Conducted:
Accept and Display Student Records

Purpose:
To enable students to define and use structures in C++ to manage student data, implement
functions to accept and display records, and demonstrate basic data organization, aligning with
modular programming and data handling concepts.

Objectives:

1. Understand the concept and syntax of structures in C++.


2. Define a structure to store student data (e.g., roll number, name, marks).
3. Implement functions to accept and display student records.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module IV: Pointers and Structures (CO4) and Module VI:
Searching, Sorting, and File Handling (CO6). A structure in C++ is a user-defined data type
that groups related data (e.g., int rollNo, string name, float marks) under a single name.
Structures allow organized storage of records, such as student data. Functions can be used to
input and display structure data, promoting modularity (CO4). This experiment also aligns with
CO6 by focusing on data handling, a precursor to file operations, as it involves structured data
management. Input validation ensures robust record handling.

Terminology:

 Structure: A user-defined data type grouping related variables.


 Member: A variable within a structure (e.g., rollNo, name).
 Dot Operator (.): Used to access structure members (e.g., student.rollNo).
 Array of Structures: An array storing multiple structure instances.
 Modularity: Organizing code into reusable functions.
 Data Handling: Managing structured data input/output.

Precautions:

1. Include <iostream> and <string> for cin, cout, and string usage, with using namespace
std;.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 45
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

2. Validate input (e.g., positive roll numbers, valid marks) to ensure data integrity.
3. Ensure structure members are accessed correctly using the dot operator.
4. Use cin.getline or getline for string input to handle spaces.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment9.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include necessary header files: #include <iostream> and #include <string>.
o Use using namespace std; to avoid prefixing std:: for cin, cout, and string.
o Define a structure for student data (e.g., Student with rollNo, name, marks).
o Declare function prototypes for accepting and displaying student records.
o Define the main() function as the program entry point.
o Declare an array of structures or a single structure to store student data.
o Use cin and getline to accept input for structure members.
o Call functions to input and display student records.
o Use cout to display results.
o Define function logic after main() or before it.
o Add comments for clarity (e.g., // Input student details).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to define a structure for a student (roll number, name, marks) and use
functions to accept and display one student’s record.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


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

// Structure definition
struct Student {
int rollNo;
string name;
float marks;
};

// Function prototypes
void inputStudent(Student& s);
void displayStudent(Student s);

int main() {
// Declare a student structure
Student s;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 46
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Input student details


inputStudent(s);

// Display student details


displayStudent(s);

return 0;
}

// Function to input student details


void inputStudent(Student& s) {
cout << "Enter roll number: ";
cin >> s.rollNo;
cin.ignore(); // Clear buffer for getline
cout << "Enter name: ";
getline(cin, s.name);
cout << "Enter marks (0-100): ";
cin >> s.marks;

// Validate input
if (s.rollNo < 0 || s.marks < 0 || s.marks > 100) {
cout << "Invalid input! Roll number and marks must be valid." <<
endl;
s.rollNo = 0;
s.marks = 0;
}
}

// Function to display student details


void displayStudent(Student s) {
cout << "\nStudent Record:" << endl;
cout << "Roll Number: " << s.rollNo << endl;
cout << "Name: " << s.name << endl;
cout << "Marks: " << s.marks << endl;
}

5. Sample Output 1:

Enter roll number: 101


Enter name: First Name Last Name
Enter marks (0-100): 85

Student Record:
Roll Number: 101
Name: First Name Last Name
Marks: 85

6. Sample Problem 2:
Write a program to define a structure for a student and use functions to accept and
display multiple student records using an array of structures.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 47
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Structure definition
struct Student {
int rollNo;
string name;
float marks;
};

// Function prototypes
void inputStudents(Student s[], int size);
void displayStudents(Student s[], int size);

int main() {
// Declare variables
int size;

// Input number of students


cout << "Enter number of students (max 50): ";
cin >> size;
if (size <= 0 || size > 50) {
cout << "Invalid size!" << endl;
return 1;
}

// Declare array of structures


Student students[50];

// Input student records


inputStudents(students, size);

// Display student records


displayStudents(students, size);

return 0;
}

// Function to input student records


void inputStudents(Student s[], int size) {
for (int i = 0; i < size; i++) {
cout << "\nEnter details for student " << i + 1 << ":" << endl;
cout << "Roll number: ";
cin >> s[i].rollNo;
cin.ignore(); // Clear buffer for getline
cout << "Name: ";
getline(cin, s[i].name);
cout << "Marks (0-100): ";
cin >> s[i].marks;

// Validate input
if (s[i].rollNo < 0 || s[i].marks < 0 || s[i].marks > 100) {
cout << "Invalid input! Setting default values." << endl;
s[i].rollNo = 0;
s[i].marks = 0;
}
}
}

// Function to display student records


void displayStudents(Student s[], int size) {
cout << "\nStudent Records:" << endl;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 48
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

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


cout << "\nStudent " << i + 1 << ":" << endl;
cout << "Roll Number: " << s[i].rollNo << endl;
cout << "Name: " << s[i].name << endl;
cout << "Marks: " << s[i].marks << endl;
}
}

8. Sample Output 2:

Enter number of students (max 50): 2

Enter details for student 1:


Roll number: 101
Name: First Name Last Name
Marks (0-100): 85

Enter details for student 2:


Roll number: 102
Name: Jane Smith
Marks (0-100): 92

Student Records:
Student 1:
Roll Number: 101
Name: First Name Last Name
Marks: 85

Student 2:
Roll Number: 102
Name: Jane Smith
Marks: 92

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to define a structure for a student (roll number, name) and
display one record.
2. Moderate: Write a program to define a structure for a student and use a function to find
the student with the highest marks in an array of structures.
3. Slightly Difficult: Write a program to define a structure for a student and sort an array
of student records by marks using a function.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 49
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Question Bloom’s Taxonomy


CO
Level
What is a structure in C++? CO4 K1 (Remembering)
Explain how the dot operator is used to access structure CO4 K2 (Understanding)
members.
How does an array of structures store multiple records? CO4 K2 (Understanding)
Describe the role of functions in managing student records. CO4 K2 (Understanding)
Write a function to input a single student’s record into a CO4 K3 (Applying)
structure.
Analyze the difference between a structure and a class in CO4 K4 (Analyzing)
C++.
How would you validate input for a student structure to CO6 K4 (Analyzing)
ensure data integrity?
Evaluate the benefits of using structures for data CO6 K5 (Evaluating)
organization versus separate arrays.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 50
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO4 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing errors; barely due to structural
student name/URN as name/URN headers) but compiles. errors.
comment. Highly readable comment but partially works.
with comments. functional.
Structure CO4 Correctly defines and uses Structure defined but Incomplete Structure No or incorrect
Implementation structure for student data minor errors in structure definition defined but non- structure
with all members. member usage. or incorrect functional. implementation.
member access.
Function CO4 Uses well-defined functions Functions Functions poorly Minimal No functions or
Modularity for input/display, promoting implemented but structured; partial function use; incorrect usage.
reusability. lack clarity or minor functionality. logic not
errors. modular.
Input/Output CO6 Uses cin/getline/cout with Minor formatting Incomplete or Minimal No input/output
Operations clear prompts and formatted issues in incorrect input/output; implemented.
output for records. input/output but input/output usage. unclear output.
functional.
Error Handling CO6 Implements robust error Basic error handling Error handling Minimal error No error handling
handling (e.g., validates roll present but attempted but handling; implemented.
number, marks). incomplete. incorrect or program may
ineffective. crash.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 51
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 10
Create a Class with Data Members and Member Functions;
Date Conducted:
Include Constructors and Display Details

Purpose:
To enable students to implement a C++ class with data members, member functions, and
constructors, demonstrating object-oriented programming (OOP) concepts like encapsulation
and modularity, and to display object details.

Objectives:

1. Understand the concept of classes and objects in C++.


2. Define a class with data members, member functions, and constructors.
3. Implement encapsulation by controlling access to data members.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module III: Functions, Arrays, and Strings (CO3) and Module V:
Object-Oriented Programming Concepts (CO5). A class in C++ is a user-defined data type that
encapsulates data members (variables) and member functions (methods) to operate on that data.
Constructors are special member functions that initialize objects, called automatically when an
object is created. Encapsulation (CO5) involves bundling data and methods, often using access
specifiers (private, public) to protect data. Member functions promote modularity (CO3) by
organizing operations within the class. This experiment focuses on creating a class (e.g., for a
student) and displaying its details.

Terminology:

 Class: A blueprint for objects, defining data members and member functions.
 Object: An instance of a class.
 Data Member: A variable defined within a class.
 Member Function: A function defined within a class to operate on its data.
 Constructor: A special function to initialize objects, with the same name as the class.
 Encapsulation: Restricting access to data members using access specifiers.
 Modularity: Organizing code into reusable units (e.g., member functions).

Precautions:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 52
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

1. Include <iostream> and <string> for cin, cout, and string usage, with using namespace
std;.
2. Ensure constructors have the same name as the class and no return type.
3. Use private for data members and public for member functions to enforce
encapsulation.
4. Validate input (e.g., positive values for roll number, valid marks) to ensure data
integrity.
5. Save the program with a .cpp extension in Dev C++ before compiling.
6. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment10.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include necessary header files: #include <iostream> and #include <string>.
o Use using namespace std; to avoid prefixing std:: for cin, cout, and string.
o Define a class with data members, constructors, and member functions.
o Define the main() function as the program entry point.
o Create objects of the class and initialize them using constructors.
o Use cin and getline to accept input for object data (if needed).
o Call member functions to display object details.
o Use cout to display results.
o Add comments for clarity (e.g., // Define class Student).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to create a Student class with data members (roll number, name,
marks), a default constructor, and a member function to display details.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


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

// Class definition
class Student {
private:
int rollNo;
string name;
float marks;

public:
// Default constructor
Student() {
rollNo = 0;
name = "Unknown";

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 53
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

marks = 0.0;
}

// Member function to display student details


void display() {
cout << "Student Details:" << endl;
cout << "Roll Number: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
// Create object with default constructor
Student s1;

// Display student details


s1.display();

return 0;
}

5. Sample Output 1:

Student Details:
Roll Number: 0
Name: Unknown
Marks: 0

6. Sample Problem 2:
Write a program to create a Student class with data members (roll number, name,
marks), a parameterized constructor, and member functions to set and display details.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

// Class definition
class Student {
private:
int rollNo;
string name;
float marks;

public:
// Parameterized constructor
Student(int r, string n, float m) {
rollNo = r;
name = n;
if (m >= 0 && m <= 100) {
marks = m;
} else {
marks = 0;
cout << "Invalid marks! Set to 0." << endl;
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 54
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Member function to set student details


void setDetails(int r, string n, float m) {
rollNo = r;
name = n;
if (m >= 0 && m <= 100) {
marks = m;
} else {
marks = 0;
cout << "Invalid marks! Set to 0." << endl;
}
}

// Member function to display student details


void display() {
cout << "\nStudent Details:" << endl;
cout << "Roll Number: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
// Declare variables for input
int rollNo;
string name;
float marks;

// Input student details


cout << "Enter roll number: ";
cin >> rollNo;
cin.ignore(); // Clear buffer for getline
cout << "Enter name: ";
getline(cin, name);
cout << "Enter marks (0-100): ";
cin >> marks;

// Create object with parameterized constructor


Student s1(rollNo, name, marks);

// Display student details


s1.display();

// Update details using setDetails


cout << "\nEnter new details for student:" << endl;
cout << "Roll number: ";
cin >> rollNo;
cin.ignore();
cout << "Name: ";
getline(cin, name);
cout << "Marks (0-100): ";
cin >> marks;

s1.setDetails(rollNo, name, marks);


s1.display();

return 0;
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 55
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

8. Sample Output 2:

Enter roll number: 101


Enter name: First Name Last Name
Enter marks (0-100): 85

Student Details:
Roll Number: 101
Name: First Name Last Name
Marks: 85

Enter new details for student:


Roll number: 102
Name: Jane Smith
Marks (0-100): 92

Student Details:
Roll Number: 102
Name: Jane Smith
Marks: 92

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to create a Book class with data members (title, author)
and a default constructor to display details.
2. Moderate: Write a program to create a Rectangle class with data members (length,
breadth), a parameterized constructor, and a member function to calculate and display
the area.
3. Slightly Difficult: Write a program to create a Student class with an array of marks, a
constructor to initialize it, and a member function to compute and display the average
marks.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is a class in C++? CO5 K1 (Remembering)
Explain the role of a constructor in a class. CO5 K2 (Understanding)
How does encapsulation protect class data members? CO5 K2 (Understanding)
Describe the difference between a default and CO5 K2 (Understanding)
parameterized constructor.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 56
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Write a constructor for a Car class with data members CO5 K3 (Applying)
(model, year).
Analyze the benefits of using member functions for CO3 K4 (Analyzing)
modularity.
How would you validate input in a constructor to ensure CO5 K4 (Analyzing)
data integrity?
Evaluate when to use a default constructor versus a CO5 K5 (Evaluating)
parameterized constructor.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 57
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO3 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or missing (e.g., missing errors; barely due to structural
student name/URN as name/URN comment headers) but partially compiles. errors.
comment. Highly readable but functional. works.
with comments.
Class CO5 Correctly defines class Class defined but Incomplete class Class defined but No or incorrect
Implementation with data members, minor errors in definition or non-functional. class
constructors, and member implementation. incorrect member implementation.
functions. usage.
Constructor CO5 Correctly implements Minor errors in Incorrect or partial Constructor No or incorrect
Usage default or parameterized constructor logic but constructor attempted but constructor usage.
constructors with proper functional. implementation. non-functional.
initialization.
Input/Output CO3 Uses cin/getline/cout with Minor formatting Incomplete or Minimal No input/output
Operations clear prompts and issues in input/output incorrect input/output; implemented.
formatted output for class but functional. input/output usage. unclear output.
data.
Encapsulation CO5 Uses private for data Minor issues in access Incorrect use of Minimal No encapsulation
members and public for specifiers but access specifiers; encapsulation; implemented.
functions, ensuring proper functional. partial data exposed.
encapsulation. encapsulation.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 58
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 11
Demonstrate Inheritance by Creating Base Class Person and
Date Conducted:
Derived Class Student

Purpose:
To enable students to implement inheritance in C++ by creating a base class Person and a
derived class Student, demonstrating object-oriented programming (OOP) concepts such as
inheritance and encapsulation.

Objectives:

1. Understand the concept of inheritance in C++.


2. Define a base class Person with attributes and methods, and a derived class Student
inheriting from it.
3. Implement member functions to input and display data for both classes.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module V: Object-Oriented Programming Concepts and aligns with
CO5 (Construct C++ classes applying OOP concepts: encapsulation, inheritance). Inheritance
allows a derived class (e.g., Student) to inherit properties and methods from a base class (e.g.,
Person), promoting code reuse and hierarchy. The derived class can extend or override base
class functionality. Encapsulation is achieved by using access specifiers (private, public,
protected) to control data access. Single inheritance, where Student inherits from Person, is
demonstrated here. Constructors initialize objects, and member functions handle input/output
operations.

Terminology:

 Inheritance: A mechanism where a derived class inherits properties and methods from
a base class.
 Base Class: The parent class (e.g., Person) from which another class inherits.
 Derived Class: The child class (e.g., Student) that inherits from the base class.
 Access Specifier: public, private, or protected, controlling access to class members.
 Constructor: A special function to initialize objects.
 Encapsulation: Restricting access to data members using access specifiers.

Precautions:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 59
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

1. Include <iostream> and <string> for cin, cout, and string usage, with using namespace
std;.
2. Use public inheritance to ensure base class members are accessible in the derived class
as intended.
3. Ensure constructors initialize all data members, including those inherited from the base
class.
4. Use protected for base class members that derived classes need to access directly.
5. Validate input (e.g., valid age, marks) to ensure data integrity.
6. Save the program with a .cpp extension in Dev C++ before compiling.
7. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment11.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include necessary header files: #include <iostream> and #include <string>.
o Use using namespace std; to avoid prefixing std:: for cin, cout, and string.
o Define a base class Person with data members (e.g., name, age) and member
functions.
o Define a derived class Student inheriting from Person with additional data
members (e.g., rollNo, marks).
o Implement constructors and member functions for input and display in both
classes.
o Define the main() function as the program entry point.
o Create a Student object and initialize it using constructors.
o Use cin and getline to accept input for object data.
o Call member functions to display object details.
o Add comments for clarity (e.g., // Define base class Person).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to create a base class Person with name and age, and a derived class
Student with roll number and marks. Use constructors and member functions to input
and display details.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


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

// Base class definition


class Person {
protected:
string name;
int age;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 60
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

public:
// Constructor
Person() {
name = "Unknown";
age = 0;
}

// Member function to input person details


void inputPerson() {
cout << "Enter name: ";
cin.ignore(1); // Clear buffer for getline
getline(cin, name);
cout << "Enter age: ";
cin >> age;
if (age < 0) {
cout << "Invalid age! Set to 0." << endl;
age = 0;
}
}

// Member function to display person details


void displayPerson() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

// Derived class definition


class Student : public Person {
private:
int rollNo;
float marks;

public:
// Constructor
Student() : Person() {
rollNo = 0;
marks = 0.0;
}

// Member function to input student details


void inputStudent() {
inputPerson(); // Call base class input
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter marks (0-100): ";
cin >> marks;
if (marks < 0 || marks > 100) {
cout << "Invalid marks! Set to 0." << endl;
marks = 0;
}
}

// Member function to display student details


void displayStudent() {
cout << "\nStudent Details:" << endl;
displayPerson(); // Call base class display
cout << "Roll Number: " << rollNo << endl;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 61
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

cout << "Marks: " << marks << endl;


}
};

int main() {
// Create student object
Student s1;

// Input student details


s1.inputStudent();

// Display student details


s1.displayStudent();

return 0;
}

5. Sample Output 1:

Enter name: First Name Last Name


Enter age: 20
Enter roll number: 101
Enter marks (0-100): 85

Student Details:
Name: First Name Last Name
Age: 20
Roll Number: 101
Marks: 85

6. Sample Problem 2:
Write a program to create a base class Person with name and age, and a derived class
Student with roll number and marks, using parameterized constructors to initialize
objects.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

// Base class definition


class Person {
protected:
string name;
int age;

public:
// Parameterized constructor
Person(string n, int a) {
name = n;
age = (a >= 0) ? a : 0;
if (a < 0) {
cout << "Invalid age! Set to 0." << endl;
}
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 62
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Member function to display person details


void displayPerson() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

// Derived class definition


class Student : public Person {
private:
int rollNo;
float marks;

public:
// Parameterized constructor
Student(string n, int a, int r, float m) : Person(n, a) {
rollNo = r;
marks = (m >= 0 && m <= 100) ? m : 0;
if (m < 0 || m > 100) {
cout << "Invalid marks! Set to 0." << endl;
}
}

// Member function to display student details


void displayStudent() {
cout << "\nStudent Details:" << endl;
displayPerson();
cout << "Roll Number: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
// Declare variables for input
string name;
int age, rollNo;
float marks;

// Input details
cout << "Enter name: ";
cin.ignore(1); // Clear buffer
getline(cin, name);
cout << "Enter age: ";
cin >> age;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter marks (0-100): ";
cin >> marks;

// Create student object with parameterized constructor


Student s1(name, age, rollNo, marks);

// Display student details


s1.displayStudent();

return 0;
}

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 63
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

8. Sample Output 2:

Enter name: Jane Smith


Enter age: 22
Enter roll number: 102
Enter marks (0-100): 92

Student Details:
Name: Jane Smith
Age: 22
Roll Number: 102
Marks: 92

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program with a Person base class (name, age) and a Student derived
class (roll number), displaying details using inherited methods.
2. Moderate: Write a program with a Person base class and a Student derived class,
adding a member function in Student to calculate grade based on marks.
3. Slightly Difficult: Write a program with a Person base class and a Student derived
class, using an array of Student objects to store and display multiple records.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question Bloom’s Taxonomy


CO
Level
What is inheritance in C++? CO5 K1 (Remembering)
Explain the difference between public and private CO5 K2 (Understanding)
inheritance.
How does a derived class access protected members of a CO5 K2 (Understanding)
base class?
Describe the role of constructors in inheritance. CO5 K2 (Understanding)
Write a code snippet for a Person base class with a display CO5 K3 (Applying)
function.
Analyze the benefits of inheritance in code reuse. CO5 K4 (Analyzing)
How would you ensure proper initialization of base class CO5 K4 (Analyzing)
members in a derived class constructor?
Evaluate when to use inheritance versus composition in OOP CO5 K5 (Evaluating)
design.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 64
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO5 Correct main(), headers, Minor errors in Incorrect structure Major structural Does not compile
Structure using namespace std;, and structure or (e.g., missing errors; barely due to structural
student name/URN as missing headers) but partially compiles. errors.
comment. Highly readable name/URN works.
with comments. comment but
functional.
Inheritance CO5 Correctly implements base Minor errors in Incorrect or partial Inheritance No or incorrect
Implementation and derived classes with inheritance setup inheritance attempted but inheritance
proper inheritance. but functional. implementation. non-functional. implementation.
Constructor CO5 Correctly implements Minor errors in Incorrect or partial Constructor No or incorrect
Usage constructors in base and constructor logic constructor attempted but constructor usage.
derived classes with proper but functional. implementation. non-functional.
initialization.
Input/Output CO5 Uses cin/getline/cout with Minor formatting Incomplete or Minimal No input/output
Operations clear prompts and formatted issues in incorrect input/output; implemented.
output for class data. input/output but input/output usage. unclear output.
functional.
Encapsulation CO5 Uses private/protected for Minor issues in Incorrect use of Minimal No encapsulation
data members and public for access specifiers access specifiers; encapsulation; implemented.
functions, ensuring proper but functional. partial encapsulation. data exposed.
encapsulation.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 65
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Expt. No. 12
Write a Program to Perform File Operations: Write and Read
Date Conducted:
Student Records Using File Streams

Purpose:
To enable students to implement file handling in C++ using file streams (ifstream, ofstream,
fstream) to write and read student records, demonstrating data persistence and management.

Objectives:

1. Understand the use of file streams (ifstream, ofstream, fstream) for file operations in
C++.
2. Implement a program to write student records to a file and read them back.
3. Use structures or classes to organize student data.
4. Write a compilable C++ program with proper syntax, comments, and modular structure.
5. Ensure code readability and proper documentation for submission.

Equipment/Components/Software:

 Hardware: Computer system with Windows/Linux/Mac OS.


 Software: Dev C++ (Version 5.11 or higher recommended).
 Other Requirements: Text editor for writing code, C++ compiler (included in Dev
C++), printer for code/output.

Theory:
This experiment is part of Module VI: Searching, Sorting, and File Handling and aligns with
CO6 (Develop programs using search/sort algorithms and file handling). File handling in C++
involves using file streams from the <fstream> library: ofstream for writing, ifstream for
reading, and fstream for both. Files can store structured data, such as student records (e.g., roll
number, name, marks). A structure or class organizes this data, and file operations enable
persistent storage. Key operations include opening, writing, reading, and closing files. Error
handling ensures robust file operations (e.g., checking if a file opened successfully).

Terminology:

 File Stream: A C++ mechanism to handle file input/output (ifstream, ofstream,


fstream).
 ofstream: Output file stream for writing to files.
 ifstream: Input file stream for reading from files.
 fstream: File stream for both reading and writing.
 Structure: A user-defined type to group related data (e.g., student records).
 File Handling: Operations to read from or write to files for data persistence.

Precautions:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 66
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

1. Include <iostream>, <fstream>, and <string> for file operations and string handling,
with using namespace std;.
2. Check if files open successfully using .is_open() to avoid runtime errors.
3. Close files using .close() after operations to free resources.
4. Validate input data (e.g., positive roll numbers, valid marks) before writing to files.
5. Ensure the file path is accessible and writable in Dev C++.
6. Save the program with a .cpp extension and create a text file (e.g., students.txt) in the
same directory as the program.
7. Check for compilation errors in Dev C++ and resolve them before execution.

Procedure:

1. Setup Dev C++:


o Open Dev C++ on your computer.
o Go to File > New > Source File to create a new C++ file.
o Save the file with a .cpp extension (e.g., experiment12.cpp).
2. Write the Program:
o Add a comment in the first line with your name and University Roll Number
(URN), e.g., // Name: First Name Last Name, URN: 123456.
o Include necessary header files: #include <iostream>, #include <fstream>,
#include <string>.
o Use using namespace std; to avoid prefixing std:: for cin, cout, and file streams.
o Define a structure or class for student data (e.g., roll number, name, marks).
o Declare functions to write and read student records to/from a file.
o Define the main() function as the program entry point.
o Use ofstream to write student records to a file (e.g., students.txt).
o Use ifstream to read and display records from the file.
o Validate input and check file operations for errors.
o Add comments for clarity (e.g., // Write student record to file).
o Return 0 in main() to indicate successful program execution.
3. Sample Problem 1:
Write a program to define a structure for a student (roll number, name, marks), input
one student’s record, write it to a file using ofstream, and read it back using ifstream.
4. Sample Code 1:

// Name: [Your Name], URN: [Your URN]


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

// Structure definition
struct Student {
int rollNo;
string name;
float marks;
};

// Function prototypes
void writeStudentToFile(Student s, const string& filename);
void readStudentFromFile(const string& filename);

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 67
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

int main() {
// Declare student structure
Student s;

// Input student details


cout << "Enter roll number: ";
cin >> s.rollNo;
cin.ignore(); // Clear buffer for getline
cout << "Enter name: ";
getline(cin, s.name);
cout << "Enter marks (0-100): ";
cin >> s.marks;

// Validate input
if (s.rollNo < 0 || s.marks < 0 || s.marks > 100) {
cout << "Invalid input! Program terminated." << endl;
return 1;
}

// Write to file
writeStudentToFile(s, "students.txt");

// Read from file


readStudentFromFile("students.txt");

return 0;
}

// Function to write student record to file


void writeStudentToFile(Student s, const string& filename) {
ofstream outFile(filename);
if (!outFile.is_open()) {
cout << "Error opening file for writing!" << endl;
return;
}
outFile << s.rollNo << " " << s.name << " " << s.marks << endl;
outFile.close();
cout << "Student record written to file successfully." << endl;
}

// Function to read student record from file


void readStudentFromFile(const string& filename) {
ifstream inFile(filename);
if (!inFile.is_open()) {
cout << "Error opening file for reading!" << endl;
return;
}
Student s;
cout << "\nStudent Record from File:" << endl;
inFile >> s.rollNo >> s.name >> s.marks;
cout << "Roll Number: " << s.rollNo << endl;
cout << "Name: " << s.name << endl;
cout << "Marks: " << s.marks << endl;
inFile.close();
}

5. Sample Output 1:

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 68
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Enter roll number: 101


Enter name: First Name Last Name
Enter marks (0-100): 85
Student record written to file successfully.

Student Record from File:


Roll Number: 101
Name: John
Marks: 85

6. Sample Problem 2:
Write a program to store multiple student records in a file using ofstream and read them
back using ifstream, with a structure for student data.
7. Sample Code 2:

// Name: [Your Name], URN: [Your URN]


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

// Structure definition
struct Student {
int rollNo;
string name;
float marks;
};

// Function prototypes
void writeStudentsToFile(Student s[], int size, const string& filename);
void readStudentsFromFile(const string& filename);

int main() {
// Declare variables
int size;

// Input number of students


cout << "Enter number of students (max 50): ";
cin >> size;
if (size <= 0 || size > 50) {
cout << "Invalid size!" << endl;
return 1;
}

// Declare array of students


Student students[50];

// Input student details


for (int i = 0; i < size; i++) {
cout << "\nEnter details for student " << i + 1 << ":" << endl;
cout << "Roll number: ";
cin >> students[i].rollNo;
cin.ignore();
cout << "Name: ";
getline(cin, students[i].name);
cout << "Marks (0-100): ";
cin >> students[i].marks;

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 69
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

// Validate input
if (students[i].rollNo < 0 || students[i].marks < 0 ||
students[i].marks > 100) {
cout << "Invalid input! Setting default values." << endl;
students[i].rollNo = 0;
students[i].marks = 0;
}
}

// Write to file
writeStudentsToFile(students, size, "students.txt");

// Read from file


readStudentsFromFile("students.txt");

return 0;
}

// Function to write student records to file


void writeStudentsToFile(Student s[], int size, const string& filename)
{
ofstream outFile(filename);
if (!outFile.is_open()) {
cout << "Error opening file for writing!" << endl;
return;
}
for (int i = 0; i < size; i++) {
outFile << s[i].rollNo << " " << s[i].name << " " << s[i].marks
<< endl;
}
outFile.close();
cout << "Student records written to file successfully." << endl;
}

// Function to read student records from file


void readStudentsFromFile(const string& filename) {
ifstream inFile(filename);
if (!inFile.is_open()) {
cout << "Error opening file for reading!" << endl;
return;
}
Student s;
cout << "\nStudent Records from File:" << endl;
int i = 1;
while (inFile >> s.rollNo >> s.name >> s.marks) {
cout << "\nStudent " << i++ << ":" << endl;
cout << "Roll Number: " << s.rollNo << endl;
cout << "Name: " << s.name << endl;
cout << "Marks: " << s.marks << endl;
}
inFile.close();
}

8. Sample Output 2:

Enter number of students (max 50): 2

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 70
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Enter details for student 1:


Roll number: 101
Name: First Name Last Name
Marks (0-100): 85

Enter details for student 2:


Roll number: 102
Name: Jane Smith
Marks (0-100): 92
Student records written to file successfully.

Student Records from File:


Student 1:
Roll Number: 101
Name: John
Marks: 85

Student 2:
Roll Number: 102
Name: Jane
Marks: 92

9. Compile and Run:


o In Dev C++, click Execute > Compile (or press F9) to compile the program.
o Check for and resolve any compilation errors displayed in the Dev C++ console.
o Click Execute > Run (or press F10) to execute the program.
o Ensure students.txt is created in the same directory as the program.
o Enter sample inputs and verify the output.
10. Save and Document:
o Save the program in Dev C++.
o Print the code and output from Dev C++.
o Paste the printed code and output in the lab manual for submission.

Practice Questions:

1. Easy: Write a C++ program to write a single student’s roll number and name to a file
and read it back.
2. Moderate: Write a program to append a new student record to an existing file using
fstream in append mode.
3. Slightly Difficult: Write a program to read student records from a file and display only
those with marks above a user-specified threshold.

Oral Questions (Mapped with CO and Bloom’s Taxonomy Level):

Question CO Bloom’s Taxonomy


Level
What is the role of ofstream in file handling? CO6 K1 (Remembering)
Explain the difference between ifstream and ofstream. CO6 K2 (Understanding)
How does fstream support both reading and writing? CO6 K2 (Understanding)
Describe how to check if a file opened successfully. CO6 K2 (Understanding)
Write a code snippet to write a student’s name to a file. CO6 K3 (Applying)
Analyze the risks of not closing a file after operations. CO6 K4 (Analyzing)

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 71
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

How would you handle errors when a file cannot be opened? CO6 K4 (Analyzing)
Evaluate the benefits of using file streams versus manual CO6 K5 (Evaluating)
data entry for student records.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 72
3AEES105 - Programming for
Department of Basic Sciences
problem solving using C++

Rubrics (Total 25 Marks, 5 Criteria, 5 Marks Each):

Criteria CO 5 Marks 4 Marks 3 Marks 2 Marks 1 Mark


Program CO Correct main(), Minor Incorrect Major Does not
Structure 6 headers, using errors in structure structural compile
namespace structure (e.g., errors; due to
std;, and or missing missing barely structural
student name/UR headers) compiles. errors.
name/URN as N but
comment. comment partially
Highly but works.
readable with functional
comments. .
File CO Correctly Minor Partial file File No or
Operations 6 implements errors in operations operations incorrect
Implementat file write and file ; incorrect attempted file
ion read operations operations read/write but non- operations.
using but in some functional.
ofstream/ifstre functional cases.
am. .
Data CO Correctly uses Minor Incomplet Minimal No or
Management 6 structure/class errors in e or data incorrect
to organize and data incorrect organizatio data
store student organizati data n; partial organizatio
data in files. on but organizati functionali n.
functional on. ty.
.
Input/Outpu CO Uses Minor Incomplet Minimal No
t Operations 6 cin/getline/cou formattin e or input/outp input/outp
t and file g issues in incorrect ut; unclear ut
streams with input/outp input/outp output. implement
clear prompts ut but ut usage. ed.
and formatted functional
output. .
Error CO Implements Basic Error Minimal No error
Handling 6 robust error error handling error handling
handling (e.g., handling attempted handling; implement
file open present but program ed.
checks, input but incorrect may crash.
validation). incomplet or
e. ineffective
.

laboratory manual of programming for problem solving using C++ (3AEES105) Page no. 73

You might also like