1

I done with my logic which is actually used to copy a Array elements into another Array but in the final output(Point 1) of printing statement is not working well as I expecting.

    #include <stdio.h>
    int main()
    {
       int arr[50],n,key,loc;

       printf("Enter size of the Elements:\n");

       scanf("%d", &n);

       printf("Enter %d Elements\n", n);

       for(int i=0;i<n;i++)
       {
           scanf("%d", &arr[i]);
       }
       //int a = arr[i];

       printf("Enter the Element to insert:\n");

       scanf("%d", &key);

       printf("Enter the Location to insert:\n");

       scanf("%d", &loc);

       for(int i=n-1;i>=loc;i--)
       {
           arr[i+1] = arr[i];
       }

       arr[loc] = key;

       printf("Result of Array:\n");

       for(int i=0;i<=n;i++) //Point 1
       {
           printf("%d\n", arr[i]);
       }

       return 0;
    }

Its expecting to print the copied value to print but its not showing the last element of the array.

eg: a[] = 1,2,3 b[] = 8,9

Expecting o/p: 1,2,3,8,9

Actual o/p: 1,2,3,8

2 Answers 2

1

When you insert your element into your array, the size of your array increases; you should put a n++ before printing.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure that is the right code that you are trying to solve? I don't see anything wrong with that logic except the potential for buffer overflow from the input. I think your logic is correct. But instead of declaring a size for the array, you can just let the value from user input do that. I posted the code below, just a small fix to make your code to become dynamic because there isn't anything wrong with your code logic.

#include <stdio.h>
int main()
{
   int n,key,loc;

   printf("Enter size of the Elements:\n");

   scanf("%d", &n);

   int arr[n + 1]; 

   printf("Enter %d Elements\n", n);

   for(int i=0;i<n;i++)
   {
       scanf("%d", &arr[i]);
   }
   //int a = arr[i];

   printf("Enter the Element to insert:\n");

   scanf("%d", &key);

   printf("Enter the Location to insert:\n");

   scanf("%d", &loc);

   for(int i=n-1;i>=loc;i--)
   {
       arr[i+1] = arr[i];
   }

   arr[loc] = key;

   printf("Result of Array:\n");

   for(int i=0;i<=n;i++) //Point 1
   {
       printf("%d\n", arr[i]);
   }

   return 0;
}

Comments

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.