user5770672
user5770672

Reputation:

Output elements from an array in reverse order

Im trying to get the program to output the numbers 1,2,3,4 in reverse order. However, I keep getting strange results and am not sure why. This is what I have so far:

#include <stdio.h>
#define NO_OF_ELEMENTS 4

int main()
{
    int numbers[NO_OF_ELEMENTS];
    int i, j;

    printf("Type a number and hit enter:\n");

    /* Input each number */
    for(i = 0; i < NO_OF_ELEMENTS; i++)
    {
        scanf("%d", &numbers[i]);
    }

    /* Print each number in reverse order */
    for(j = NO_OF_ELEMENTS; j > 0; j--)
    {
        printf("%d\n", &numbers[j]);
    }

    return(0);
}

The output of the program looks as follows:

Program Running

Any help in explaining why the code doesn't work as I expect it to will be greatly appreciated.

FIXED

/* Print each number in reverse order */
for(j = NO_OF_ELEMENTS; j > 0; j--)
{
    printf("%d\n", numbers[j - 1]);

}

enter image description here

Upvotes: 0

Views: 6465

Answers (1)

AlexR
AlexR

Reputation: 98

For printf you doesn't need &, remove it and it would works.

And the second for you need start at NO_OF_ELEMENTS - 1 because of array start at 0 and ends at 3 for 4 items.

enter image description here

Upvotes: 0

Related Questions