简体   繁体   中英

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

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.
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

After this changes the output is this:

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.

If you want to use a for loop to print elements of an array, you have two options. You can use a traditional for loop with a loop counter like 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. 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';
  }
}

Learn more about for loops here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM