mgbelegu
mgbelegu

Reputation: 1

How to print an array in descending order?

Basically this is my code and it works fine. I just don't know how to print it in descending order. This code basically shows the odd numbers:1,3,5,7. I want it to be printed 7,5,3,1. I know I need use the sort function but I dont know how.

#include <iostream>

using namespace std;

void fillArray(int arr[], int &n);
void printArray(int arr[], int n);
void findSum(int arr[], int &n);

int main()
{
    int n;
    cin>>n;
    int arr[n];
    fillArray(arr,n);
    printArray(arr,n);
    findSum(arr,n);

    return 0;
}

void fillArray(int arr[], int &n)
{
    int j=1;
    for(int i=0;i<n;i++)
    {
        if(j%2==1)
            arr[i]=j;
        else
            i--;
        j++;
    }
}

void printArray(int arr[], int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<", ";
    }
}

void findSum(int arr[], int &n)
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        sum=sum+arr[i];
    }
}

Upvotes: 0

Views: 3751

Answers (3)

Chad K
Chad K

Reputation: 952

You can simply use a sort function. There is one included with the algorithm header.

#include <algorithm> // this goes at the top

void printArray(int arr[], int n)
{
  sort(arr, arr+n, [](int x, int y){return y<x;});

  for(int i=0;i<n;i++)
    cout << arr[i] << endl;
}

the [](int x, int y){return y<x;} part is just to make it descending. Normally it is y>x, at which point you can just omit the third parameter

Here is a repl: https://repl.it/JQor/0

Upvotes: -1

21koizyd
21koizyd

Reputation: 2003

example:

void printArray(int *tab, int size)
{
    for (int i = size - 1; i >= 0; i--)
        std::cout << tab[i] << std::endl;
}
int main() {
    int tab[3] = { 1,2,3 };
    printArray(tab, 3);

}

You should begin from last element array, and decrement iterator (i) to i == 0

Upvotes: 1

Fabien
Fabien

Reputation: 4972

for(int i = n-1; i >= 0; i--)
{
    cout << arr[i] << ", ";
}

Upvotes: 1

Related Questions