交换列表中的元素

时间:2013-01-23 16:09:37

标签: c

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

int main()
{
   int array[100], num1, c, n, num2;

   printf("Enter number of elements in array\n");
   scanf("%d", &n);

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

   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);

   printf("Enter the number to swap\n");
   scanf("%d", &num1);

   printf("Enter the number to swap with\n");
   scanf("%d", &num2);

    printf("%d is swap place with %d.\n", num1, num2);


    for (c = 0; c < n; c++)
   {
   if (array[c] == num1)
   {
    array[c] = num2;
   }
   else if (array[c] == num2)
   {
    array[c] = num1;
   }
  }

  printf("The new output will be\n");

        getch();       
        return 0;
 }

嗨,我正在做我的代码的一半,但我不知道如何继续。 我正在编码以在列表中交换号码。有人可以帮帮我吗?

输入数组中的元素数: 五 输入5个元素 2 4 6 8 0 输入要交换的第一个数字: 8 输入要交换的第二个数字: 2 8是交换位置2。 输出将是: 8 4 6 2 0

如何输入-1到结束程序? 示例:输入数组中的元素数:-1 输出:结束程序。

1 个答案:

答案 0 :(得分:0)

只要没有进一步的说明,您只需要遍历您的数组,并将8的每次出现更改为2,反之亦然。

int i;

for (i = 0; i < n; i++)
{
  if (array[i] == num1)
  {
    array[i] = num2;
  }
  else if (array[i] == num2)
  {
    array[i] = num1;
  }
}
相关问题