Santino
Santino

Reputation: 23

Why isn't my code working properly when looping this array

if I have the array N[12] and I have the code:

float N[12];
for (int X = 1; X < 12; X++) {
    N[X] = N[X] + 2;
    cout << N[X] << endl;
}

what else do I need to get this to display odd numbers starting at 1 and increasing until I have 12?? (so until 23)

Its outputting a really weird slew of numbers I'm pretty new to c++, I know this is a silly question, sorry...

Upvotes: 1

Views: 129

Answers (3)

kadina
kadina

Reputation: 5376

Couple of issues in your code as mentioned below.

Major issue : your array is uninitialized. So when you perform N[x] = N[x] + 2, it is meaningless as N[x] doesn't have any value.

Minor issue : No need to declare array as float as we are going to store integer values.

Below is the code.

#include <iostream>

using namespace std;

int main()
{
    int N[12];

    for(int x = 0; x < 12; x++)
    {
        N[x] = (2 * x) + 1;
        cout << N[X] << endl;
    }

    return 0;
}

Upvotes: 3

Russell Islam
Russell Islam

Reputation: 216

Your array is not initialized to any values, so depending on how your compiler does it, it most likely will be filled with random values. This would explain why you are seeing weird numbers.

Since you want to start with a initial value of 1, you can initialize your array like this:

float N[12] = { 1 }; 

This will set the first element of the array to 1 and the rest of the elements will be set to 0. But then the other person is right, in that you want to add 2 to the previous element in your array. So it would make the code into this:

float N[12] = { 1 }
int X;

for(X=1; X<12; X++){
  N[X]= N[X-1] + 2;
  cout << N[X] << endl;
}

Upvotes: 4

Aplet123
Aplet123

Reputation: 35482

I think you mean to add two to the previous element, not the current one, since the current one is uninitialized. Also, since odd numbers are integers, you don't need floats.

int n[12];
n[0] = 1; // start off with the first odd
for (int x = 0; x < 12; x ++) {
    // we already have a value for n[0] so we shouldn't overwrite it
    if (x != 0) {
        // n[x - 1] gets the previous value
        n[x] = n[x - 1] + 2;
    }
    std::cout << n[x] << std::endl;
}

Upvotes: 1

Related Questions