c - 如何在 C 中正确比较和打印出此数组中的匹配元素?

标签 c arrays loops nested-loops

我有一个简单的问题,我正在尝试用 C 编写解决方案。

If an array arr contains n elements, then write a program to check 
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.

我的代码看起来像这样-

#include<stdio.h>
int main()
{
    int arr[10],i=0,j;
    int k=0;
    printf("\n Enter 10 positive integers: \n");
    for(k=0;k<=9;k++)
    scanf("%d",&arr[k]);

    while(i<=9)
    {
        for(j=9;j>=0;j--)
        {
            if(arr[i]==arr[j])
            {
                printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
            }

            i++;
            continue;
        }
    }

    return 0;
}

输入此输入时-

 Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90

我得到的输出是-

 The array element 20 is equal to array element 20

 The array element 40 is equal to array element 40

 The array element 40 is equal to array element 40

 The array element 20 is equal to array element 20

现在,这段代码有两个问题-

  1. 如您所见,程序两次打印出匹配的数组元素。这是因为,按照我构建程序的方式,一旦变量 i 从第一个元素到最后一个元素循环遍历数组,然后 j 从最后一个元素循环遍历到第一个元素。因此每个都打印出匹配的数组元素一次,从而产生两组值。
  2. 我的第二个问题是——在我的代码中,我在 for 循环中对数组的长度进行了硬编码(对于 10 个元素的数组为 0 到 9)。可以做哪些更改,以便用户输入的数组长度可以直接用于 for 循环?

我读到过,在 C 中,数组维数(声明时)不能是变量。所以,像这样的声明(这是我的第一个想法)是行不通的-

int n; // n is no. of elements entered by the user

int arr[n];

我是编程新手,所以如果问题听起来/太简单、质量太差,我深表歉意。

谢谢。

最佳答案

1)你可以遍历数组一半,只得到一次打印。您可以使用 for(j=9;j>=9/2;j--) 而不是 for(j=9;j>=0;j--) >.

2)

int n;
int arr[n].

最近的编译器支持这个声明。如果你不喜欢使用它,你可以为数组进行动态内存分配。

关于c - 如何在 C 中正确比较和打印出此数组中的匹配元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24989486/

相关文章:

c - 给C中的指针赋值

c - 从 C 中的路径名中提取基本路径

c - FindHeight(二叉树)方法总是返回 1?

c# - Foreach 循环 - 以不同方式显示项目,前 3 项,项目 4-6 等

c - 如何在c中使用数组存储字符串?

arrays - 在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

Php关联数组排序并获取最大长度的键

c++ - 这两种动态扩展数组的方法有什么区别?

python - 根据 sort_values 标准添加水平线以绘制

Javascript FOR 循环回调