【发布时间】:2014-07-28 06:24:51
【问题描述】:
我有一个简单的问题,我正在尝试用 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
现在,这段代码有两个问题——
- 如您所见,程序打印出匹配的数组元素两次。这是因为,按照我构建程序的方式,一旦变量
i从第一个元素到最后一个元素循环遍历数组,然后j从最后一个元素循环到第一个元素。因此,每个都打印出匹配的数组元素一次,从而产生两组值。 - 我的第二个问题是 - 在我的代码中,我在 for 循环 (
0 to 9 for an array of 10 elements) 中硬编码了数组的长度。可以进行哪些更改,以便用户输入的数组长度可以直接在 for 循环中使用?
我读过,在 C 中,array dimensions(声明时)不能是 variable。所以,像这样的declaration(这是我的第一个想法)是行不通的-
int n; // n is no. of elements entered by the user
int arr[n];
我是编程新手,所以如果问题听起来/太简单、质量低下,我深表歉意。
谢谢。
【问题讨论】:
标签: c arrays loops nested-loops