0% found this document useful (0 votes)
16 views23 pages

C++ Programs for Basic Algorithms

The document outlines a series of C++ programming exercises aimed at various computational tasks such as calculating sums, finding GCD, and checking for palindromes. Each exercise includes a clear aim, algorithm steps, and a result indicating successful execution. The exercises cover a range of topics including arrays, strings, classes, and inheritance.

Uploaded by

R.V.Maniessh Ram
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)
16 views23 pages

C++ Programs for Basic Algorithms

The document outlines a series of C++ programming exercises aimed at various computational tasks such as calculating sums, finding GCD, and checking for palindromes. Each exercise includes a clear aim, algorithm steps, and a result indicating successful execution. The exercises cover a range of topics including arrays, strings, classes, and inheritance.

Uploaded by

R.V.Maniessh Ram
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

Ex.

No: 1 Sum of Individual Digits of a Positive Integer

Date:

Aim

To write a C++ program to calculate the sum of individual digits of a positive integer.

Algorithm

Step 1: Declare the required variables for input, process and output.

Step 2: Prompt for positive number input form the user.

Step 3: Initialize sum variable = 0.

Step 4: Use looping statement to perform the below steps

 While extracting the last digit of num add it to the sum (sum += num % 10)

 Reduce the number (num = num / 10).

 Repeat doing this until num becomes 0.

Step 5: Output the Sum:

 Print the total sum of the marks.

Result:

Thus, the given C++ program was successfully executed and verified.
Ex. No: 2 GCD of Two Numbers

Date:

Aim

To write a C++ program to calculate the Greatest Common Divisor of two numbers.

Algorithm

Step 1: Declare the required variables for input, process and output.

Step 2: Prompt for positive number inputs (a,b) form the user.

Step 3: Find the product of a and b.

Step 4: Find the Least Common Multiple (LCM) of a and b.

Step 5: Divide the product of the numbers by the LCM of the numbers.

Step 6: The obtained value after division is the greatest common divisor of a and b.

Result:

Thus, the given C++ program was successfully executed and verified.
Ex. No: 3 Square Root of a Number

Date:

Aim

Write a C++ program that calculates the square root of a given number using Newton's method.

Algorithm

Step 1: Declare the required variables for input, process and output.

Step 2: Prompt for positive number whose square root has to be calculated from the user.

Step 3: Call the user defined function to calculate the square root of given number using Newtons method.

User Defined Function:


Step 3.1: Declare variables guess, nextguess.
Step 3.2: Assign 1e-7 as the value of tolerance.
Step 3.3: Calculate nextGuess=0.5*(guess + n/guess);
Step 3.4: If absolute value of nextguess is lower than tolerance
Exit the loop.
else
Assign the value of newguess to guess.
Step 3.5: Return nextguess.

Step 4: Display the square root returned back by the function.

Result:

Thus, the given C++ program was successfully executed and verified.
Ex. No: 4 Maximum of An Array of Numbers

Date:

Aim

Write a C++ program that calculates the maximum of an array of numbers.

Algorithm

Step 1: Declare the required variables for input, process and output.

Step 2: Prompt for positive integer, n , representing the size of the array.

Step 3: Prompt for n positive integers as array contents.

Step 4: Assume the first array element as the maximum.

Step 5: compare the second array element with the current maximum value.

Step 6: If found greater, make it as the current maximum.

Step 7: Repeat the process till all array elements are compared. Ensure maximum is updated accordingly.

Step 8: Return the maximum.

Result:

Thus, the given C++ program was successfully executed and verified.
Ex. No: 5 Removing duplicates using strings
Date:
Aim
To write a C++ program that removes duplicate elements from an array and prints the array with unique
elements.

Algorithm
Step 1: Input the Size of the Array:
o Declare an integer n to store the size of the input array.
o Read the size n using cin.
Step 2: Input the Array Elements:
o Declare an array A of size 10 to store the input.
o Use a loop to read n elements into array A.
Step 3: Initialize Variables:
o Declare another array B of size 10 to store unique elements.
o Use an integer k to track the number of unique elements in B, initializing it to 0.
Step 4: Remove Duplicates:
o Use a nested loop to compare each element of A with the elements in B:
 For each element A[i], iterate over B (from 0 to k-1).
 If A[i] matches any element in B, break the inner loop.
 If no match is found (j == k), add A[i] to B and increment k.
