Increasing and decreasing orders

Hello! Today I am going to show you how to read n numbers from the keyboard and rearrange them in an increasing or decreasing order.I hope this  helps you! Enjoy!

So,in order to do that you will need to work with arrays of numbers. Example code:

#include <iostream>

using namespace std;
int n,V[101],ok,i,aux;
int main()
{

    cin>>n;
    for (i=1;i<=n;i++)
        cin>>V[i];
    do
    {
        ok=0;
        for(i=1;i<=n-1;i++)
       {
           if (V[i]>V[i+1])
        {
            aux= V[i];
            V[i]= V[i+1];
            V[i+1]= aux;
            ok = 1;
        }
       }
    }

    while (ok==1);
    for(i=1;i<=n;i++)
    cout<<V[i]<<" ";

    return 0;
}
/*this code rearranges the numbers in an increasing order, if you want to
rearrange them in a decreasing order you have to change the if condition from
V[i]>V[i+1] to V[i]<V[i+1] */

 

Feel free to try the code yourselves, soon I will talk about reading the values from a file in case you have some values that are already generated.

Keep on coding 😉 !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s