【问题标题】:Is there a way to use Nested loops for insertion in array in C?有没有办法使用嵌套循环在 C 中插入数组?
【发布时间】:2021-04-19 17:31:02
【问题描述】:

所以这里是代码......

#include <stdio.h>
#include <stdlib.h>

int main() {
    int a[20] = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
    int new_num, n, i = 0;

    for (i; i < 10; i++) {
        //printf("the elements in the array are:");
        printf("%d\n",a[i]);
    }
    printf("enter the index you want to insert the element");
    scanf("%d", &n); //don't forget to add &
    printf("Enter the element");
    scanf("%d", &new_num);
    for (i = 9; i >= n; i--) {
        for (int j = 10; j > n; j--) {
            a[j] = a[i];
        }   
    }
    a[n] = new_num;

    printf("new array is:");
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }

    return 0;
}

and here is the output...

谁能告诉我我做错了什么?

我想使用嵌套循环将元素移动到下一个地址,而不是使用以下语法:

for (i = 9; i >= n; i--) {
    a[i + 1] = a[i];
} 

但输出看起来有点怪异,正如我在输出图像中显示的那样。

【问题讨论】:

  • 您应该在此处添加输出,而不是作为外部图像...只是将其作为代码传递
  • 很抱歉我没有足够的声望点来做这件事
  • 你有简单的单循环代码,那么你为什么有兴趣通过更复杂的代码来实现相同的结果呢?至于你的具体代码,没有意义。每个需要移动的元素只需要移动一次,到一个特定的新位置。相反,您的代码会破坏所有数组元素通过插入位置与插入位置的元素。效率低下。
  • @Antiarin,在您的问题中编辑额外的 文本 没有声誉阈值。
  • 非常感谢。我终于明白我做错了什么,我太傻了。至于声誉部分,我只是误解了你想说的话。我认为只需将其粘贴为代码,您只是将图像粘贴到帖子中,而不是输出文本。 xD

标签: arrays c nested-loops insertion


【解决方案1】:

问题是这个sn-p:

for (i=9;i>=n;i--){
    for (int j=10;j>n;j--){
        a[j]=a[i];
    }   
}

i == 4 时,您将索引超过4 的a 的所有元素设置为a[4] 的值(即6)。您可能想要更接近:

for (int j = 10; j > n; j++) {
    a[j] = a[j - 1];
}
a[n] = new_num;

另外,您有一个小错误,即您假设 a 的长度为 10,但您缺少值 3,因此它只有 9 个元素。

编辑:我刚刚看到您想使用嵌套循环。这是一个硬性要求吗?嵌套循环不是正确的方法。

【讨论】:

  • 我明白了。不,这不是一个硬性要求,是在尝试不同的东西。使用 for 循环我离成功还差得很远。无论如何,谢谢,我理解错误
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2020-01-06
  • 2010-09-30
  • 2021-08-10
  • 2020-09-14
  • 2019-08-22
  • 2011-04-30
  • 1970-01-01
相关资源
最近更新 更多