Thread: sorting number

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    1

    sorting number

    write a program in c to sort numbers in both descending and ascending order using array and pointers

  2. #2
    Complete Beginner
    Join Date
    Feb 2009
    Posts
    312
    Done.

    Greets,
    Philip
    All things begin as source code.
    Source code begins with an empty file.
    -- Tao Te Chip

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Snaf, I would give that post green candy if we still had it.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I did that about 10 years ago, does that count?

    Seriously, either go find another forum to annoy with your request for homework, or show us what you've tried - in other words: Show us that you are trying, and we will guide you.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    4
    Courtesy of the Dev C\C++ help files.


    Arrays


    Objectives:

    Having read this section you should have a good understanding of the use of arrays in C.


    Advanced Data Types:

    Programming in any language takes a quite significant leap forwards as soon as you learn about more advanced data types - arrays and strings of characters. In C there is also a third
    more general and even more powerful advanced data type - the pointer but more about that later. In this section we introduce the array, but the first question is, why bother?

    There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is
    a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:
    Code:
    main()
    {
     int al,a2,a3,a4,a5;
     scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
     printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
    }
    Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular
    variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the
    basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.

    In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. For example,

    Code:
    int a[5];
    declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. C programmer's always start counting at zero! Languages vary
    according to where they start numbering arrays. Less technical, i.e. simpler, languages start counting from 1 and more technical ones usually start counting from 0. Anyway, in the case of C

    you have to remember that

    type array[size]

    declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].

    Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple:


    Code:
     main()
      {
       int a[5];
       int i;
       for(i =0;i < 5; ++i) scanf("%d",&a[i]);
       for(i =4;i> =0;--i) printf("%d",a[i]);
      }
    Well we said simple but I have to admit that the pair of for loops looks a bit intimidating. The for loop and the array data type were more or less made for each other. The for loop can be

    used to generate a sequence of values to pick out and process each element in an array in turn. Once you start using arrays, for loops like:
    Code:
    for (i=0 ; i<5 ; ++i)
    to generate values in the order 0,1,2 and so forth, and
    Code:
    for(i=4;i>=0;--i)
    to generate values in the order 4,3,2... become very familiar.


    In Dis-array:

    An array of character variables is in no way different from an array of numeric variables, but programmers often like to think about them in a different way. For example, if you want to read

    in and reverse five characters you could use:
    Code:
     main()
      {
       char a[5];
       int i;
       for(i=0; i<5; ++i) scanf("%c",&a[i]);
       for(i=4;i>=0;--i) printf("%c",a[i]);
      }
    Notice that the only difference, is the declared type of the array and the %c used to specify that the data is to be interpreted as a character in scanf and printf. The trouble with character
    arrays is that to use them as if they were text strings you have to remember how many characters they hold. In other words, if you declare a character array 40 elements long and store H E L

    L O in it you need to remember that after element 4 the array is empty. This is such a nuisance that C uses the simple convention that the end of a string of characters is marked by a null
    character. A null character is, as you might expect, the character with ASCII code 0. If you want to store the null character in a character variable you can use the notation \0 - but most
    of the time you don't have to actually use the null character. The reason is that C will automatically add a null character and store each character in a separate element when you use a

    string constant. A string constant is indicated by double quotes as opposed to a character constant which is indicated by a single quote. For example:

    Code:
    "A"
    is a string constant, but

    Code:
    'A'
    is a character constant. The difference between these two superficially similar types of text is confusing at first and the source of many errors. All you have to remember is that &QUOTA"
    consists of two characters, the letter A followed by \0 whereas 'A' is just the single character A. If you are familiar with other languages you might think that you could assign string constants

    to character arrays and work as if a string was a built-in data type. In C however the fundamental data type is the array and strings are very much grafted on. For example, if you try
    something like:

    Code:
    char name[40];
    name="Hello"
    it will not work. However, you can print strings using printf and read them into character arrays using scanf. For example,

    Code:
     main()
      {
    
        static char name[40] ="hello";
    
        printf("%s",name);
        scanf("%s",name);
        printf("%s",name);
    
       }
    This program reads in the text that you type, terminating it with a null and stores it in the character array name. It then prints the character array treating it as a string, i.e. stopping when it hits
    the first null string. Notice the use of the "%s" format descriptor in scanf and printf to specify that what is being printed is a string.

    At this point the way that strings work and how they can be made a bit more useful and natural depends on understanding pointers which is covered in the next section.

  6. #6
    Registered User
    Join Date
    May 2009
    Posts
    4
    Pointers


    Objectives:

    Having read this section you should be able to:

    1.program using pointers
    2.understand how C uses pointers with arrays


    Point to Point:

    Pointers are a very powerful, but primitive facility contained in the C language. Pointers are a throwback to the days of low-level assembly language programming and as a result they are
    sometimes difficult to understand and subject to subtle and difficult-to-find errors. Still it has to be admitted that pointers are one of the great attractions of the C language and there will be

    many an experienced C programmer splutering and fuming at the idea that we would dare to refer to pointers as 'primitive'!

    In an ideal world we would avoid telling you about pointers until the very last minute, but without them many of the simpler aspects of C just don't make any sense at all. So, with apologies,
    let's get on with pointers.

    A variable is an area of memory that has been given a name. For example:
    Code:
    int x;
    is an area of memory that has been given the name x. The advantage of this scheme is that you can use the name to specify where to store data. For example:
    Code:
    x=lO;
    is an instruction to store the data value 10 in the area of memory named x. The variable is such a fundamental idea that using it quickly becomes second nature, but there is another way of
    working with memory.

    The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that
    memory location.

    A pointer is a variable that stores this location of memory. In more fundamental terms, a pointer stores the address of a variable . In more picturesque terms, a pointer points to a variable.

    A pointer has to be declared just like any other variable - remember a pointer is just a variable that stores an address. For example,
    Code:
    int *p;
    is a pointer to an integer. Adding an asterisk in front of a variable's name declares it to be a pointer to the declared type. Notice that the asterisk applies only to the single variable name that it
    is in front of, so:
    Code:
    int *p , q;
    declares a pointer to an int and an int variable, not two pointers.

    Once you have declared a pointer variable you can begin using it like any other variable, but in practice you also need to know the meaning of two new operators: & and *. The & operator

    returns the address of a variable. You can remember this easily because & is the 'A'mpersand character and it gets you the 'A'ddress. For example:
    Code:
    int *p , q;
    declares p, a pointer to int, and q an int and the instruction:
    Code:
    p=&q;
    stores the address of q in p. After this instruction you can think of p as pointing at q. Compare this to:
    Code:
    p=q;
    which attempts to store the value in q in the pointer p - something which has to be considered an error.

    The second operator * is a little more difficult to understand. If you place * in front of a pointer variable then the result is the value stored in the variable pointed at. That is, p stores the

    address, or pointer, to another variable and *p is the value stored in the variable that p points at.

    The * operator is called the dereferencing operator and it helps not to confuse it with multiplication or with its use in declaring a pointer.

    This multiple use of an operator is called operator overload.

    Confused? Well most C programmers are confused when they first meet pointers. There seems to be just too much to take in on first acquaintance. However there are only three basic ideas:

    1.To declare a pointer add an * in front of its name.
    2.To obtain the address of a variable us & in front of its name.
    3.To obtain the value of a variable use * in front of a pointer's name.

    Now see if you can work out what the following means:

    Code:
    int *a , b , c;
    b = 10;
    a = &b;
    c = *a;
    Firstly three variables are declared - a (a pointer to int), and b and c (both standard integers). The instruction stores the value l0 in the varable b in the usual way. The first 'difficult'

    instruction is a=&b which stores the address of b in a. After this a points to b.

    Finally c = *a stores the value in the varable pointed to by a in c. As a points to b, its value i.e. 1O is stored in c. In other words, this is a long winded way of writing
    Code:
    c = b;
    Notice that if a is an int and p is a pointer to an int then
    Code:
    a = p;
    is nonsense because it tries to store the address of an int, i.e. a pointer value, in an int. Similarly:
    Code:
    a = &p;
    tries to store the address of a pointer variable in a and is equally wrong! The only assignment between an int and a pointer to int that makes sense is:
    Code:
    a = *p;
    Swap Shop:

    At the moment it looks as if pointers are just a complicated way of doing something we can already do by a simpler method. However, consider the following simple problem - write a
    function which swaps the contents of two variables. That is, write swap(a,b) which will swaps over the contents of a and b. In principle this should be easy:
    Code:
    function swap(int a , int b);
     {
      int temp;
      temp = a;
      a    = b;
      b    = temp;
     }
    the only complication being the need to use a third variable temp to hold the value of a while the value of b overwrites it. However, if you try this function you will find that it doesn't work.

    You can use it - swap(a,b); - until you are blue in the face, but it just will not change the values stored in a and b back in the calling program. The reason is that all parameters in C are
    passed by value. That is, when you use swap(a,b) function the values in a and b are passed into the function swap via the parameters and any changes that are made to the parameters do
    not alter a and b back in the main program. The function swap does swap over the values in a and b within the function, but doesn't do so in the main program.

    The solution to this very common problem is to pass not the values stored in the variables, but the addresses of the variables. The function can then use pointers to get at the values in the
    variables in the main program and modify them. That is, the function should be:

    Code:
     function swap(int *a , int *b);
     {
      int temp;
      temp = *a;
      *a   = *b;
      *b   = temp;
     }
    Notice that now the two parameters a and b are pointers and the assignments that effect the swap have to use the dereference operator to make sure that it is the values of the variables

    pointed at that are swapped. You should have no difficulty with:
    Code:
    temp = *a;
    this just stores the value pointed at by a into temp. However,
    Code:
    *a = *b;
    is a little more unusual in that it stores that value pointed at by b in place of the value pointed at by a. There is one final complication. When you use swap you have to remember to pass the
    addresses of the variables that you want to swap. That is not:
    Code:
    swap(a,b)
    but
    Code:
    swap(&a,&b)
    The rule is that whenever you want to pass a variable so that the function can modify its contents you have to pass it as an address. Equally the function has to be ready to accept an address

    and work with it. You can't take any old function and suddenly decide to pass it the address of a variable instead of its value. If you pass an address to a function that isn't expecting it the
    result is usually disaster and the same is true if you fail to pass an address to a function that is expecting one.

    For example, calling swap as swap(a,b) instead of swap(&a,&b) will result in two arbitrary areas of memory being swapped over, usually with the result that the entire system, not just

    your program, crashes.

    The need to pass an address to a function also explains the difference between the two I/O functions that we have been using since the beginning of this course. printf doesn't change the
    values of its parameters so it is called as printf("%d",a) but scanf does, because it is an input function, and so it is called as scanf("%d",&a).


    Pointers And Arrays:

    In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as:

    int a[10];

    you are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a
    constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate
    element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the same way *(a+ 1) is the same as a[1] and so on.

    Being able to add one to a pointer to get the next element of an array is a nice idea, but it does raise the question of what it means to add 'one' to a pointer. For example, in most
    implementations an int takes two memory locations and a float takes four. So if you declare an int array and add one to a pointer to it, then in fact the pointer will move on by two
    memory locations. However, if you declare a float array and add one to a pointer to it then the pointer has to move on by four memory locations. In other words, adding one to a pointer

    moves it on by an amount of storage depending on the type it is a pointer to.

    This is, of course, precisely why you have to declare the type that the pointer is to point at! Only by knowing that a is a pointer to int and b is a pointer to float can the compiler figure out
    that

    a + 1

    means move the pointer on by two memory locations i.e. add 2, and

    b + 1

    means move the pointer on by four memory locations i.e. add 4. In practice you don't have to worry about how much storage a pointer's base type takes up. All you do need to remember is

    that pointer arithmetic works in units of the data type that the pointer points at. Notice that you can even use ++ and -- with a pointer, but not with an array name because this is a constant
    pointer and cannot be changed. So to summarise:

    1.An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0].
    2.Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i].

    It is up to you whether you want to think about an array as an array or an area of storage associated with a constant pointer. The view of it as an array is the more sophisticated and the

    further away from the underlying way that the machine works. The view as a pointer and pointer arithmetic is more primitive and closer to the hardware. In most cases the distinction is
    irrelevant and purely a matter of taste.

    One final point connected with both arrays and functions is that when you pass an entire array to a function then by default you pass a pointer. This allows you to write functions that
    process entire arrays without having to pass every single value stored in the array - just a pointer to the first element. However, it also temps you to write some very strange code unless you

    keep a clear head. Try the following - write a function that will fill an array with random values randdat(a,n) where a is the array and n is its size. Your first attempt might be something
    like:

    Code:
     void randdat(int *pa , int n)
      {
       for (pa = 0 ; pa < n ; pa++ ) *pa = rand()%n + 1;
      }
    Well I hope your first attempt wouldn't be like this because it is wrong on a number of counts! The problem is that the idea of a pointer and the idea of an index have been confused. The

    pointer pa is supposed to point to the first element of the array, but the for loop sets it to zero and then increments it though a series of memory locations nowhere near the array. A lesser
    error is to suppose that n-1 is the correct final value of the array pointer! As before, you will be lucky if this program doesn't crash the system, let alone itself! The correct way of doing the
    job is to use a for loop to step from 0 to n-1, but to use pointer arithmetic to access the correct array element:
    Code:
    int randdat(int *pa , int n)
    {
      int i;
      for ( i=0 ; i< n ; ++i)
       {
         *pa = rand()%n + 1;
         ++pa;
       }
    }
    Notice the way that the for loop looks just like the standard way of stepping through an array. If you want to make it look even more like indexing an array using a for loop you could
    write:
    Code:
    for(i=0 ; i<n ; ++i) *(pa+i)=rand()%n+1;
    or even:
    Code:
    for(i=0 ; i<n ; ++i) pa[i]=rand()%n+1;
    In otherwords, as long as you define pa as a pointer you can use array indexing notation with it and it looks as if you have actually passed an array. You can even declare a pointer variable

    using the notation:
    Code:
    int pa[];
    that is, as an array with no size information. In this way the illusion of passing an array to a function is complete.


    All you need was in the help files. GL and happy reading.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    tiaratt, please stop posting tutorials in this thread. Help given should be tailored to the question asker's problem. In this case, the question asker needs to show an attempt first, upon which we can focus on what needs to be fixed or improved.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    May 2009
    Posts
    4
    Quote Originally Posted by laserlight View Post
    tiaratt, please stop posting tutorials in this thread. Help given should be tailored to the question asker's problem. In this case, the question asker needs to show an attempt first, upon which we can focus on what needs to be fixed or improved.
    I think those two post cover everything the OP asked for. Not much needed to be done with the swap function in the tutorial to make it sort in acending or decending order. If the OP can't read that and understand what to do, then the OP should take a reading comprehesion class also.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The point Laserlight was making was that they didn't just think their homework problem up out of the blue. It was given to them for some reason. Generally, that means they've already covered what they need to know to do the homework.

    You don't generally just get an assignment with no basis or background behind it. As such, there's no real need for us to explain to them how to do everything. Especially when they're not making any effort of their own. You don't need to give them a tutorial, because the chances are they've already covered the subject--they're just being lazy.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program that requests input of an integer number
    By theejuice in forum C Programming
    Replies: 6
    Last Post: 04-30-2008, 02:18 AM
  2. Need help getting program print out the digit in words
    By cosmiccomputing in forum C Programming
    Replies: 26
    Last Post: 04-24-2008, 08:28 AM
  3. Need help with this compiler error
    By Evangeline in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 09:27 AM
  4. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  5. help with a source code..
    By venom424 in forum C++ Programming
    Replies: 8
    Last Post: 05-21-2004, 12:42 PM