0% found this document useful (0 votes)
3 views28 pages

C++ Programming Lab Manual-24-25

The document is a lab manual for a C++ programming course (CS4102) for various engineering branches, detailing experiments and programming tasks. It includes aims, algorithms, sample code, inferences, and results for multiple programming exercises, such as implementing constructors, destructors, inheritance, polymorphism, and function overloading. Each experiment is designed to teach fundamental programming concepts through practical coding examples.

Uploaded by

N Dhanvanth
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)
3 views28 pages

C++ Programming Lab Manual-24-25

The document is a lab manual for a C++ programming course (CS4102) for various engineering branches, detailing experiments and programming tasks. It includes aims, algorithms, sample code, inferences, and results for multiple programming exercises, such as implementing constructors, destructors, inheritance, polymorphism, and function overloading. Each experiment is designed to teach fundamental programming concepts through practical coding examples.

Uploaded by

N Dhanvanth
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/ 28

REGULATION 2024

LAB MANUAL

CS4102- C++ Programming

I SEMESTER
COMMON TO CSE, IT,AI&DS,AI&ML,CSBS,CZ
BRANCHES

Name of the Student :

Register Number :

Year / Semester / Section :

Batch :
1
CONTENT
EXP. DATE
SIGN OF
NO OF TITLE CO PO MARKS
THE
THE Mapped Mapped
FACULTY
EXP
1. C PROGRAM TO PO1,PO2,PO3
IMPLEMENT HALF
CO1
PYRAMID USING ‘*’
2. C PROGRAM TO PO1,PO2,PO3
CO1
IMPLEMENT GCD USING
FUNCTION
3. C PROGRAM TO FIND A
PO1,PO2,PO3
PRIME NUMBER
CO1

4. C++ PROGRAM TO PO1,PO2,PO3


IMPLEMENT
CONSTRUCTOR AND
CO2
DESTRUCTOR
5. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT COPY CO2
CONSTRUCTOR
6. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT
OVERLOADING
CO2
FUNCTIONS
7. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT INHERITANCE
CO3
8. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT CO3
POLYMORPHISM
9. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT TEMPLATES
CO4
10. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT MAX CO4
FUNCTION TEMPLATE
11. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT EXCEPTION CO4
HANDLING
12. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT EXCEPTION
HANDLING USING WHAT
CO4
FUNCTION
13. C++ PROGRAM TO PO1,PO2,PO3
IMPLEMENT FILE CO5
OPERATIONS

2
EX.NO: 1
C PROGRAM TO IMPLEMENT HALF PYRAMID USING ‘*’
DATE:

AIM:
To write a C program for printing half pyramid using ‘*’

ALGORITHM:
Step 1: Start the program.
Step 2: Repeat the steps 3 to 5.
Step 3: Repeat the step 4.
Step 4: Display *.
Step 5: Go to next line.
Step 6: Stop the program.

PROGRAM:
#include <stdio.h>

int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=0; j<i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}

INFERENCE:
For loops are used in C are used to facilitate the execution of a code block a specified number of
times by assessing a condition as either true or false. Through this program we learnt how to use
for loops for pattern printing.

RESULT:

The program was successfully executed and the output was got.

3
EX.NO: 2
C PROGRAM TO IMPLEMENT GCD USING FUNCTION
DATE:

AIM:
To write a C program to find the GCD (Greatest Common Divisor)of two numbers using a function.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialize the two numbers.
Step 3: Call the GCD function.
Step 4: Display the numbers and GCD.
Step 5: Stop the program.

Subprogram for Function


Step 1: Start the function.
Step 2: If first number is 0 then second number is retuned ass GCD.
Step 3: If second number is 0 the first number is returned as GCD.
Step 4: If both the numbers are equal the first number is returned as GCD
Step 5: If first number is greater than second number then the function called again with value
first number –second number and second number.
Step 6: If second number is greater than first number then the function called again with value
first number and second number- first number.
Step 7: GCD value is returned to the main function.
Step 8: Stop the function.

PROGRAM:
#include<stdio.h>
int calcGCD(int n1, int n2)
{
// Takes care of the case n1 is 0
if (n1 == 0)
return n2;
// Takes care of the case n2 is 0
if (n2 == 0)
return n1;
// base case
if (n1 == n2)
return n1;
// n1 is greater
4
if (n1 > n2)
return calcGCD(n1 - n2, n2);
// n2 is greater
return calcGCD(n1, n2 - n1);
}

int main()
{
int n1 = 45, n2 = 18;
int gcd = calcGCD(n1, n2);
printf("The GCD of %d and %d is: %d", n1, n2, gcd);
return 0;
}

