Program help :D

I challenged myself with a program... Basically user has to input five numbers, and computer has to order those five numbers from larger one to smaller one.. I began with this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;

int main(){
 
int x = 1;    
int num[4];

cout << "Write five numbers." << endl;

while (x <= 5){
      cin >> num[4];
      x++;     
          }            
           
system("Pause")
return 0;
} 


I tried with if's but it doesn't work, anyway the main reason I challenged myself with this is because I have a hard time learning loops, and I realized if I make this program I would pretty much have the basic idea...

So I am asking you guys to help me make my program. You don't need to write me the code if you don't want, just tell me what I am supposed to do..

Thanks :D
Last edited on
You are reading all the values into num[4]. This isn't even a valid array element because num contain 4 element so the first is num[0] and the last is num[3]. You should make the array one bigger. Start x at 0 instead of 1. Change x <= 5 and num[4] to something else :P
I suggest the use of the "for" loop where you decided to use the cin.

*spoiler alert* if you really didn't want to see the solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

int main() {
    int num[5]; //array of 5 elements
    bool sorted = false;  //create exit condition for our while loop

    cout << "Write five numbers." << endl;

    for (int i = 0; i< 5; i++)
    {
        cin >> num[i];   //Read in 5 numbers into array num[]
    }

    while (! sorted) //continue if not sorted
    {
        sorted = true; // set exit condition
        for (int i = 0; i < 4; i++) // go through all elements of num
        {
            if (num[i] < num[i+1])  // compare elements of num
            {
                int temp = num[i];  // if swapping is required do these three lines
                num[i] = num[i+1];
                num[i+1] = temp;
                sorted = false; // sorting was required, lets do the while loop again.
            }
        }
    } 

    for (int i = 0 ; i < 5 ; i++)
   {
        cout << num[i] << ", ";
    }

    system("Pause")
    return 0;
}
Last edited on
I think that everything I did is fine... I am asking for the next part.. But thanks for your comment :D

EDIT: Thanks Stewbond :D I understand everything here, so I can see that I will still have a hard time with loops, because what you did was really complicated (for me). But still I understood every single thing. :D

oh btw. you forgot the semi-colon on

system("Pause")

but thanks again :D
Last edited on
Topic archived. No new replies allowed.