Write a C++ program using the concept of OOP to find the second smallest element in an array
Algorithm:
- Create a class called "Array"
- Define variables for size and a pointer to an array to store the elements
- Create a constructor to initialize the size and allocate memory for the array
- Create a method called "input" to take input from the user and store it in the array
- Create a method called "sort" to sort the array in ascending order
- Create a method called "secondSmallest" to find the second smallest element in the array
- Create an object of the Array class and use the methods to find the second smallest element
C++ Program:
#include <iostream>
using namespace std;
class Array {
int size;
int *arr;
public:
Array(int s) {
size = s;
arr = new int[size];
}
void input() {
cout << "Enter elements of array: " << endl;
for(int i = 0; i < size; i++)
cin >> arr[i];
}
void sort() {
for(int i = 0; i < size; i++) {
for(int j = i+1; j < size; j++) {
if(arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void secondSmallest() {
cout << "The second smallest element is: " << arr[1] << endl;
}
~Array() {
delete[] arr;
}
};
int main() {
int s;
cout << "Enter the size of the array: ";
cin >> s;
Array a(s);
a.input();
a.sort();
a.secondSmallest();
return 0;
}
/*
======Input/Output=====
Enter the size of the array: 5
Enter elements of array:
10 20 30 40 50
The second smallest element is: 20
*/
Explanation:
- The user enters 5 for the size of the array, indicating that the array has 5 elements.
- The user then enters the elements of the array: 10 20 30 40 50
- The program creates an Array object, sorts the array in ascending order, and finds the second smallest element which is 20 and prints the result.
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment