![](/media/cache/profiles/Headshot_Fall2023_Square.jpg.50x50_q85.jpg)
Demonstrates runtime array allocation. Number of grades not known at compile time.
main.cpp
- Committer:
- CSTritt
- Date:
- 2017-10-23
- Revision:
- 0:f5bbc63c654b
File content as of revision 0:f5bbc63c654b:
/* Project: ArrayRunSize File: main.cpp Ported to mbed/Nucleo by: Dr. C. S. Tritt Last revised: 10/22/17 (v. 1.1) Horton Program 5.7 Averaging a variable number of grades. Runtime array creation. Also demonstrates array output showing index values. */ #include "mbed.h" int main(void) { printf("\nAssure Terminal > local echo is on.\n"); printf("Enter the number of grades: "); size_t nGrades = 0; // Number of grades. scanf("%zd", &nGrades); // The z is a type modifier for size type. float grade[nGrades]; // Array storing nGrades values. float sum = 0.0f; // Initialize sum of grades. printf("\nEnter the %zd grades:\n", nGrades); // Prompt for grade entry. // Read the grades to be averaged. for(size_t i = 0 ; i < nGrades ; ++i) { printf("%zd> ", i + 1); scanf("%f", &grade[i]); // Read a grade. sum += grade[i]; // Add it to the running sum. } // Display results. printf("The grades you entered are:\n"); for(size_t i = 0 ; i < nGrades ; ++i) { printf("Grade[%2zd] = %.1f ", i + 1, grade[i]); if ((i+1) % 5 == 0) printf("\n"); // After 5 values, go to a new line. } float average = sum/nGrades; // Calculate and display the average. printf("\nAverage of the %zd grades entered is: %.2f\n", nGrades, average); while (true) {}; }