0

I wrote a simple C program which reads space separated integers from stdin.

#include<stdio.h>
int main(){
    int k, n, a[5], i = -1;
    printf("Enter K and N: \n");
    scanf("%d %d", &k, &n);
    printf("Enter the values: \n");
    scanf("%d %d %d %d %d", &a[++i], &a[++i], &a[++i], &a[++i], &a[++i]);
    for (int i = 0; i < 5; ++i)
    {
        printf("%d ", a[i]);
    }
    return 0;
}

If you enter 1, 2, 3, 4, 5, the output given is 5, 4, 3, 2, 1. If you don't use i while taking the input and use the values 0, 1, 2, 3, 4 instead, the inputs are taken in normal way. I want to understand why is the program behaving so.

Screenshot of output:

enter image description here

Akash Agarwal
  • 2,326
  • 1
  • 27
  • 57
  • I did not understand why did you take K and N from the user. by the way your code works fine and prints normally. – ReshaD Jun 07 '16 at 13:31
  • @reshad please ignore that, the program is incomplete. I'm using g++ compiler on Xubuntu 16.04 and it prints the output in reverse order for me. – Akash Agarwal Jun 07 '16 at 13:32
  • for me if prints out in the correct order, but if you say so, try this for (i=4; i>=0; i--) { printf("%d ", a[i]); } – ReshaD Jun 07 '16 at 13:34
  • @reshad added screenshot, I know your approach should work but that isn't the problem. I'm seeking an explanation. – Akash Agarwal Jun 07 '16 at 13:41

0 Answers0