Home > Back-end >  Troubleshooting for loop - problems with sum
Troubleshooting for loop - problems with sum

Time:10-12

Im taking a C programming beginning course, and have a problem with a for loop.

I want to make two double arrays. One that takes input from user, and one that sums the inputs. I then want to output the two arrays. One that shows the input, and one that shows the sums og the input in every cell.

The problem comes when I try to show the sum for every "cell" in the array. The output just becomes the same as the input. I can solve it with:

// print all the numbers in the second array
   for (i = 0; i < n; i  ) {
     sum = sum   a[i];
       printf("%lf ", sum);

but then the assignment wouldn't be solved. Hope you can educate me.

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


int main(void) {

int n; //numbers of cells
int i; //The numbers in the cells


printf("How many cells in the array would you like? \n");
scanf("%d", &n);


double a[n], sum=0; // declare an array and a loop variable.
double b[n], sumo=0;

printf("Enter the numbers:\n");


for (i = 0; i < n; i  ) { // read each number from the user
    scanf("%lf", &a[i]);
}

printf("The results, my lord:\n");

// print all the numbers in the first array
for (i = 0; i < n; i  ) {
    printf("%lf ", a[i]);

}
printf("\n"); //THIS IS WHERE THE PROBLEM STARTS
// print all the numbers in the second array
   for (i = 0; i < n; i  ) {
     b[i] = b[i]   a[i];
       printf("%lf ", b[i]);
   }

return 0;

}

CodePudding user response:

You can calculate the sum (aka the b array) when you read the user data:

for (i = 0; i < n; i  ) 
{
    scanf("%lf", &a[i]);
    if (i == 0)
    {
        b[i] = a[i];
    }
    else
    {
        b[i] = b[i-1]   a[i];
    }
}

or do it like:

scanf("%lf", &a[0]);
b[0] = a[0];
for (i = 1; i < n; i  ) 
{
    scanf("%lf", &a[i]);
    b[i] = b[i-1]   a[i];
}

or do it like:

sum = 0;
for (i = 0; i < n; i  ) 
{
    scanf("%lf", &a[i]);
    sum  = a[i];
    b[i] = sum;
}

CodePudding user response:

For starters the array b is not initialized

double b[n], sumo=0;

So this statement

b[i] = b[i]   a[i];

invokes undefined behavior.

It seems what you need is the following for loop

for (i = 0; i < n; i  ) {
  b[i] = a[i];
  if ( i != 0 ) b[i]  = a[i-1];
    printf("%lf ", b[i]);
}
  • Related