INFERENCE:
A function in C is a set of statements that when called perform some specific task. Through this
program we learnt how to implement a function for GCD.

RESULT:

The program was successfully executed and the output was got.

5
EX.NO: 3
C PROGRAM TO FIND A PRIME NUMBER
DATE:

AIM:
Write a C program to check if a given number is a prime number.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialize the three variables.
Step 3: Get number form user.
Step 4: Repeat the steps from 5 to 6 till the number divided by 2 times
Step 5: if the number is divided by any other number the temp variable is incremented.
Step 6: Go out of repetition.
Step 7: if temp variable is zero and num is not equal to 1 then display number is Prime.
Step 8: Otherwise display the number is not prime.
Step 8: Stop the program.

PROGRAM:
#include <stdio.h>
int main()
{
int i, num, temp = 0;
// read input from user.
printf("Enter the number you want to Check for Prime: ");
scanf("%d", &num);
// Run loop for num/2
for (i = 2; i <= num / 2; i++)
{
// check if given number is divisible by any number.
if (num % i == 0)
{
temp++;
break;
}
}
// check for the value of temp and num.
if (temp == 0 && num != 1)
{
printf(“%d is a Prime number”, num);
}

6
else
{
printf("%d is not a Prime number", num);
}
return 0;
}

INFERENCE:
For loop implements a state of statements and if condition checks the condition needed for that
particular application. Through this program we learnt how to combine for loop and if condition
for finding a prime number.

RESULT:

The program was successfully executed and the output was got.

7
EX.NO: 4
C++ PROGRAM TO IMPLEMENT CONSTRUCTOR AND
DESTRUCTOR
DATE:

AIM:
To Implement a C++ program to create a class called “simple class” and also to create a constructor,
destructor for this class called simpleclass

ALGORITHM:
Step 1: Start the program.
Step 2: Create a class called Simpleclass.
Step 3: Create a constructor for this class.
Step 4: Create a destructor for this class.
Step 5: In the main class create an object for the class simpleclass.
Step 6: Messages are displayed when constructor and destructor are called.
Step 7: Stop the program.

PROGRAM:
#include <iostream>
class SimpleClass {
public:
// Constructor
SimpleClass() {
std::cout << "SimpleClass Constructor called" << std::endl;
}
// Destructor
~SimpleClass() {
std::cout << "SimpleClass Destructor called" << std::endl;
}
};

int main() {
// Creating an object of SimpleClass
SimpleClass obj;

// Object goes out of scope here, so the destructor will be called


return 0;
}

8
INFERENCE:
A constructor is a special member function of a class and shares the same name as of class.
Through this program we learnt implement constructor and destructor.

RESULT:

The program was successfully executed and the output was got.

9
EX.NO: 5
C++ PROGRAM TO IMPLEMENT COPY CONSTRUCTOR
DATE:

AIM:
To Implement a C++ program for a Copy Constructor. Create a Person class with a name and an age
and create a copy constructor to create a new object with the same name and age as the source
object.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a class called Person with name and age.
Step 3: Create a constructor for this class.
Step 4: Copy this constructor with the members .
Step 5: In the main class create an object for the class person.
Step 6: Display the members of the class person.
Step 7: Create an object for object of the class person.
Step 8: Display the members of the copied class.
Step 9:Stop the program.

PROGRAM:
#include <iostream>
#include <string> // For std::string
using namespace std;
class Person {
private:
string name;
int age;
public:
// Constructor
Person(const string& personName, int personAge) {
name = personName;
age = personAge;
cout << "Constructor: Name is " << name << " and Age is " << age << endl;
}
// Copy Constructor
Person(const Person &obj) {
name = obj.name;
age = obj.age;
cout << "Copy Constructor: Name is " << name << " and Age is " << age << endl;
}
// Destructor
~Person() {
cout << "Destructor: Memory to be released for " << name << endl;

10
}
// Function to change name
void setName(const string& newName) {
name = newName;
}
// Function to display Person details
void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Creating a Person object
Person person1("Vijay", 50);

// Copying person1 to person2 using the copy constructor


Person person2 = person1;

// Display both objects


cout << "\nBefore changing name:" << endl;
person1.display();
person2.display();

// Change the name of person1


person1.setName("Joseph");

// Display both objects again to show they are independent


cout << "\nAfter changing name of person1:" << endl;
person1.display();
person2.display();
return 0;
}
INFERENCE:
A constructor is a special member function of a class and shares the same name as of class.
Through this program we learnt implement copy constructor.

