-1

The following program gets the input and reverses it but it seems to skip the last element of the array while doing so

/*C program that declares an array A and inputs n integer values in A.
Then the contents of array A is copied to another array B in reversed order. 
Finally print the elements of array B*/

#include<stdio.h>
int main()
{
  int n, reverse, i ;
  int A[100], B[100] ;
  printf("Input the size of array A: ") ;
  scanf("%d", &n ) ;
  printf("Input the values of  A: ") ;
  for( i = 0 ; i<n ; i++ )
      scanf("%d ", &A[i] ) ;
  for(i = n-1 , reverse = 0 ; i>= 0 ; i--, reverse++)
      B[reverse] = A[i] ;
  for(i = 0 ; i<n ; i++ )
      A[i] = B[i];
  printf("Array B: ") ;
  for(i=0 ; i<n ; i++ )
      printf("%d ", A[i] ) ;
  return 0 ;
}

Here is an online repel of the code demonstrating the problem

user93
  • 1,866
  • 5
  • 26
  • 45
  • 2
    What is your input? Have you considered using a debugger to trace through the code and find the issue? 3, 1, 2, 3 seems to work fine other than saying you're going to print B when you print A. – Retired Ninja Jul 01 '17 at 03:51
  • "If i run this code then it takes all the input but it prints out one less data" --> rather than only _describe_ input and output, post the true input, output seen and expected output. – chux - Reinstate Monica Jul 01 '17 at 04:02
  • Compile with all warnings & debug info (`gcc -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/)...) then **use the debugger**. BTW, read documentaton of [scanf](http://en.cppreference.com/w/c/io/fscanf) and every function you are using – Basile Starynkevitch Jul 01 '17 at 04:38
  • See [Trailing blank in `scanf()` format string](http://stackoverflow.com/questions/19499060/what-is-difference-between-scanfd-and-scanfd) and don't use them. – Jonathan Leffler Jul 01 '17 at 06:40

2 Answers2

3

The problem is how you are formatting the scanf here

  for( i = 0 ; i<n ; i++ )
     scanf("%d ", &A[i] ) ;

The extra space after %d is messing up the input. Input data has to match the formatting of scanf string exactly. To fix this change to

  for( i = 0 ; i<n ; i++ )
     scanf("%d", &A[i] ) ;

this is because

White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input. Everything else matches only itself.

This explains it in detail

physicist
  • 844
  • 1
  • 12
  • 24
0

This code is working fine and printing all the data in reversed order provided you input the values of array by giving a space inbetween each, and all values at once.