[英]Printing original array and changed array
I'm doing an exercise where I have to print the original array and add more elements to the array and print those too.我正在做一个练习,我必须打印原始数组并向数组添加更多元素并打印它们。 So the output should be
所以 output 应该是
Original array:
[10, 20, 30]
After append values to the end of the array:
[10 20 30 40 50 60 70 80 90]
The second part is printing but for some reason, the original array elements won't print.第二部分是打印,但由于某种原因,原始数组元素不会打印。
int arr[9] = {10, 20, 30};
cout << "The original array elements are : " << endl;
for (int i = 0; arr[i] <= 3; ++i)
{
cout << arr[i] << endl;
}
arr[3] = {40};
arr[4] = {50};
arr[5] = {60};
arr[6] = {70};
arr[7] = {80};
arr[8] = {90};
cout << "After append values to the end of the array : " << endl;
for (int j = 0; arr[j] >= 9; ++j)
{
cout << arr[j] << endl;
}
This is the code that I've written, could someone please tell me what I'm doing wrong?这是我写的代码,有人可以告诉我我做错了什么吗?
Because因为
for (int i = 0; arr[i] <= 3; ++i)
Means "loop until arr[i]<=3
", which is always false in your case.表示“循环直到
arr[i]<=3
”,在你的情况下这总是错误的。
You probably want instead this:你可能想要这个:
for (int i = 0; i < 3; ++i)
Same thing with the second loop, instead of arr[j] >=9
you probably want j < 9
与第二个循环相同,而不是
arr[j] >=9
你可能想要j < 9
After this changes the output is this:在此更改后 output 是这样的:
The original array elements are :
10
20
30
After append values to the end of the array :
10
20
30
40
50
60
70
80
90
for (int i = 0; arr[i] <= 3; ++i)
Should be应该
for (int i = 0; i < 3; ++i)
and similarly the j
-loop should check for j < 9
, because you want to check the number of elements (3 and 9) printed, not their values.同样,
j
-loop 应该检查j < 9
,因为您要检查打印的元素(3 和 9)的数量,而不是它们的值。
If you want to use a for loop to print elements of an array, you have two options.如果你想使用 for 循环来打印数组的元素,你有两个选择。 You can use a traditional for loop with a loop counter like
i
.您可以使用带有循环计数器的传统 for 循环,例如
i
。 This is usually preferred if you want to iterate over a partial range.如果您想迭代部分范围,这通常是首选。 You usually compare the loop counter with the last index.
您通常将循环计数器与最后一个索引进行比较。 On the other hand, if you are going to iterate over the whole thing, a more convenient option is to use a range-based for loop.
另一方面,如果您要遍历整个事物,更方便的选择是使用基于范围的 for 循环。 You can see both examples here:
您可以在此处查看这两个示例:
#include <iostream>
int main() {
int arr[9] = {10, 20, 30};
std::cout << "The original array elements are :\n";
// Traditional for-loop
for (int i = 0; i <= 3; ++i) {
std::cout << arr[i] << '\n';
}
arr[3] = {40};
arr[4] = {50};
arr[5] = {60};
arr[6] = {70};
arr[7] = {80};
arr[8] = {90};
std::cout << "After append values to the end of the array :\n";
// Range-based for loop
for (auto const elm : arr) {
std::cout << elm << '\n';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.