RESULT:

The program was successfully executed and the output was got.

11
EX.NO: 6
C++ PROGRAM TO IMPLEMENT OVERLOADING FUNCTIONS
DATE:

AIM:
To Implement a C++ program for Overloading Functions with Different Number of Parameters
for addition in a calculator.

ALGORITHM:
Step 1: Start the program.
Step 2: Read two numbers
Step 3: Call the function add for adding two numbers.
Step 4: Return the sum of two numbers.
Step 5: Display the sum of two numbers.
Step 6: Read three numbers.
Step 7: Call the function add for adding three numbers.
Step 8: Display the sum of three numbers.
Step 9: Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}

// Function to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

int main() {
int num1, num2, num3, num4;

// Adding two numbers


cout << "Enter two numbers to add: ";
cin >> num1 >> num2;
cout << "Sum: " << add(num1, num2) << endl;

// Adding three numbers

12
cout << "Enter three numbers to add: ";
cin >> num1 >> num2 >> num3;
cout << "Sum: " << add(num1, num2, num3) << endl;
return 0;
}

INFERENCE:
Function overloading is a feature of object-oriented programming where two or more functions
can have the same name but different parameters. When a function name is overloaded with
different jobs it is called Function Overloading. In Function Overloading “Function” name should
be the same and the arguments should be different. Through this program we learnt implement
function for addition.

RESULT:

The program was successfully executed and the output was got.

13
EX.NO: 7
C++ PROGRAM TO IMPLEMENT INHERITANCE
DATE:

AIM:
To Implement a C++program for Inheritance for calculating the area of a triangle.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a class shape.
Step 3: Declare variables and functions.
Step 4: Function setbase is inherited from shape.
Step 5: Read triangle base.
Step 6: Function setheight is inherited from shape.
Step 7: Read triangle height.
Step 8: Class triangle is inherited form shape.
Step 9: Display area of triangle.
Step 10: Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
class shape
{
protected:
int base,height;
public:
void setbase();
void setheight();
};
void shape::setbase()
{
cout<<" Enter base of triangle : ";
cin>>base;
}
void shape::setheight()
{
cout<<" Enter height of triangle : ";
cin>>height;
}
class triangle:public shape{

14
public:
int area;
void trianglearea(){
area=(0.5)*height*base;
cout<<" height of triangle : "<<height <<endl;
cout<< " base of traingle : "<<base <<endl;
cout<< " area of traingle is : "<<area <<endl;
}
};

int main(void)
{
cout<<" triangle started "<<endl;
triangle t1;
t1.setbase();
t1.setheight();
t1.trianglearea();
cout<<endl;
}

INFERENCE:

In C++, inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. Through this program we learnt implement inheritance for finding
area of triangle.

RESULT:

The program was successfully executed and the output was got.

15
EX.NO: 8
C++ PROGRAM TO IMPLEMENT POLYMORPHISM
DATE:

AIM:
To Implement a C++ program that demonstrates polymorphism using a basic example of shapes.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a class shape.
Step 3: Declare a function area..
Step 4: Class circle is inherited from shape.
Step 5: Function area is declared.
Step 6: Class circle is inherited from shape.
Step 7: Function area is declared.
Step 8: Create an object for class shape.
Step 9: Call area through that object.
Step 10: Create an object for class circle.
Step 11: Call area through that object.
Step 12: Create an object for class rectangle.
Step 13: Call area through that object.
Step 14: Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
class Shape
{
public:
void area()
{
cout << "Base Class" << endl;
}
};
class Circle : public Shape
{
public :
void area()
{
cout << "Area of Circle" << endl;
}
};
class Rectangle : public Shape

16
{
public :
void area()
{
cout << "Area of rectangle" << endl;
}
};

int main()
{
Shape a;
a.area();
Circle p;
p.area();
Rectangle q;
q.area();
return 0;
}

INFERENCE:

Polymorphism is an important concept of object-oriented programming. It simply means more


than one form. That is, the same entity (function or operator) behaves differently in different
scenarios. Through this program we learnt implement inheritance for basic shapes.

RESULT:

The program was successfully executed and the output was got.

17
EX.NO: 9
C++ PROGRAM TO IMPLEMENT TEMPLATES
DATE:

