81.3k views
1 vote
C++ Programming.

Task :

This program takes (n) number of elements from the user and stores it in the (arr) array. Find the 3 largest elements in that array. (use pointers)


Plase help me...

1 Answer

5 votes

Answer: in C++

#include <iostream>

using namespace std;

const int NUM_ELEMENTS = 3; // number of elements to find

int main() {

int n;

cout << "Enter the number of elements: ";

cin >> n;

int* arr = new int[n]; // dynamically allocate an array of size n

cout << "Enter the elements: ";

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

cin >> arr[i];

}

// find the 3 largest elements

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

int max = arr[i]; // current max

int maxIndex = i; // current max index

for (int j = i + 1; j < n; j++) {

if (arr[j] > max) {

max = arr[j];

maxIndex = j;

}

}

// swap arr[i] and arr[maxIndex]

int temp = arr[i];

arr[i] = arr[maxIndex];

arr[maxIndex] = temp;

}

// print the 3 largest elements

cout << "The 3 largest elements are: ";

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

cout << arr[i] << " ";

}

cout << endl;

delete[] arr; // deallocate the array

return 0;

}

User Lood Van Niekerk
by
7.5k points