c - 交换列表中的元素

标签 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个 输入5个元素 2个 4个 6个 8个 0 输入要交换的第一个数字: 8个 输入要交换的第二个数字: 2个 8 与 2 交换位置。 输出将是: 8 4 6 2 0

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

最佳答案

只要没有进一步的说明,您只需遍历数组,并将每次出现的 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;
  }
}

关于c - 交换列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484078/

相关文章:

c - 移入一位(此位应为“1”)

c - 为什么C中的这个无限循环不是无限循环呢?

c - 此代码在指针数组中返回错误的第一个指针

c - 如果我使用 else, "EVEN NUMBER ENTERED"会打印一次,如果我不使用,它会打印两次。为什么?

c - 用 C + Winapi 编程 : Launching A Second Window When A Button Is Pressed

c - 常量数组的声明

c - 使用 C 文件函数的 nesC 文件

c - 对一维数组进行排序的函数不起作用?

c - malloc'ing 和 realloc'ing 指针在返回时导致内存泄漏

c - 为什么快速排序比计数排序更好?