AIM:
To define a template for example stack. Define a template parametertype name T which will
represent the data type that the stack will hold. Define the class methods push, pop, empty and size
having their respective data types. Create two instances of the stack in the main function, one for
integers and the other for double. Perform stack operations.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a instance to stack template.
Step 3: Use instance to push element into stack.
Step 4: Display the top of the stack using instance.
Step 5: Display the size of the stack using instance.
Step 6: Use instance to pop element from stack.
Step 7: Display the size of the stack using instance after pop.
Step 8: Create a instance to stack template for floating point numbers.
Step 9: Use instance to push element into stack for floating point numbers.
Step 10: Display the top of the stack using instance for floating point numbers.
Step 11: Display the size of the stack using instance for floating point numbers.
Step 12: Use instance to pop element from stack for floating point numbers.
Step 13: Display the size of the stack using instance after pop for floating point numbers.
Step 14: Create a TEMPLATE using <typename T>.
Step 15: Create a class stack.
Step 16: Create a vector for storing elements in the stack.
Step 17: Create push method for pushing elements into stack.
Step 18: Create pop method to remove elements from stack.
Step 19: Create empty method to check if stack is empty.
Step 20: Create size method to find the size of the stack.
Step 21: Create a method top to get the top element in the stack.
Step 22: Stop the program.

PROGRAM:
#include <iostream>
#include <stdexcept>
using namespace std;
// Stack template class
template <typename T>
class Stack {
private:
T* arr;
int top;
18
int capacity;

public:
// Constructor to initialize the stack
Stack(int size) {
capacity = size;
arr = new T[capacity];
top = -1;
}

// Destructor to clean up allocated memory


~Stack() {
delete[] arr;
}

// Method to push an element onto the stack


void push(T value) {
if (top == capacity - 1) {
throw overflow_error("Stack overflow");
}
arr[++top] = value;
}

// Method to pop an element from the stack


T pop() {
if (top == -1) {
throw underflow_error("Stack underflow");
}
return arr[top--];
}

// Method to check if the stack is empty


bool empty() const {
return top == -1;
}

// Method to get the size of the stack


int size() const {
return top + 1;
}
};

int main() {
// Create a stack for integers
Stack<int> intStack(10);
intStack.push(10);

19
intStack.push(20);
cout << "Integer Stack Size: " << intStack.size() << endl;
cout << "Popped from Integer Stack: " << intStack.pop() << endl;
cout << "Is Integer Stack Empty? " << (intStack.empty() ? "Yes" : "No") << endl;

// Create a stack for doubles


Stack<double> doubleStack(5);
doubleStack.push(3.14);
doubleStack.push(2.71);
cout << "Double Stack Size: " << doubleStack.size() << endl;
cout << "Popped from Double Stack: " << doubleStack.pop() << endl;
cout << "Is Double Stack Empty? " << (doubleStack.empty() ? "Yes" : "No") << endl;

return 0;
}

INFERENCE:
Templates are a feature of the C++ programming language that allows functions and classes to
operate with generic types. Through this program we learnt implement templates with the help of
stack.

RESULT:

The program was successfully executed and the output was got.

20
EX.NO: 10
C++ PROGRAM TO IMPLEMENT MAX FUNCTION TEMPLATE
DATE:

AIM:
Create a max function template using template keyword. Create a template parameter using the
declaration <typename T>. this template should act as place holder for the actual type that will be
used when the function is instantiated. The max function created takes two parameters of the type
T and should return the maximum of two values. Create a main function. This template should be
used by calling both integer and double values.

ALGORITHM:
Step 1: Start the program.
Step 2: Read integer inputs.
Step 3: Call max method for integer inputs.
Step 4: Display the result.
Step 5: Read floating point inputs.
Step 6: Call max method for floating point inputs.
Step 7: Display the result.
Step 8: Create a template
Step 9: Use template to create a max method to find the maximum of two numbers.
Step 10: Return the result.
Step 11: Stop the program.

PROGRAM:
#include <iostream>
// Template function definition for max
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Use the max function template with integers
int int1 = 10;
int int2 = 20;
std::cout << "Max of " << int1 << " and " << int2 << " is: " << max(int1, int2) << std::endl;

// Use the max function template with doubles


double double1 = 3.14;
double double2 = 2.718;
std::cout << "Max of " << double1 << " and " << double2 << " is: " << max(double1, double2)
<< std::endl;
return 0; }

21
INFERENCE:
Templates in c++ are defined as a blueprint or formula for creating a generic class or a function.
Through this program we learnt implement templates with the help of max function.

RESULT:

The program was successfully executed and the output was got.

22
EX.NO: 11
C++ PROGRAM TO IMPLEMENT EXCEPTION HANDLING
DATE:

AIM:
To implement c++ program for the try block containing the code that might potentially raise an
exception. In this case, it attempts to perform a division operation and throws a std::runtime error
exception if the denominator is zero. The catch block catches any exception of type std::exception(or
its derived classes)and displays an error message.

