My question is about array.How do we store even numbers in an array without initializing array at first and store them in consecutive memory locations

Viewed 55

Write a C++ program to Input 6 even numbers in an array and then display them one by one.

I wrote this C++ program:

#include <iostream>

using namespace std;

int main() {
  int num[6];
  int i, ;
  for (i = 1; i <= 12; i++) {
    if (i % 2 == 0) {
      num[i] = i;
      cout << num[i] << endl;
    }
  }

  return 0;

But the mistake here is I have to store all the even values in consecutive memory locations like num[1], num[2], num[3] to num[5] but with this method the values will store in even arrays only like num[2], num[4], num[6], etc.

What could be the real solution? My scope is only in C++.

1 Answers

This for loop

for(i=1;i<=12;i++)
{
    if(i%2==0)
{
    num[i]=i;
    cout<<num[i]<<endl;
    }

}

is incorrect because there is used an invalid index to access elements of the array. For example when i is equal to 12 you are trying to access 13-th element of the array that does not exist (indices in C++ start from 0).

Just write

for( i = 0; i < 6; i++ )
{
    num[i] = 2 * ( i + 1 ) ;
    cout<<num[i]<<endl;
}

Pay attention to that it is a bad programming practice to use magic numbers as 6. Instead you should introduce a named constant.

If your compiler supports C++ 20 then you could write for example using the range-based for loop

const size_t N = 6;
int num[N];

for ( int value = 1; auto &item : num )
{
    item = 2 * value++;
}

If your compiler does not support C++ 20 then just place the declaration of the variable value before the range-based for loop

const size_t N = 6;
int num[N];

int value = 1;
for ( auto &item : num )
{
    item = 2 * value++;
}
Related