Step 5: Output the Unique Elements:
o Use a loop to print the first k elements of B, separated by spaces.
Step 6: End the Program:
o Return 0 to indicate successful execution.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 6 Removing even numbers
Date:
Aim
To write a C++ program to identify and display all odd numbers in an array of integers entered by the user.

Algorithm
Step 1: Input the Size of the Array:
o Declare an integer n to store the size of the array.
o Read the value of n using cin.
Step 2: Declare the Array:
o Create an array arr of size n.
Step 3: Input the Array Elements:
o Use a for loop to iterate from 0 to n - 1.
o Read each element into the array using cin.
Step 4: Check for Odd Numbers:
o Declare a boolean variable hasOdd and set it too false.
o Use another for loop to iterate through the array.
 For each element, check if it is odd using the condition arr[i] % 2 != 0.
 If the condition is true, print the element and set has Odd to true.
Step 5: Output Results:
o After the loop, all odd numbers from the array will be printed in a single line.
o The program does not explicitly check for hasOdd to display further messages (e.g., "No odd
numbers found"), but it can be extended to include such a feature if needed.

Step 6: End the Program:


o Return 0 to indicate successful execution.

Result:
Thus, the given C++ program was successfully executed and verified.

[Link]: 7 Write a C++ program to check whether a given string is palindrome or not.
Date:
Aim

To write a C++ program to check whether a given string is a palindrome. A string is considered a palindrome
if it reads the same backward as forward.

Algorithm

Step 1: Input the String:

o Declare a string variable to hold the input.

o Use cin to accept the string from the user.

Step 2: Initialize Variables:

o Declare two integer variables:

 start, initialized to 0, representing the beginning of the string.

 end, initialized to [Link]() - 1, representing the last index of the string.

o Declare a boolean variable is Palindrome and set it to true.

Step 3: Check for Palindrome:

o Use a while loop to iterate as long as start is less than end.

 Compare the characters at positions start and end.

 If they are not equal, set is Palindrome to false and break the loop.

 Increment starts and decrement end to move inward.

Step 4: Output the Result:

o If is Palindrome is true, print "Palindrome".

o Otherwise, print "Not a Palindrome".

Step 5: End the Program:

o Return 0 to indicate successful execution.


Result: Thus, the given C++ program was successfully executed and verified.
[Link] Write a C++ program to count the occurrences of each character in a given word

Date:

Aim

To write a C++ program that counts the frequency of each character in a given string using a map and displays
the result.

Algorithm

Step 1: Input the String:

o Declare a string variable to hold the input.

o Use cin to accept a string from the user.

Step 2: Initialize Data Structures:

o Declare a map of type <char, int> to store characters as keys and their frequencies as values.

Step 3: Populate the Map:

o Iterate through each character in the string using a for loop.

o For each character, increment its count in the map.

Step 4: Iterate and Display:

o Use a map iterator (map<char, int>::iterator) to traverse the map.

o For each element in the map, print the character (key) and its frequency (value).

Step 5: Stop the program.

Result:
Thus, the given C++ program was successfully executed and verified.
Ex. No: 9 Sum of marks of the student by using pointers

Date:
Aim
To write a C++ program to calculate the Sum of marks of the student by using pointers.

Algorithm
Step 1: Define the Marks Array:
 Declare an array to store the marks of 5 subjects for a student.
Step 2: Use Pointer to Traverse the Array:
 Declare a pointer to point to the first element of the array.
 Use the pointer to traverse through each element of the array and accumulate the sum of marks.
Step 3: Input Marks:
 Take input for the marks of 5 subjects using a loop, storing the values in the array.
Step 4: Calculate the Sum Using Pointer:
 Initialize a variable sum to 0.
 Use the pointer to access each element of the array and add the marks to sum.
Step 5: Output the Sum:
 Print the total sum of the marks.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 10 Salary Slip
Date:
Aim
To write a C++ program to generate salary slips of employees using structures and pointers.

Algorithm
Step 1: Define the Structures:
 Define a nested structure Date to store the date in the format (Day, Month, Year).
 Define the main structure Employee which will have the following members:
o EID: Employee ID (integer).
o Ename: Employee name (string).
o Designation: Employee designation (string).
o DOB: Employee date of birth (using Date structure).
o DOJ: Employee date of joining (using Date structure).
o Basicpay: Employee basic pay (float).
Step 2 : Create Employee Object Using Pointer:
 Declare a pointer to Employee and dynamically allocate memory for an employee.
Step 3: Input Employee Details:
 Use pointer arithmetic to input employee details such as ID, name, designation, date of birth, date
of joining, and basic pay.
Step 4: Generate Salary Slip:
 Calculate the salary (or other benefits) based on basic pay, and generate a salary slip that displays
all the details of the employee.
Step 5: Output Salary Slip:
 Display the employee's salary slip, showing all the information entered, including the calculated
salary.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 11 Find maximum and minimum element in an array using inline function
Date:
Aim

To write a C++ program to find the maximum and minimum elements in an integer array using inline
functions.

Algorithm

Step 1: Define Inline Functions:

 Define two inline functions:

o maxArray(int arr[], int size): This function will take the array and its size as arguments and
return the maximum value from the array.

o minArray(int arr[], int size): This function will take the array and its size as arguments and
return the minimum value from the array.

Step 2 : Input Array Size and Elements:

 Prompt the user to enter the size of the array.

 Dynamically allocate an array of that size.

 Input the integers into the array.

Step 3: Call Inline Functions:

 Call the maxArray function to find the maximum element in the array.

 Call the minArray function to find the minimum element in the array.

Step 4: Display the Results:

 Display the maximum and minimum values found by the functions.


Result: Thus, the given C++ program was successfully executed and verified.
[Link] Calculator class using constructors and destructor

Date:

Aim

To write a C++ program to create a Class Calculator using Constructor and Destructor.

Algorithm

Step 1: Define the Calculator Class:


 Attributes:
o operand1 (double): First operand for the operation.
o operand2 (double): Second operand for the operation.
o operation (char): The operation to be performed (+, -, *, /).
 Methods:
o Constructor (Default Constructor): Initialize operand1 and operand2 to 0, and operation to +.
o Constructor (Parameterized Constructor): Initialize operand1, operand2, and operation with
specified values.
o Destructor: To clean up if necessary (e.g., for resource management, though it's not required
in this basic example).
o performOperation() Method: Perform the operation based on the input values of the operands
and the operation, then return the result.
Step 2: Input and Output:
 Prompt the user to input the operands and the operation.
 The program will create an instance of the Calculator class (using the parameterized constructor with
user input).
 Call the performOperation() method to compute the result and display it.
Step 3: Error Handling:
 Handle division by zero by checking if the second operand is zero when performing division.
 Handle invalid operations by checking if the operation is one of the valid ones (+, -, *, /).
Step 4: Cleanup:
 The destructor will be automatically called when the Calculator object goes out of scope, but no
dynamic memory allocation is used, so no explicit cleanup is necessary.
Result:
Thus, the given C++ program was successfully executed and verified.

Ex. No: 13 Distance converter using friend function

Date:
Aim
To write a C++ program that demonstrates the usage of a friend function by definining a class
called DistanceConverter with a private member variable kilometers and declare a friend function
named convertToMiles that takes a DistanceConverter object as a parameter and converts the distance
from kilometers to miles display the result.
Algorithm
Step 1: Define a class DistanceConverter and add a private member variable kilometers to store the
distance in kilometers.
Step 2: Provide a constructor to initialize kilometers.
Step 3: Provide a public member function to display the value of kilometers.
Step 4: Declare a friend function convertToMiles inside the DistanceConverter class.
Step 5: This function will access the private member kilometers.
Step 6: Implement the convertToMiles function to convert the value of kilometers to miles.
Step 7: Display the converted value.
Step 8: Instantiate an object of the DistanceConverter class.
Step 9: Call the friend function and pass the object as an argument.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 14 Display the student's information - Multiple Inheritance
Date:
Aim
To write a C++ program to display the student’s information using multiple inheritance.
Algorithm
Step 1: Define the Student Class and add private attributes for name (student's name) and id (student's ID),
provide a constructor to initialize these attributes and include a method to display the student's information.
Step 2: Define the Worker Class and add private attributes for hourlyWage and hoursWorkedPerWeek,
provide a constructor to initialize these attributes and include a method to display the worker's information.
Step 3: Define the PartTimeWorkerStudent Class and use multiple inheritance to inherit from both Student
and Worker, provide a constructor that initializes the attributes of both base classes by calling their
constructors and include a method to display the part-time worker student's information by combining details
from both the Student and Worker classes.
Step 4: Create the main Function by instantiating an object of the PartTimeWorkerStudent class and display
the information of the part-time worker student using the class's display method.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 15 Display Employee information - Multi level inheritance
Date:
Aim

To write a C++ program to display Employee information using Multi level inheritance. Algorithm

Step 1: Define the Base Class Employee and add private attributes id (int) and name (string), create a
constructor to initialize these attributes and provide a method to display employee information.

Step 2: Define the Derived Class Performance and inherit from the Employee class, add private attributes to
store ratings for qualityOfWork, punctuality, and teamwork (all floats), create a constructor to initialize these
attributes along with the base class attributes and provide a method to display the performance ratings.

Step 3: Define the Further Derived Class Result, inherit from the Performance class and add private attributes
overallRating (float) and grade (char), provide a method to calculate the overall performance rating as the
average of all ratings and Implement logic to assign a grade based on the following criteria: A: 90-100, B:
75-89, C: 50-74, D: Below 50, provide a method to display the overall rating and grade.

Step 4: Create the main Function and instantiate an object of the Result class with employee details and
performance ratings, call methods to calculate the overall rating and display all details.

Result: Thus, the given C++ program was successfully executed and verified.
[Link] Implementation of media content using inheritance.

Date:

Aim

To write a C++ program to create a media content using inheritance.

Algorithm

Step 1: Define the Base Class Media:


 Add attributes:
o title (string): Name of the media content.
o duration (int): Duration of the media content in minutes.
 Implement methods:
o play(): Simulate playing the media content.
o getDescription(): Return a generic description of the media content.
Step 2: Define Subclasses Movie, Song, and TVShow:
 Inherit from the Media class.
 Add content-specific attributes if needed (e.g., genre for Movie, artist for Song, number of episodes
for TVShow).
 Override the play() method to provide media-specific play behavior.
 Override the getDescription() method to provide media-specific details.
Step 3: Create Instances:
 Instantiate objects of Movie, Song, and TVShow.
 Provide unique attributes for each instance.
Step 4: Demonstrate Functionalities:
 Call the play() and getDescription() methods on each instance.
 Observe and ensure the overridden methods exhibit subclass-specific behavior.

Result:
Thus, the given C++ program was successfully executed and verified.
Ex. No: 17 Implementing Library Managing System
Date:
Aim:
To write a C++ program to manage a collection of books, allowing the user to input and store details of
both fiction and non-fiction books. The program uses classes, inheritance, and polymorphism to handle
different types of books, store their properties, and display them appropriately. The program also
demonstrates the use of dynamic memory management to create and delete book objects.
Algorithm:
1. Class Definitions:
o Define a Book class that holds the basic details of a book: title, author, and ISBN. It has a
displayDetails() function that outputs the basic details of the book.
o Define a FictionBook class that inherits from Book. It adds a genre attribute and overrides
the displayDetails() function to include the genre.
o Define a NonFictionBook class that inherits from Book. It adds a subject attribute and
overrides the displayDetails() function to include the subject.
2. Main Function:
o Ask the user for the number of books they want to input.
o Use a vector to store pointers to Book objects, allowing polymorphism to store both
FictionBook and NonFictionBook objects.
3. User Input:
o Loop through the number of books. For each book:
 Prompt the user for the title, author, ISBN, and type of book (either "Fiction" or
"NonFiction").
 Based on the book type, prompt the user for additional details (genre for fiction
books and subject for non-fiction books).
 Create the appropriate book object (FictionBook or NonFictionBook) dynamically
and store the pointer in the vector.
4. Display Book Details:
o Use a loop to call the displayDetails() method of each book pointer stored in the vector,
displaying all the details of the books.
5. Clean-Up:
o After displaying all the books, iterate through the vector and delete each dynamically
allocated book object to free memory
Result:
Thus, the given C++ program was successfully executed and verified.

Ex. No: 18 Return the count of account holders using sequential access file
Date:
Aim:
To write a C++ program to return the count of account holders using sequential access file

Algorithm:
1. Input the filename and minimum balance from the user.
2. Open the file:
o If the file cannot be opened, display an error message and terminate the program.
3. Process the file line by line:
o Read each line.
o Split the line into the account holder's name and balance using a comma delimiter.
o Convert the balance to a numerical value and check if it is less than the minimum balance.
4. Count the number of accounts where the balance is below the threshold.
5. Output the count of such accounts.
6. Close the file after processing.

Result:
Thus, the given C++ program was successfully executed and verified.
[Link]: 19 Exception Handling-Zero Division Exception
Date:
Aim:
To write a C++ program that takes two integer inputs, numerator and denominator, from the user.
Implement error handling to check if the denominator is zero. If the denominator is zero, display the
message "Division by zero is not allowed!" using an exception. If the denominator is not zero, calculate the
result of the division and display it.

Algorithm:
1. Input the Numerator and Denominator:
o Prompt the user to input the numerator and denominator for division.
2. Check for Division by Zero:
o Call the divide() function to attempt the division.
o Inside the divide() function, check if the denominator is zero. If it is, throw an exception with
a message: "Division by zero is not allowed!".
3. Try to Perform the Division:
o Use a try block to catch any potential exceptions thrown during division.
o If no exception occurs, the division result is printed.
4. Catch the Exception:
o If a division by zero occurs, the exception is caught in the catch block, where an appropriate
message is displayed.
5. Continue Program Execution:
o After the exception is handled, the program continues and prints a message stating that the
program continues after exception handling.
Result:
Thus, the given C++ program was successfully executed and verified.
Ex. No: 12 Trailing Zeros in Factorial
Date: 07.11.25
Aim

To write a C++ program to count the number of trailing zeros in the factorial of a given
number.
Algorithm
Step 1: Input the number from the user.
Step 2: Use a class with a private function to calculate trailing zeros.
Step 3: Initialize a count variable.
Step 4: Repeatedly divide the number by 5 and add the quotient to count.
Step 5: Return the count of trailing zeros.
Step 6: Display the result.
Result
Thus, the given C++ program was successfully executed and verified.

Ex. No: 14 Add two numbers using binary operator overloading


Date: 14.11.25
Aim
To write a C++ program to add two numbers using operator overloading.
Algorithm
Step 1: Create a class with a private integer variable.
Step 2: Initialize the variable using constructors.
Step 3: Overload the + operator to add two objects.
Step 4: Create a function to display the result.
Step 5: Input two numbers and create objects.
Step 6: Add objects using the overloaded operator.
Step 7: Display the result.
Result
Thus, the given C++ program was successfully executed and verified.

Ex. No: 15 Volume of Cylinder and Cuboid using function overloading


Date: 21.11.25
Aim
To write a C++ program to calculate the volume of a cylinder and a cuboid using function
overloading.

Algorithm
Step 1: Define a function to calculate the volume of a cylinder.
Step 2: Overload the function to calculate the volume of a cuboid.
Step 3: Input radius and height and calculate cylinder volume.
Step 4: Input length, width, and height and calculate cuboid volume.
Step 5: Display the volumes.
Result
Thus, the given C++ program was successfully executed and verified.

Ex. No: 17 Method Overriding


Date: 28.11.25
Aim
To write a C++ program to calculate the area of a triangle, rectangle, and circle using method
overriding.
Algorithm
Step 1: Define a base class with variables and a virtual function.
Step 2: Create derived classes for triangle, rectangle, and circle.
Step 3: Override the virtual function in each class.
Step 4: Use formulas:
Triangle → (x × y) / 2
Rectangle → x × y
Circle → π × x × x
Step 5: Use base class pointers to refer to derived objects.
Step 6: Input data and display areas.
Result

Thus, the given C++ program was successfully executed and verified.

Ex. No: 21 Areas for Geometric shapes - Hierarchical Inheritance


Date: 02.12.25
Aim
To write a C++ program to calculate the areas of geometric shapes using Hierarchical
inheritance.
Algorithm
Step 1: Create a base class storing width and height.
Step 2: Derive a Rectangle class to compute width × height.
Step 3: Derive a Triangle class to compute (width × height) / 2.
Step 4: Input dimensions for both shapes.
Step 5: Create objects and calculate areas.
Step 6: Display the results.
Result
Thus, the given C++ program was successfully executed and verified.

You might also like