08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

The following shows how we want the program to work:

Enter up to 100 numbers (end with 0)

2 7 5 3 0

Numbers entered: 4

Sum of numbers: 17

The average is 4.25

Numbers and differences from average

2 -2.25

7 2.75

5 0.75

3 -1.25

Program P8.1 shows how to write the program to work like this.

Program P8.1

//find average and difference from average

#include <stdio.h>

#define MaxNum 100

int main() {

int a, num[MaxNum];

int n = 0;

double sum = 0;

printf("Enter up to %d numbers (end with 0)\n", MaxNum);

scanf("%d", &a);

while (a != 0) {

sum += a;

num[n++] = a; //store in location n, then add 1 to n

scanf("%d", &a);

}

}

if (n == 0) printf("No numbers entered\n");

else {

printf("\nNumbers entered: %d\n", n);

printf("Sum of numbers: %1.0f\n\n", sum);

double average = sum / n;

printf("The average is %3.2f\n", average);

printf("\nNumbers and differences from average\n");

for (int h = 0; h < n; h++)

printf("%4d %6.2f\n", num[h], num[h] - average);

}

204

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!