Aim_algorithms-C++ Lab
Aim_algorithms-C++ Lab
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.
While extracting the last digit of num add it to the sum (sum += num % 10)
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 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.
Result:
Thus, the given C++ program was successfully executed and verified.
Ex. No: 4 Maximum of An Array of Numbers
Date:
Aim
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 5: compare the second array element with the current maximum value.
Step 7: Repeat the process till all array elements are compared. Ensure maximum is updated accordingly.
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.
Ex.No: 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.
Result:
Thus, the given C++ program was successfully executed and verified.
Ex.No: 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
If they are not equal, set is Palindrome to false and break the loop.
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
o Declare a map of type <char, int> to store characters as keys and their frequencies as values.
o For each element in the map, print the character (key) and its frequency (value).
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.
Ex.No: 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.
Ex.No: 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
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.
Call the maxArray function to find the maximum element in the array.
Call the minArray function to find the minimum element in the array.
Date:
Aim
To write a C++ program to create a Class Calculator using Constructor and Destructor.
Algorithm
Result:
Thus, the given C++ program was successfully executed and verified.
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.
Ex.No: 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.
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.
Ex.No:16 Implementation of media content using inheritance.
Date:
Aim
Algorithm
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.
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.