Filling every odd index in array

Hello everyone!

First off this is my first post so sorry if it's a tad out of touch with how the forum works!

Anyway, I am currently trying to fill a 64 length array[n] with 1/n. But fill every odd index with 0. Oh and the first [0] index should be 1, but I have that part correctly coded (see code below).

for example, the first 5 values should be:
Square = 1
Square = 0
Square = 0.3333
Square = 0
Square = 0.2
Square = 0
Square = 0.1429
Square = 0
Square = 0.1111 .......

instead of:
Square = 1
Square = 0.5
Square = 0.3333
Square = 0.25
Square = 0.2
Square = 0.1667
Square = 0.1429
Square = 0.125
Square = 0.1111


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    
    
    float step = 1;
    double op = 1;
    double op2 = 1;
    int arraysize = 32;
    long double saw [arraysize];
    long double square [arraysize];
    saw [0] = 1;
    square [0] = 1;

//-----------------------------------------

for (int i = 0.0; i < arraysize /*64*/ ; i++){

//---------------------------           
        step = step + 1.0;
//---------------------------     
        op2 = 1 / step;  //This correctly fills the array with the 1/[n]
//-------------------------
        square[i+1] = op2; // using this to push the array forward one so that square [1] = 0.5, rather than square [0] = 0.5.

        square[1] = 0;
        square[3] = 0;
        square[5] = 0;
        square[7] = 0;
        square[9] = 0;
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    const int ARRAY_SZ = 64 ;

    double array[ARRAY_SZ] = {0} ; // initialise to all zeroes

    // fill elements at even positions (note: i += 2 )
    for( int i = 0 ; i < ARRAY_SZ ; i += 2 ) array[i] = 1.0 / (i+1) ;

    // print the contents of the array, ten numbers per line
    for( int i = 0 ; i < ARRAY_SZ ; ++i )
    {
        std::cout << std::fixed << array[i] << "  " ;
        if( i%10 == 9 ) std::cout << '\n' ;
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/c920714c3b725feb
You sir, have done me a solid. Thank you!!
Topic archived. No new replies allowed.