#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    Help! Ascending and Descending order


    I'm trying to create a program that will display numbers in ascending and descending order. I just encountering a little problem.. everytime I run the program, the ascending order always display zero even though it's not the numbered entered.
    Thanks in advance


    Code:
    #include<stdio.h> 
    #include<stdlib.h>
    #define SIZE 10 
    int a[10],i,j,k,n; 
    void sort(int *a,int n); 
    void swap(int *x,int *y); 
    int main() 
    {
        system("cls"); 
        printf("Enter the 10 numbers:\n\n"); 
        
        for (i=0;i<SIZE;++i) 
        {
            scanf("%d",&a[i]); 
        }    
        
        sort(a,n); 
        printf("\nDescending order: \n"); 
        
        for (k=0;k<SIZE;k++) 
        {
            printf("\n%d",a[k]);
        }
     
        printf("\nAscending order:");
        
        for (k=10;k>0;k--) 
        {
            printf("\n%d",a[k]); 
        }
        
        system("pause");
        return 0;
    }
     
    void sort(int *a,int n) 
    {
        int p=SIZE-1; 
        while (p>=0) 
        { 
            for(i=0;i<=(p-1);++i) 
            { 
                if (a[i]<=a[i+1]) 
                swap(&a[i],&a[i+1]); 
                else 
                continue; 
            } 
        --p;
        } 
    } 
    void swap(int *x,int *y) 
    { 
        int t; 
        t=*x; 
        *x=*y; 
        *y=t; 
    }

    Comments on this post

    • salem agrees : good job on using code tags on the first post
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    > for (k=10;k>0;k--)
    You're off by one, at both ends.

    You start at SIZE-1, and end at zero.

    Code:
    for ( i = 0 ; i < SIZE ; i++ ) printf("%d\n", i );
    for ( i = SIZE ; i > 0 ; i-- ) printf("%d\n", i );
    Fix the second loop so you get the same indices, but in reverse.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0
    Originally Posted by salem
    > for (k=10;k>0;k--)
    You're off by one, at both ends.

    You start at SIZE-1, and end at zero.

    Code:
    for ( i = 0 ; i < SIZE ; i++ ) printf("%d\n", i );
    for ( i = SIZE ; i > 0 ; i-- ) printf("%d\n", i );
    Fix the second loop so you get the same indices, but in reverse.
    Thanks man!!!

IMN logo majestic logo threadwatch logo seochat tools logo