ALGORITHM:
Step 1: Start the program.
Step 2: Read numerator and denominator.
Step 3: Under the try block call divide function.
Step 4: Display the result if no error.
Step 5: Catch block is called if there is an error.
Step 6: Division function checks if the denominator is 0 and throws an error.
Step 7: Stop the program.

PROGRAM:

#include <iostream>
#include <stdexcept>
using namespace std;
// Function to perform division
double divide(double numerator, double denominator) {
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
}
return numerator / denominator;
}

int main() {
double num, denom, result;
cout << "Enter numerator: ";
cin >> num;
cout << "Enter denominator: ";
cin >> denom;

try {
result = divide(num, denom);
cout << "Result: " << result << endl;

23
} catch (const std::runtime_error&) {
cerr << "Error: Division by zero is not allowed." << endl;
}

return 0;
}

INFERENCE:
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution. Through this program we learnt implement exception handling using division
operation.

RESULT:

The program was successfully executed and the output was got.

24
EX.NO: 12
C++ PROGRAM TO IMPLEMENT EXCEPTION HANDLING USING
WHAT FUNCTION
DATE:

AIM:
To implement a C++ program to perform division based on user inputs for numerator and
denominator. If the user enters a denominator of 0, a std::runtime error exception must be thrown
with a custom error message. The try block must contain the code that might throw an exception,
and the catch block must catch the exception and display the error message using the what ()
function of the exception object. Regardless of whether an exception is thrown or not, the program
must continue executing after the exception handling block.

ALGORITHM:
Step 1: Start the program.
Step 2: Read numerator and denominator.
Step 3: Under the try block call divide function.
Step 4: Display the result if no error.
Step 5: Catch block is called if there is an error.
Step 6: Division function checks if the denominator is 0 and throws an error.
Step 7: Error is thrown using what function.
Step 8: Program continues after error display.
Step 9: Stop the program.

PROGRAM:
#include <iostream>
#include <stdexcept>
using namespace std;
// Function to perform division
double divide(double numerator, double denominator) {
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
}
return numerator / denominator;
}

int main() {
double num, denom, result;

cout << "Enter numerator: ";


cin >> num;
cout << "Enter denominator: ";
cin >> denom;

try {

25
result = divide(num, denom);
cout << "Result: " << result << endl;
} catch (const std::runtime_error& e) {
cerr << "Error: " << e.what() << endl;
}

cout << "Program continues executing after exception handling block." << endl;

return 0;
}

INFERENCE:
An exception is an unexpected problem that arises during the execution of a program our program
terminates suddenly with some errors/issues. Exception occurs during the running of the program
(runtime). Through this program we learnt implement exception handling using division operation
and display the error using what function.

RESULT:

The program was successfully executed and the output was got.

26
EX.NO: 13
C++ PROGRAM TO IMPLEMENT FILE OPERATIONS
DATE:

AIM:
To Implement a c++ program which includes the necessary header files: <iostream> for
input/output operations and <fstream> for file stream operations. Use an of stream object to write
data to the file named "output.txt". There should be a check if the file is opened successfully. Use <<
operator to write data to the file, and use close () method for closing the file. Use if stream object to
read data from the same file, use close () method for closing the file. The program must return0 to
indicate successful execution.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a file to write text.
Step 3: Write Data to the File, add a few lines of text to the file.
Step 4: Close the File
Step 5: Open the same file to read the text.
Step 6: Read each line from the file and display it on the screen.
Step 7: Close the file after reading.
Step 8: Stop the program

PROGRAM:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create an ofstream object to write to a file
ofstream outFile("output.txt");

// Check if the file was opened successfully


if (!outFile) {
cerr << "Error opening file for writing." << endl;
return 1; // Return non-zero to indicate error
}

// Write data to the file


outFile << "Hello, this is a test message!" << endl;
outFile << "Writing another line to the file." << endl;

// Close the file


outFile.close();

27
// Create an ifstream object to read from the file
ifstream inFile("output.txt");

// Check if the file was opened successfully


if (!inFile) {
cerr << "Error opening file for reading." << endl;
return 1; // Return non-zero to indicate error
}

// Read data from the file


string line;
while (getline(inFile, line)) {
cout << line << endl; // Print each line to the console
}

// Close the file


inFile.close();

// Return 0 to indicate successful execution


return 0;
}

INFERENCE:
File handling in C++ is a mechanism to create and perform read/write operations on a file. Through
this program we learnt implement operations in files.

RESULT:

The program was successfully executed and the output was got.

28

You might also like