Search code examples
arrayscscanf

How to write a for loop that calculates the sum of the items in C?


I was programming an assignment which asked me to do the following:

1. User input : A list of decimal numbers. (The items represent numeric values of usd(us dollars), the first item is the dollar exchange ratio,

(let's say 1usd = 3.58another_currency, for example.)

  1. convert the values to another currency (the converted items will be in another list)

2.1 for example: original:[3.58 12 11.50 3.20 4.10] -> converted: [(42.96), (41.17), ....] (multiplied 3.58 by each item next)

  1. present it in a nice tabular form and the last line of the table should be the sum of the dollars and the sum of the converted currency

It seems that I have done the first step, and the second step correctly. But when calculating the sum of the other currency, I ran into a problem. Only the sum of the dollars happen to be correct, but the sum of the other currency is problematic. Not only it's incorrect, the sum is changing every time I run it. Green one is correct, red one is not correct. enter image description here

I activated the same function upon the two different arrays but it calculates only one of the sum correctly.

MY .H FILE (doll.c):

#define SIZE 10

void dollar_to_shekel(float[], float[]);

void print_array(float[], float[]);

float sum_array(int, float[]);

MY .C FILE (doll.c):

#include <stdio.h>
#include "doll.h"

void dollar_to_shekel(float usd[], float ils[])
{
  int i;
  for(i=1; i<SIZE; i++)
  {
    /*the first element in the received list, in index 0, is the dollar ratio*/
    ils[i-1] = usd[i] * usd[0];
  }
}

void print_array(float usd[], float ils[])
{
  int i;
  for(i=1; i<SIZE; i++)
  {
    printf("%.2f \t \t \t \t %.2f\n", usd[i], ils[i-1]);
  }
}

float sum_array(int x, float arr[])
{
  int i;
  float sum = 0;
  for(i=x; i<SIZE; i++)
  {
    sum = sum + arr[i];
  }
  return sum;
}

int main()
{
  float usd[SIZE];
  float ils[SIZE];
  int i;
  printf("Insert a list of numbers:");
  for(i=0; i<SIZE; i++)
  {
    scanf("%f", &usd[i]);
  }

  dollar_to_shekel(usd, ils);
  printf("$ \t \t \t \t IS\n");
  print_array(usd,ils);
  printf("%.2f \t \t \t \t %.2f\n", sum_array(1,usd), sum_array(0,ils));

  return 0;
}

I don't really know where and why the program fails with calculating the sum of one column, but does the job on the other.


Solution

  • as in the loop in dollar_to_shekel in the last iteration you assign ils[SIZE-1-1], which is correct as you start at 0 and have SIZE-1 values to calculate, you don't assign ils[SIZE-1], but it is included in the sum in sum_array. ils[SIZE-1] is a "random" value, so the result of the sum is random too. A solution would be to sum until SIZE-x:

        float sum_array(int x, float arr[])
        {
          int i;
          float sum = 0;
          for(i=x; i<SIZE-x; i++)
          {
            sum = sum + arr[i];
          }
          return sum;
        }