Help with populating an array

Hi there,
Im trying to populate an array with values in increments of 2.
I.e. index 0 = 2, index 1 = 4 etc. up to index 14 with value 30, using a for loop.

But im struggling with this part. Ive gotten so far as to creating a simple for loop but cant wrap my head around it fully.

Any help would be appreciated.
Heres what I have so far.

1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;

int main (){
  return 0;
}
Last edited on
You could use a var value with initial value of 0 and increment it by 2 inside the loop and assign it to array[i]
Now I've made a mess :D

Somehow I feel I've made it worse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;

int main (){

  int size = 15, n, i;
  double array[size];

  for (int i = 0; i < size; i++ ){
    for (int n = 2; n <= 30; n+=2){
  }
    array[i] = n;
    cout << array[i] <<endl;
  }


  return 0;
}


Just a little bit more suggestion please
Last edited on
In your ORIGINAL code, change line 12
array[i] = i;
to
array[i] = 2 * ( i + 1 );

It will then produce what you want, I believe.


When that is corrected, REMOVE the statement
#include <array>
because that is a particular type of C++ container that you are NOT using.

To avoid potential confusion, I would also rename "array" as something else as well.


I believe (but could be wrong) that
int size = 15;
should, for strictly-standards-compliant code actually be
const int size = 15;
if you are intending to declare an array with that size.
Last edited on
My idea:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
include <iostream>

using namespace std;

int main (){

  const int size = 15;
  double array[size];
  int val = 0;
  for (int i = 0; i < size; i++ ){
      array[i] = val;
      val += 2;
      cout << array[i] <<endl;
  }


  return 0;
}
Facepalming really hard right now!

Thank you both so much!
Topic archived. No new replies allowed.