Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program: Subtraction Please help with this problem. The square pattern is obtain

ID: 3597170 • Letter: P

Question

Program: Subtraction

Please help with this problem.

The square pattern is obtained by putting the numbers 37, 28, 1, and 25 at the corners of square. By joining the midpoints of its sides, a smaller square was drawn inside the first square. Each corner of this new square was allocated a number by finding the difference between the two numbers at the ends of the line (eg. 37-28-9,28-1-27). This new square was then taken as the starting point and the process was repeated until the numbers in the corners were the same - in this case, 6. The sign of the differences is to be ignored. Figure to be drawn in class. Your program should read in the four numbers at the corners of the initial square (the outermost square) from the UNIX command line (argv[1]) starting with the value in the upper right hand corner and continuing clockwise. You are to print out the values at the corners of all squares, including the initial square, until the corners are all the same. You may assume that the maximum number of squares will be 20. The original four numbers will be integers between 0 and 1000 inclusively. Sample launch and input: -/a.out 37 281 25 Output: 37 28 1 25 9 27 24 12 18 3 123 15 99 15 60 60

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>

int abs(int a) {
if ( a < 0) {
a = -1*a;
}
return a;
}

int main(int argc, char *argv[])
{
if (argc != 5) {
printf("Please enter exactly 4 integers between 0 and 1000 ");
exit(0);
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
int d = atoi(argv[4]);

while(1)
{
printf("%d %d %d %d ", a, b, c, d);
int newa, newb, newc, newd;
newa = abs(a-b);
newb = abs(b-c);
newc = abs(c-d);
newd = abs(d-a);
if ((newa == newb) && (newb == newc) && (newc == newd)) {
break;
}
a = newa;
b = newb;
c = newc;
d = newd;
}

return 0;
}

Sample run

37 28 1 25
9 27 24 12
18 3 12 3
15 9 9 15
6 0 6 0