Programming Fundamentals
Download advanced_addition.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity advanced_addition
Your task is to add code to this function in advanced_addition.c:
// Put the sum of the lines in the array into the last line
// accounting for carrying. Return anything you did not carry.
//
// NOTE: num_lines is the number of lines you are adding together. The
// array has an extra line for you to put the result.
int sum(int num_lines, int num_digits, int array[MAX_SIZE][MAX_SIZE]) {
// Put your code here.
return 0;
}
You will implement the sum function, which will be given a two-dimensional
array with a variable number of rows ("lines") and columns ("digits"), like
the following:

When you receive this array, you are guaranteed the last row will be all zeroes. For each column, starting from the right-most digit, you should add every digit in that column, and put the result of that addition into the last row.
An example of the first column is shown below
To simulate real addition, however, none of the values in the array may exceed
9, so you will need to implement "carrying", just like in normal addition.
"Carrying" is when all the numbers in a column sum to greater than 9, and
you add extra to the next column to keep the current column below 10. For
example, the following array:
And then
The sum In addition, the function will normally return 0. However, if your
addition cannot be represented in the array because the last column you add
still carries something over, your function should return the amount carried.
For example:
More formally, you should:
- Start at the rightmost column of the array.
- Add together the integers in that column, as well as anything "carried across".
- If the result of that addition would be less than ten, write the result of that addition into the last number in that row. Nothing is carried across.
- Otherwise, find the result of the addition modulo 10, and write that into the last value in the column.
- Then, divide the result of the addition by 10, and "carry that accross" to the next column.
- Repeat on the next column to the next, from step two.
- If you reach the leftmost column of the array, and there is still a value "carried across", return it. Otherwise, return zero.
The file advanced_addition.c contains a main function which reads values into
a 2D array and calls sum.
Examples
dcc advanced_addition.c -o advanced_addition ./advanced_addition Enter the number of rows (excluding the last): 3 Enter the number of digits on each row: 3 Enter 2D array values: 1 2 3 4 5 6 0 1 0 5 8 9 ./advanced_addition Enter the number of rows (excluding the last): 4 Enter the number of digits on each row: 2 Enter 2D array values: 1 3 1 3 1 3 1 3 5 2 ./advanced_addition Enter the number of rows (excluding the last): 2 Enter the number of digits on each row: 1 Enter 2D array values: 9 9 8 Carried over: 1