【问题标题】:How to initialize an array using a for loop? [closed]如何使用 for 循环初始化数组? [关闭]
【发布时间】:2014-04-27 04:47:43
【问题描述】:

我希望有人可以帮助我。我有一个作业问题,说声明一个可以恰好存储 7 个 int 值的数组。展示 2 种不同的方式来初始化数组中的单元格,以便它们都包含值 65。一种技术必须使用循环。

我想出了一种不使用循环的方法,但有人可以告诉我一种使用循环的方法吗? 谢谢!

【问题讨论】:

  • 一个简单的谷歌搜索c for loop example会给出大量的答案

标签: c arrays for-loop


【解决方案1】:

下面的代码就可以了:

#include <stdio.h>

#define MAX_SIZE 7

int main()
{
   int arr[MAX_SIZE];

   for (int i = 0; i < MAX_SIZE; ++i) 
       arr[i] = 65;

   // Verify array output :
   for (int i = 0; i < MAX_SIZE; ++i)
       printf("%d\n", arr[i]);

   return 0;
}

【讨论】:

    【解决方案2】:

    这是一种方法,

    const int SIZE = 7; /* <----------- The size. */
    int array[SIZE];    /* <----------- How to declare an int array. */
    int x;              /* <----------- The loop counter. */
    for(x = 0; x < SIZE; x++) { /* <--- Initialize x. Test (x < SIZE). Increment x. */
        array[x] = 65; /* <------------ Set to 65 */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-08
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多