In: Computer Science
3. Complete programming project 5 in Chapter 5 of the Hanly/Koffman Problem Solving & Program Design in C book. All input should be read from a file and output should be written to a file. Make sure that you design a function greatest_common_divisor() which calculates and returns the greatest common divisor of two integer numbers. Also, develop functions to read data from a file and to write data to a file. Problem Statement: The greatest common divisor (gcd) of two integers is the product of the integers' common factors. Write a program that inputs two numbers and implements the following approach to finding their gcd. We will use the numbers -252 and 735. Working with the numbers' absolute values, we find the remainder of one divided by the other. 252 / 735 = 0 R252 Now we calculate the remainder of the old divisor divided by the remainder found. 735 / 252 = 2 R231 We repeat this process until the remainder is zero. 252 / 231 = 1 R21 231 / 21 = 11 R0 The last divisor (21) is the gcd.
Below is the code in C for the calculation of GCD by reading two integers from the file and then writing back the result to file. One function is built for the reading of input, one for writing the output and one for calculating the GCD. Sample output is attached at the end, and also attached the sample input and output file.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int gcd(int a, int b){ // gcd function following the logic given in question.
if(a==0) return b;
return gcd(b%a, a);
}
void read_file(int *first, int *second, char *str){ // reading from file function.
FILE * pFile;
int number;
pFile = fopen (str,"r"); // opening file in read mode.
int idx = 1;
while (!feof (pFile)) { // reading till the end of the file.
fscanf(pFile, "%d", &number);
if(idx%2==1){ // logic to appropriately updating the two variables for gcd calculation.
*first = number;
idx++;
}
else{
*second = number;
}
}
fclose (pFile); // closing the file.
}
void write_file(int result, char *str){
FILE *fptr;
fptr = fopen(str, "w"); //opening the file in write mode.
if (fptr != NULL){ // since only one integer to write, 'if' is used, otherwise loop can be used.
fprintf(fptr, "%d", result);
}
fclose(fptr); // closing the file.
}
int main()
{
int first, second;
printf("reading from file...\n");
read_file(&first, &second, "input.txt"); // calling reading function by providing two integers address and file name as a string.
printf("first = %d ",first);
printf("second = %d \n",second);
int gcd_ans = gcd(abs(first), abs(second)); // calling gcd function.
printf("gcd = %d\n",gcd(abs(first), abs(second)));
printf("writing result to file...\n");
write_file(gcd_ans, "integers.txt"); // calling write function.
return 0;
}
Sample Output:-
Input File:-
Output File:-