Computers in Engineering WWW Site - Example 13.2

Example 13.2


C Version

/*
  This program demonstrates how to sum all the elements of an array.
*/

#include <stdio.h>

main()
{
  /*  Declaration Statements  */
  char month[12][4];
  short units[12];
  double sales[12];
  double ss;            /* ss stands for sum of sales */
  short i, j, su, k;    /* su stands for sum of units */

  clrscr();
  printf("C52.C -> How to sum all the elements of an array \n");

  /*  Assignment Statements  */
  for (i = 1; i <= 12; i++) {
    printf("\nMonth (Jan,Feb,...) : ");
    scanf("%s",month[i-1]);
    printf("\nUnits Sold          : ");
    scanf("%hd", &units[i - 1]);
    printf("\nSales (in million $): ");
    scanf("%lg", &sales[i - 1]);
  }

  i = 0;
  for (j = 1; j <= 4; j++) {
    su = 0;
    ss = 0.0;
    for (k = 1; k <= 3; k++) {
      i++;
      su += units[i - 1];
      ss += sales[i - 1];
    }  /*  End of inner for{} loop  */

    /*  Print result by quarter  */
    printf("\nquarter%2d%7d cars     $%5.1f m\n\n", j, su, ss);
  }  /*  End of outer for{} loop  */

  return(0);
}
/* End of Program C52 */
/*
INPUT :

Jan
5
12
Feb
4
78
Mar
1
3
Apr
5
32
May
6
12
June
5
32
July
1
12
Aug
34
12
Sep
4
10
Oct
5
23
Nov
1
23
Dec
0
0

OUTPUT :

C52.C -> How to sum all the elements of an array

Month (Jan,Feb,...) : Jan
Units Sold          : 5
Sales (in million $): 12
Month (Jan,Feb,...) : Feb
Units Sold          : 4
Sales (in million $): 78
Month (Jan,Feb,...) : Mar
Units Sold          : 1
Sales (in million $): 3
Month (Jan,Feb,...) : Apr
Units Sold          : 5
Sales (in million $): 32
Month (Jan,Feb,...) : May
Units Sold          : 6
Sales (in million $): 12
Month (Jan,Feb,...) : June
Units Sold          : 5
Sales (in million $): 32
Month (Jan,Feb,...) : July
Units Sold          : 1
Sales (in million $): 12
Month (Jan,Feb,...) : Aug
Units Sold          : 34
Sales (in million $): 12
Month (Jan,Feb,...) : Sep
Units Sold          : 4
Sales (in million $): 10
Month (Jan,Feb,...) : Oct
Units Sold          : 5
Sales (in million $): 23
Month (Jan,Feb,...) : Nov
Units Sold          : 1
Sales (in million $): 23
Month (Jan,Feb,...) : Dec
Units Sold          : 0
Sales (in million $): 0
quarter 1     10 cars     $ 93.0 m


quarter 2     16 cars     $ 76.0 m


quarter 3     39 cars     $ 34.0 m


quarter 4      6 cars     $ 46.0 m

*/

Last modified: 22/07/97