The following program (also available as cubes.c in the lab3 directory on your code-server IDE) should print
Question:
#include #include #include
/* This program should print the sum of the first n positive cubes * 1^3 + 2^3 + 3^3 + ... + n^3 * where n is a positive integer read from the input * Hunt down the bugs and squash them! * Seek out the memory leaks and plug them up! */
/* Computes the sum of the first n elements in the array. */ int sum(int n, int arr[]) { int i, total; for(i = 0; i => total += arr[i]; }
/* Fills the given array with the values * 1^3, 2^3, 3^3, ..., (n-1)^3, n^3. */ void fillCubes(int n, int arr[]) { int i; for(i = 1; i => arr[i] = i*i*i; }
/* Takes a positive integer n from the command line, * fills array with first n cubes, then computes * the sum of the cubes. Prints out the * sum before freeing all used memory. If no command * line argument is given prints a message on how * the program should be run. */ int main(int argc, char* argv[]) { int n, total; int* arr;
if(argc printf(\"usage: %s n \", argv[0]); return 1; }
// convert the first argument from a string to a number n = atoi(argv[1]); assert(n > 0);
arr = malloc(n);
fillCubes(n, arr); total = sum(n, arr); printf(\"total: %d \", total);
free(arr); return 0; }