C - Write program to read values from user and store in array


Write a program that will read five values from the keyboard.

Store them in an array of type float with the name amounts.

Create two arrays of five elements of type long with the names dollars and cents.

Store the whole number part of each value in the amounts array in the corresponding element of dollars and cents

Output the values from the two arrays of type long as monetary amounts (e.g., $2.75).


2.75 in amounts[1] would result in 2 being stored in dollars[1] and 75 being stored in cents[1].


#include <stdio.h>

int main(void)
  const size_t size = 5;
  float amounts[size];       // Stores data values
  long dollars[size];
  long cents[size];

  printf("Enter %zd monetary values separated by spaces:\n", size);
  for (size_t i = 0; i < size; ++i)
    scanf("%f", &amounts[i]);

  for (size_t i = 0; i < size; ++i)
  {/*ww  w.  ja v  a  2s.  co m*/
    dollars[i] = (long)amounts[i];
    cents[i] = (long)(100.0*(amounts[i] - dollars[i]));

  for (size_t i = 0; i < size; ++i)
    printf("  $%d.%02d", dollars[i], cents[i]);

  return 0;


Related Exercise