Gokul UK
Gokul UK

Reputation: 49

Copy all array elements into another array in C

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

Upvotes: 1

Views: 83

Answers (2)

Kevin Ng
Kevin Ng

Reputation: 2174

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;
}

Upvotes: 0

Art Sd
Art Sd

Reputation: 31

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

Upvotes: 1

Related Questions