// =================================================================== // Program: for_loop_sum.c // Date: July 2020 // Author: Jean-Michel Richer // Email: jean-michel.richer@univ-angers.fr // =================================================================== // Description: // This program shows how to code a for loop in C and iterate // through an array. // It is intended to be translated in 32 bits x86 assembly // language. // =================================================================== #include #include #include // Size of the array const int MAX_ELEMENTS = 8; // Array of integers that needs to be allocated int *array; /** * Initialization with random numbers from 1 to 10 * @param a array of integer * @param size size of the array */ void random_init(int *a, int size) { for (int i = 0; i < size; ++i) { a[i] = (rand() % 10) + 1; } } /** * Print contents of the array * @param a array of integer * @param size size of the array */ void print_values(int *a, int size) { for (int i = 0; i < size; ++i) { printf("%d ", a[i]); } printf("\n"); } /** * Sum of the values of the array * @param a array of integer * @param size size of the array */ int array_sum(int *a, int size) { int sum = 0; for (int i = 0; i < size; ++i) { sum += a[i]; } return sum; } /** * main method */ int main(int argc, char *argv[]) { // initialize random number generator srand( time(nullptr) ); // allocate array array = new int [ MAX_ELEMENTS ]; // initialize araray with random values random_init( array, MAX_ELEMENTS ); // print contents of array print_values( array, MAX_ELEMENTS ); // compute and print sum of values of array printf( "sum=%d\n", array_sum( array, MAX_ELEMENTS ) ); // free resources delete [] array; return EXIT_SUCCESS; }