将所有数组元素复制到另一个数组中

标签 c arrays

我完成了我的逻辑,它实际上用于将一个数组元素复制到另一个数组中,但在打印语句的最终输出(点1)中并没有像我预期的那样工作得很好。

我希望打印要打印的复制值,但它没有显示数组的最后一个元素。

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

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

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

我到目前为止的代码:

    #include <stdio.h>
    int main()
    {
       int a[50],b[50],m,n,loc;

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

       scanf("%d", &m);

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

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

       printf("Enter size of 2nd Element:\n");

       scanf("%d", &n);

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

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

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

       scanf("%d", &loc);

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

      }

      for(int i=0;i<n;i++)
      {
          a[loc+i] = b[i];
      }

      printf("Result of final Array is\n");

      for(int i=0;i<=m+n;i++)  //point-1
        {
          printf("%d \n", a[i]);
        }

       return 0;
    }

最佳答案

A minor mistake fixed in the code. Added the size of n in the final printing loop (Point -1).

#include<stdio.h>

int main()
{
    int a[50],b[50],m,n;
    int loc;

    printf("Enter the size of 1st Element\n");

    scanf("%d", &m);

    printf("Enter %d elements\n", m);

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

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

    scanf("%d", &n);

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

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

    printf("Enter the location to insert\n");

    scanf("%d", &loc);

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

    for(int i=0;i<n;i++)
    {
        a[loc+i] = b[i];
    }

    printf("Final Elements\n");

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

    return 0;

}

关于将所有数组元素复制到另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264626/

相关文章:

c - 如何 - 使用文件锁求矩阵元素之和 (unix - C/C++)

c - 如何获取函数内 double 值的绝对值(不使用 math.h)

javascript - 更改数组字符串值的第一个(或任何)字符

c - 打印结构

c - C语言中<<是什么意思?

c++ - 在运行时确定缓冲区的大小? (套接字编程)

javascript - Vue如何将具有特定键的对象推送到数组

java - 将 JSONObject 值作为数据库中的单独实体存储在数据库中

arrays - 在 o(1) 的整数数组中查找 i 和 j 之间的元素数

ios - 使用随机生成的字符串查找数组字符串值的索引