0
#include <stdio.h>
#include <conio.h>

void main()
{
  int arr[5], new[5], i, j;

  printf("ENTER ANY FIVE NUMBERS:");
  scanf("%d%d%d%d%d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);

  for(i=0; i<5; i++)
  {
    for(j=5; j>=0 ;--j)
    {
      new[i] = arr[j];
      printf("%d", new[i]);
      printf(" ");
    }
  }
  getch();
}

The above code is of a simple problem, which asks to take inputs of numbers in an array and show the inverse array of the input. I tried to solve it myself and wrote the above code. But the compiler is showing the result multiple times, I mean, the result should have only 5 numbers but the output shows series of numbers.

1
  • You have one for-loop too many. Commented Oct 20, 2018 at 11:23

1 Answer 1

1

Here is one problem:

for(j=5;j>=0;--j){
    new[i]=arr[j];
               ^ out of bounds access to arr[5]

Change it to

for(j=4;j>=0;--j){  // 4 instead of 5
    new[i]=arr[j];

That said, if all you want is to print an array in reverse order, simply do:

    for(j=4;j>=0;--j){
        printf("%d", arr[j]);
        printf(" ");
    }
    printf("\n");

No need for two loops and no need for the extra array new

If you really want a "reversed copy" do:

    for(j=4;j>=0;--j){
        new[4-j] = arr[j];
        printf("%d", arr[j]);  // or printf("%d", new[4-j]);
        printf(" ");
    }
    printf("\n");
Sign up to request clarification or add additional context in comments.

2 Comments

@user4386427 Thanks ...But I cant understand why does the two-loops not work ?
@NehalSamee With two loops you get 5*6 calls of printf as your inner loop executes 6 times and your outer loop executes 5 times

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.