Home > front end >  How to print values in descending order for every number entered?
How to print values in descending order for every number entered?

Time:03-05

I need to create a program that asks the user for N unique values and print the values in descending order for every number entered. The problem is it only outputs the number 0. Can anyone point out what is wrong with my code?

#include <iostream>

using namespace std;

int main(){
    //declare the variables
    int N, j, i, k, z, desc, temp, sorter[N];
    bool found;
    //Ask the user for N size array
    cout << "Enter array size: ";
    cin >> N;
    while(N<5){
        cout << "Invalid value. N must be greater than five(5)" << endl;
        cout << "Enter array size: ";
        cin >> N;
    }
    int list[N];
    //Printing how many values they need to enter
    cout << " " << endl;
    cout << "Please enter " << N << " values" << endl;
    //Code of the program
    for (int i = 0; i < N; i  ){
        do{
            found = false;
            cout << "\n" << endl;
            cout << "Enter value for index " << i << ": ";
            cin >> temp;
            for (int j = 0; j < i; j  )
                if (list[j] == temp)
                    found = true;
            if (found == true)
                cout << "Value already exist";
            else{
                for(int k = 0; k < i; k  ){
                    int key = sorter[k];
                    j = k - 1;
                    while(j >= 0 && key >= sorter[j]){
                        sorter[j   1] = sorter[j];
                        j--;
                    }
                    sorter[j   1] = key;
                }
                cout << "\nValues: ";
                for(int z = 0; z <= i; z  ){
                    cout << sorter[z] <<" ";
                }
            }
        } while(found == true);
        sorter[i] = temp;   
    }

CodePudding user response:

You shouldn't be defining the array 'sorter[N]', the position, where you are currently, because you don't have the value of 'N', during compilation the arbitrary amount of space will be allocated to the the array.

solve the other compiling errors in your code.

CodePudding user response:

What you want is just a 3-line code:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> vecOfNumbers  = { 1,3,5,7,9,8,6,4,2 }; // scan these numbers if you want
    std::sort(vecOfNumbers.begin(), vecOfNumbers.end());
    std::copy(vecOfNumbers.rbegin(), vecOfNumbers.rend(), std::ostream_iterator<int>(std::cout, " "));
    return 0;
}

Make sure you understand it before using it

  • Related