从数组中复制一个元素并将其粘贴到最后?

时间:2017-07-19 15:17:51

标签: c

错误:我没有得到所需的输出

这是我的计划流程:

  1. 获取元素数量。
  2. 获取所有元素。
  3. 获取要复制的元素的位置。
  4. 在集合末尾添加复制元素。
  5. 显示集合。
  6. 代码:

    #include<stdio.h>
    void main()
    {
        int arr[20],position,i,n,value;
        printf("Enter number of elements in the set\n");
        scanf("%d",&n);
    
        printf("Enter the elements in the set\n");
        for(i=0;i<n;i++)
            scanf("%d",&arr[i]);
    
        printf("Enter the position of element to be replicated\n");
        scanf("%d",&value);
        for(i=n-1;i>=position-1;i--)
            arr[i+1]=arr[i];
        arr[position-1]=value;
    
        printf("Set after replication is\n");
        for(i=0;i<=n;i++)
            printf("%d\n", arr[i]);
    }
    

1 个答案:

答案 0 :(得分:1)

如果我不理解,你想把元素放在数组的末尾,而另一个则放在同一个地方。这种情况下的代码可以是:

#include<stdio.h>
void main()
{
    int arr[20],position,i,n,value;
    printf("Enter number of elements in the set\n");
    scanf("%d",&n);

    printf("Enter the elements in the set\n");
    for(i=0;i<n;i++)
       scanf("%d",&arr[i]);

    printf("Enter the position of element to be replicated from 1 to n\n");
    scanf("%d",&value);
    arr[n]=arr[value-1];

    printf("Set after replication is\n");
    for(i=0;i<=n;i++)    
       printf("%d\n", arr[i]);
}