Click here to Skip to main content
16,016,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>
#include <conio.h>
#define arr_size 5
void main(void)
{
    float numbers[arr_size] ;
    int counter;
    printf("Input five numbers: \n");
    for (counter = 0; counter < arr_size; ++counter)
        {
            printf("%i?",counter + 1);
            scanf("%f", &numbers[counter]);
        }
    printf("Here they are:");
    for (counter = 4; counter >= 0; --counter)
    printf(" %g",numbers[counter]);
}

I want to change the output from descending to ascending order. For example, the output will showing 54321, but I want the output showing start from 12345, may I know is it change the counter to 0?
Posted
Updated 16-Apr-11 20:33pm
v2
Comments
CPallini 17-Apr-11 3:11am    
What do you mean exactly? Do you want to sort the array?

1 solution

Firstly, don't use Magic Numbers. You used "arr_size" in your first loop, use it in your second as well. Otherwise you run the risk of changing the size in one place, and your code fails because you didn't change t in the other.
for (counter = arr_size - 1; counter >= 0; --counter)
   printf(" %g",numbers[counter]);
To reverse the order of printing, you could do this two ways:
for (counter = arr_size; counter > 0; --counter)
   printf(" %g",numbers[arr_size - counter]);
Or
for (counter = 0; counter < arr_size; ++counter)
   printf(" %g",numbers[counter]);
BTW: It is a convention to use postfix notation in for loops - not mandatory, but normal:
Instead of
for (counter = arr_size - 1; counter >= 0; --counter)
   printf(" %g",numbers[counter]);
Use
for (counter = arr_size - 1; counter >= 0; counter--)
   printf(" %g",numbers[counter]);


[edit]Typo: Forgot to remove old condition from for loop when adding new condition - it's early! - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Jayfam 17-Apr-11 3:01am    
thanks a lot, im finally understand about it
Sergey Alexandrovich Kryukov 17-Apr-11 14:21pm    
Correct, especially a note against Magic Numbers. Generally, those are immediate constants which should be avoided my any means. Explicit constants should be used if not resources or input data, such as configuration types.

I noticed Jayfam tends to understand the Answers; this is good.

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900