How can i sort this array pls..

#include<iostream>
#include<algorithm>
using namespace std;
int prompt(int x[]);
void printreverse(int x[]);


int main()
{
	int x[5];
	prompt(x);
	printreverse(x);
	
	system("pause");
	return 0;
}

int prompt(int x[])
{
	
	for(int i=0;i<5;i++)
	{
		cout <<"Enter integers:";
		cin >>x[i];
	}
}



void printreverse(int x[])
{
	for(int i=0;i<5;i++)
	{
		cout <<x[i]<<" ";
	}
	cout <<endl;
}

Dani AI

Generated

was right to point you at the standard algorithms, and 's short example shows the idea. The original program has a few problems worth fixing: prompt is declared int but never returns, printreverse doesn't print in reverse, the input prompt repeats inside the loop, and system("pause") is Windows-specific. Use a standard container (or pass the array size) and modern C++ idioms for safety and clarity.

A concise, idiomatic solution using std::array and range-based loops:

#include <iostream>
#include <array>
#include <algorithm>

int main() {
    std::array<int, 5> a;
    std::cout << "Enter 5 integers: ";
    for (int &v : a) {
        if (!(std::cin >> v)) return 1; // simple input check
    }

    std::sort(a.begin(), a.end());

    std::cout << "Ascending: ";
    for (int v : a) std::cout << v << ' ';
    std::cout << '\n';

    std::cout << "Descending: ";
    for (auto it = a.rbegin(); it != a.rend(); ++it) std::cout << *it << ' ';
    std::cout << '\n';
}

Notes and pitfalls: when you pass a C-style array to a function it decays to a pointer, so you must also pass its size (or use std::array/std::vector to avoid that). If you want descending order in-place, pass a comparator like std::greater<>() to std::sort. Prefer std::stable_sort only if you need to preserve the relative order of equal elements. Avoid using namespace std; in global scope and avoid system("pause") for portable code. See the standard documentation for details on complexity and overloads: std::sort reference.

Recommended Answers

All 3 Replies

The most direct way, since you've already included the algorithm header, is to use std::sort().

what type of sorting pls?

Use the suggestion above, although you might want to google sorting for knowledge experience.

You can do this if you want to use std::sort;

#
int main()
{
int x[5];
prompt(x);
printreverse(x);
std::sort(x,x+5);
system("pause");
return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.