Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

C++ entering numbers and displaying

So I got this code, I input three numbers. Now I want to display them in a for loop. From smallest to biggest, and in another loop from biggest to smallest. How can I do this?

Code
int main() {

int num1, num2, num3;
cout << "Enter first num" << endl;
cin >> num1;

cout << "Enter second num" << endl;
cin >> num2;

cout << "Enter third num" << endl;
cin >> num3;

I have done this like this but I think it's not a proper way to do it?

Code
for(int i=0; i<=0; i++) {
  cout << num1 << num2 << num3;

}

for(int i=0; i<=0; i++) {
  cout << num3 << num2 << num1;

}
Well you'll have to decide how you want to sort these integers. You can use a old fashion array or a C++ container or even recursion.

Its really up to you.

The easiest is qsort and arrays.

https://www.tutorialspoint.com/c_standar..._qsort.htm

A not so easy way is to create an array of integer pointers to the integers and sort the pointers(smallest to largest or largest to smallest).

Here's a solution which uses an array of pointers to the integers...

Code
#include <iostream>
#include <cstdlib>

int cmpfunc (const void * a, const void * b) {
  return ( **(int**)a - **(int**)b);
}

int main () {
  int a, b, c, d, e;

  int *arr[5] = {&a, &b, &c, &d, &e};
 
  std::cout << "Enter five numbers" << std::endl;
  std::cin >> a >> b >> c >> d >> e;

  std::cout << "Before sorting the list is:" << std::endl;
  for(int n = 0 ; n < 5; n++ ) {
    std::cout << *arr[n] << " ";
  }

  qsort(arr, 5, sizeof(int*), cmpfunc);

  std::cout << "\nAfter sorting the list is" << std::endl;
  for(int n = 0 ; n < 5; n++ ) { 
    std::cout << *arr[n] << " ";
  }

  std::cout << "\n" << std::endl;

  return(0);
}

How about one that uses a C++ set?

Code
#include <iostream>
#include <set>

int main() {
  int a, b, c, d, e;
  std::set<int> intSet;
  std::set<int>::iterator it;
  std::set<int>::reverse_iterator rit;
  
  std::cout << "Enter five integers: ";
  std::cin >> a >> b >> c >> d >> e;
  
  intSet.insert(a);
  intSet.insert(b);
  intSet.insert(c);
  intSet.insert(d);
  intSet.insert(e);
  
  for (it=intSet.begin(); it!=intSet.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  for (rit=intSet.rbegin(); rit!=intSet.rend(); ++rit)
    std::cout << ' ' << *rit;
  std::cout << '\n';

  
  return 0;
}
May you be given directions by software engineer document writers.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by Ferrari F40Dec 7, 2019 12:07 PM 1 254 Dec 7, 2019 12:07 PM
Last Post: itcorp
[C#] by Iera NamhorunJun 26, 2019 04:28 AM 4 235 Jun 26, 2019 04:28 AM
Last Post: Iera Namhorun
[Java] by cryptobassboostFeb 7, 2019 05:28 PM 4 218 Feb 7, 2019 05:28 PM
Last Post: Caliban