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 :
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
usingnamespace 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..
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
#include <iostream>
usingnamespace 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;
}
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