Home > Net >  Double arrays in C
Double arrays in C

Time:10-19

Im in the process of learning C and the basis of the class is C primer plus(6th edition). We use Eclipse as an IDE.

For an project we have to create to arrays. One array that takes numbers in a loop and another array that display the cumulative value. So if array 1 has values 1, 5 and 3(out of 10 inputs total) then the resulting input in array 2 should be 9(on the 3th input because of the 3 inputs in array 1).

Im having trouble getting started the right way - anyone here has ideas how I could proceed? So far I have this for starters but forgive me for it it very weak:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 10
void doublearrays (double usernumber);

int main(void)
{
    double usernumbers = 0.0;
    int loop1 = 1;
    while(loop1)
    {
        printf("Type numbers as doubles. \n");
        fflush(stdout);
        loop1 = scanf("%lf", &usernumber);
        if(loop1)
        {
            doublearrays(usernumber);
        }
    }
    return 0;
}

CodePudding user response:

(your current code isn't what you need... delete it and then...)

anyone here has ideas how I could proceed?

Well the first step would be to actually define some arrays.

double input[SIZE];
double cum[SIZE];

The next step would be a loop to read input.

for (int i = 0; i < SIZE;   i)
{
    if (scanf("%lf", &input[i]) != 1)
    {
        // Input error - add error handling - or just exit
        exit(1);
    }
}

The next step is to add code for calculating the the cumulative value.

I'll leave that for you as an exercise.

The last step is to print the array which I also will leave to you as an exercise.

CodePudding user response:

All the text in a homework assignment shall be read:

For a project we have to create two arrays... 10 inputs total...

Why on earth do not you declare them?... You already have defined SIZE so

double usernumbers[SIZE];
double cumulnumbers[SIZE];

Next do yourself a favour and handle one problem at a time:

One array that takes numbers in a loop...

Ok, so write a loop up to 10 reading floats directly into the array and note how many numbers were received

int n;
for(n=0; n<SIZE; n  ) {
    if (scanf("%lf", &usernumbers[n]) != 1) break;
}
// ok we now have n number in the first array

Let us go on

and another array that display the cumulative value.

Ok cumul is initially 0. and is incremented on each value from the first array:

double cumul = 0.;
for(int i=0; i<n; i  ) {
    cumul  = usernumbers[i];
    cumulnumbers[i] = cumul;
}
  • Related