# C Language Programming Fifth Edition Tan Haoqiang's Postclass Answers Chapter VII Exercise Answers

Posted by therealchuckles on Sun, 06 Mar 2022 18:34:09 +0100

## 1. Write two functions to find the maximum common divisor and the minimum common multiple of two integers respectively. Call the two functions with the main function and output the results. Two integers are entered by the keyboard.

Interpretation: This topic mainly examines two kinds of knowledge:

Rolling-and-rolling division: divide small values by large values, assign small values to large values if the remainder is not equal to zero, and assign small values to the remainder. Continue repeating the previous step until the remainder is zero, and the remainder of the previous step is the greatest common number we are looking for.

Minimum common multiple: The minimum common multiple has a property that is "Minimum common multiple x Maximum common multiple = Integer multiply"

```int function_Common_divisor(int num1, int num2)
{
int temp = 0;
//Ensure that large values are divided by small values
if (num1 < num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
//You can use the remainder here by accident and jump out of the loop if num1%num2 = 0
while (num1 % num2)
{
num1 = num1 % num2;
temp = num1;
num1 = num2;
num2 = temp;
}
//Pass out the last non-zero remainder
return num2;
}
//Properties of Minimum Common Multiple
int function_Common_multiple(num1, num2, Common_divisor)
{
return ((num1 * num2) / Common_divisor);

}

int main()
{
int num1,num2;
while (1)
{
printf("Please enter two positive integers to calculate:>");
scanf("%d %d", &num1, &num2);
//Determine if the number entered is a positive integer or not, and you can modify it slightly to be non-zero here
if (num1 > 0 && num2 > 0)
{
break;
}
else
{
}
}
//Common_divisor common multiple
//Common_multiple common divisor
int Common_divisor = function_Common_divisor(num1, num2);
int Common_multiple = function_Common_multiple(num1, num2, Common_divisor);
printf("The maximum common divisor is:%d\n The lowest common multiple is:%d", Common_divisor, Common_multiple);
return 0;
}```

Run result:

## 2. Solving EquationsThe root is determined by three functions:Roots greater than 0, equal to 0, and less than 0 and output results. Enter the values of a,b,c from the main function.

Analysis: The root-seeking formula of high school learning, using the relationship between_and 0 to determine whether there is a root.

```//Declare as a global variable so you don't have to write it one by one
float x1, x2, disc;
void Greater_than_zero(int a, int b,int c)
{
x1 = (-b + sqrt(disc)) / (2 * a);
x2 = (-b - sqrt(disc)) / (2 * a);
printf("\n▲=%d^2 - 4*%d*%d > 0\n\nx1 = %.2f\tx2 = %.2f", b, a, c, x1, x2);
}
void Equal_to_zero(int a, int b, int c)
{
x1 = x2 = (-b) / (2 * a);
printf("\n▲=%d^2 - 4*%d*%d = 0\n\nx1 = %.2f\tx2 = %.2f", b, a, c, x1, x2);
}
void Less_than_zero(int a, int b, int c)
{
printf("\n▲=%d^2 - 4*%d*%d < 0\n\n No Root", b, a, c);
}

int main()
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
printf("The expression is:%dx^2 + %dx + %d = 0\n", a, b, c);
disc = b * b - 4 * a * c;
if (disc > 0)
{
Greater_than_zero(a, b,c);
}
else if (disc == 0)
{
Equal_to_zero(a, b,c);
}
else
{
Less_than_zero(a, b, c);
}

return 0;
}```

Run result:

## 3. Write a function to determine a prime number, enter an integer in the main function, and output information about whether it is a prime number or not.

Parse: prime number: all but 1 and itself cannot be divided, so we can divide the input number by the square from the beginning to the input number. If it cannot be divided from beginning to end, it is considered a prime number.

```//Write a function to determine a prime number, in which the main function loses an integer and outputs information about whether it is a prime number or not.
void prime_check(int num)
{
int flag = 0;
if (num == 1 || num == 2)
{
printf("Is a prime number!\n");
}
else
{
for (int i = 2; i < sqrt(num)+1; i++)
{
if (num % i == 0)
{
printf("Not a prime number!\n");
flag = 1;
break;
}

}
if (flag == 0)
{
printf("Is a prime number!\n");
}

}

}
int main()
{
int num;
while (1)
{
printf("Please enter a value to detect:>");
scanf("%d", &num);
if (num > 0)
{
break;
}
else
{
}
}
prime_check(num);

return 0;
}
```

Run result:

## 4. Write a function that transposes a given two-dimensional integer array of 3X3, i.e. rows and columns.

Resolution: Transposition is actually a row-column exchange, and after transposing, you will find that the left diagonal is unchanged.

```void print(int* arr[ROW][COL])
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void reverse(int arr[ROW][COL])
{
int temp = 0;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < i; j++)
{
if (i != j)
{
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
printf("\n");
}

int main()
{
int arr[ROW][COL] = { 1,2,3,4,5,6,7,8,9 };
print(&arr);
reverse(&arr);
print(&arr);
return 0;
}```

Run result:

## 5. Write a function so that one of the input strings is stored in reverse order, and the input and output strings are in the main function.

Interpretation: This topic is very similar to the one in Chapter 6, except that it encapsulates him as a function. Here we can use the method of creating strings.

```//Store strings in reverse order
void reverse(char* s, int len)
{
int left = 0;
int right = len-1;
int temp = 0;
//This is actually just a circular decision
//A comma statement has a feature that precedes operations but only considers the last as a result
while(temp = s[left],s[left] = s[right],s[right] = temp,left<right)
{
left++;
right--;
}
}

int main()
{
char s[9999] = {0};
//gets are really much better than scanf, and getchar works here, but you have to write loops
gets(s);
int len = strlen(s);
reverse(&s,len);
printf("Post-inverted string:>%s",s);
return 0;
}```

Run result:

## 6. Write a function that connects two strings.

Interpretation: Let's just say it's an unfamiliar question. Chapter VI, 13 ) or two methods: rebuilding strings or pointers; Place the code directly!

plan A:

```void my_strcat(char*arr3, char* arr2, char* arr1, int len1, int len2)
{
for (int i = 0; i < len1; i++)
{
arr3[i] = arr1[i];
}
for (int i = 0; i < len2; i++)
{
arr3[len1 + i] = arr2[i];
}
}
int main()
{
char arr1[9999] = { 0 };
char arr2[9999] = { 0 };
char arr3[9999] = { 0 };
printf("Please enter the first string of characters:>");
gets(arr1);//scanf swallows spaces, get is recommended
int len1 = strlen(arr1);
gets(arr2);
int len2 = strlen(arr2);
my_strcat(&arr3, &arr2,&arr1,len1, len2);
printf("Stitched Characters:>%s", arr3);
return 0;
}```

Run result:

plan B:

```void my_strcat(char* arr1, char* arr2, char* p)
{
int i = 0;
for (; *arr1 != '\0';)
{
*p = *arr1;
arr1++;
p++;
}
for (; *arr2 != '\0';)
{
*p = *arr2;
arr2++;
p++;
}
*p = '\0';

}

int main()
{
char arr1[9999] = { 0 };
char arr2[9999] = { 0 };
char arr3[9999] = { 0 };
char* p = 0;
p = arr3;
printf("Please enter the first string of characters:>");
gets(arr1);
gets(arr2);
my_strcat(arr1, arr2, p);
printf("Stitched Characters:>%s", p);
return 0;
}
```

Run result:

## 7. Write a function that copies the vowel letters from one string to another and outputs them.

Resolution: We have done replication many times, and now we are in the hands. The difficulty lies in the vowel determination, vowel letters: a, e, i, o, u, A, E, I, O, U

```//Copies the vowel letters in a string to another string and outputs them.
void filter(char*s, char*c, int len)
{
int index = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == 'a' || s[i] == 'A'
|| s[i] == 'e' || s[i] == 'E'
|| s[i] == 'i' || s[i] == 'I'
|| s[i] == 'o' || s[i] == 'O'
|| s[i] == 'u' || s[i] == 'U')
{
c[index] = s[i];
index++;
}
}
}

int main()
{
char s[99999] = { 0 };
char c[99999] = { 0 };
gets(s);
int len = strlen(s) ;
filter(&s, &c, len);
printf("Filtered string:>%s", c);
return 0;
}```

Run result:

## 8. Write a function that inputs a 4-digit number, which requires the output of the four numeric characters, but with a space between each two digits. If the loser is 1990, the output should be "19 9 0".

Parse: Traverse the string, printing one space at a time, and do not print a space when traversing the last character.

```/*Write a function that inputs a 4-digit number and requires the output of these 4 numeric characters.
But there is a space between each two numbers. If the loser is 1990, the output should be "19 9 0".*/
void Non_breaking_space(char* num)
{
for (int i = 0; i < 4; ++i)
{
printf("%c", num[i]);
if (i < 3)
{
printf(" ");
}
}
}
int main()
{
//The array is given 5 here to prevent the array from crossing the bounds
char num[5] = { 0 };
gets(num);
Non_breaking_space(&num);
return 0;
}```

Run result:

## 9. Write a function that passes a string from an argument and counts the number of letters, numbers, spaces and other characters in the string. Type a string in the main function and output the above results.

Parse: This is also a topic that has been done. The main step is to enter the characters into the string and transfer them to the function to count the specific values of the characters in the function.

```/*Write a function that passes a string from an argument.
Count the number of letters, numbers, spaces, and other characters in this string.
Enter a string in the main function and output the above results.*/
void counter(char* s, int len)
{
int index = 0;
int capital = 0, minuscules = 0, numbe = 0, space = 0, other = 0;
while (index != len)
{
if (s[index] >= 'A' && s[index] <= 'Z')
{
capital++;
}
else if (s[index] >= 'a' && s[index] <= 'z')
{
minuscules++;
}
else if (s[index] >= '0' && s[index] <= '9')
{
numbe++;
}
else if (s[index] == ' ')
{
space++;
}
else
{
other++;
}
index++;
}
printf("Number of uppercase letters:%d\n", capital);
printf("Number of lowercase letters:%d\n", minuscules);
printf("Number of Numbers:%d\n", numbe);
printf("Number of spaces:%d\n", space);
printf("Number of other characters:%d\n", other);
}
int main()
{
char s[99999] = {0};
gets(s);
int len = strlen(s);
counter(&s,len);
return 0;
}```

Run result:

## 10. Write a function that outputs the longest word in a line of characters.

Parse: Each word is separated by spaces. What we need to do here is to detect the number of characters in each space and space. When a space is detected, set this to'\0', and calculate len. If len is the longest, transfer the word to a new character.

```//Write a function that outputs the longest word in a line of characters.
void finder(char*s,char*word)
{
int index = 0;
int max_len = 1;
int len = strlen(s);
//The best decision to add a letter to while
while (s[index] != '\0')
{
index++;
if (s[index] == ' '|| s[index] =='\0')
{
s[index] = '\0';
len = strlen(s);
if (len >= max_len)
{
max_len = len;
strcpy(word, s);
s += len + 1;

}
}

}
}

int main()
{
char s[99999] = {0};
char word[100] = { 0 };
gets(s);
finder(&s,&word);
printf("The longest word is:%s", word);
return 0;
}```

Run result:

## 11. Write a function that uses the "frothing" method to sort the 10 characters you enter in order from small to large.

Resolution: Bubble method is what we call bubble sorting, two-layer cycle, number of control sorting trips for outer control cycle, and number of order digits for inner control cycle.

```void bubble(char*s)
{
int len = strlen(s);
for (int i = 0; i < len; i++)
{
int flag = 0;
for (int j = 0; j < len - i-1; j++)
{
if (s[j] > s[j + 1] )
{
int temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}

}
int main()
{
char s[11] = { 0 };
gets(s);
bubble(&s);
printf("Sorted Characters:>%s", s);
return 0;
}```

Run result:

## 12. Use Newton's iteration method to find the root. The equation isThe values of coefficients a, b, C and D are 1, 2, 3, 4, respectively, and are the inputs of the main function. Find a real root of x near 1. After the root is found, it is output by the main function.

Parsing: The difficult point of this problem is the Newton iteration method. Understanding the Newton iteration method is easy to implement.

Newton's iteration formula:According to this formula, whenandWhen the absolute value of the difference equals 0, the solution converges! Of course, we generally assume that when the absolute value is less than 1 e-5, the solution is obtained.

```//Xn+1 = Xn - (f-f') && |Xn+1 - Xn|<1e-5
int a, b, c, d;
float x0, x1, f0, f1;
float Newton_Iteration()
{
x0 = 0;
x1 = 1;
while (fabsf(x1 - x0) > 1e-5)
{
x0 = x1;
f0 = (x0 * (x0 * (a * x0 + b) + c) + d);
f1 = (x0 * (3 * a * x0 + 2 * b) + c);
x1 = x0 - (f0 / f1);
}
return x1;
}
int main()
{

scanf("%d %d %d %d", &a, &b, &c, &d);
return 0;
}```

Run result:

## 13. Use the recursive method to find the value of the n-order Legendre polynomial. The recursive formula is

Parsing: The difficulty lies in understanding Legend polynomials and recursion. Looking at the formula, we can see that Pn-1 and Pn-2 need to be calculated when n>=1, where recursion is used.

```float operate(int x, int n)
{
if (n == 0)
{
return 1;
}
if (n == 1)
{
return x;
}
if (n > 1)
{
return (((2 * n - 1) * x - operate(x, n - 1) - (n - 1) * operate(x, n - 2)) / n);
}

}

int main()
{
int n = 0, x = 0;
scanf("%d %d", &x, &n);
return 0;
}```

Run result:

## 14. The results of 5 courses of 10 students were lost. The following functions were implemented with functions:

(1) Calculate the average score of each student;
(2) Calculate the average score of each course;
(3) Find out the students and courses corresponding to the highest score of all 50 scores;
(4) Calculating the mean score variance:

Where x; Average score for a student.

Resolution: It looks complicated and complicated, but every function is not difficult, it's nauseous. The solution is to create a two-dimensional array, followed by calculating the row mean, column mean, finding the maximum value, and calculating the variance of the row mean.

```/*The results of 5 courses for 10 students were lost. The following functions were implemented with functions:
①Calculate the average score of each student;
②Calculate the average score for each course;
③Find out which students and courses correspond to the highest score of all 50 scores;
④Calculate mean score variance:
Where, x; Average score for a student.*/
#define ROW 10
#define COL 5
float stu[ROW] = { 0 };
//(1) Calculate the average score of each student;
void ave_stu_num(int arr[ROW][COL])
{
int i, j;
float s = 0;
printf("Average student score:>");
for (i = 0; i < ROW; i++)
{
s = 0;
for (j = 0; j < COL; j++)
{
s = s + arr[i][j];
}
stu[i] = s / 5;
printf("%.2f  ",s/5);
}
printf("\n");
}

//(2) Calculate the average score of each course;
void ave_cla_num(int arr[ROW][COL])
{
int i, j;
float s = 0;
printf("Average score per course:>");
for (i = 0; i < COL; i++)
{
s = 0;
for (j = 0; j < ROW; j++)
{
s = s + arr[j][i];
}
printf("%.2f  ", s / 10);
}
printf("\n");
}

//(3) Find out the students and courses corresponding to the highest score of all 50 scores;
void max_stu_num(int arr[ROW][COL])
{
int i, j;
int max = 999;
int index, ondex;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
if(max>= arr[i][j])
max  = arr[i][j];
index = i;
ondex = j;
}
}
printf("No.%d Classmate's Class%d Top points in the course:%d\t", index + 1, ondex + 1, arr[index][ondex]);
}
//(4) Calculating the mean score variance
void arrange(int arr[ROW][COL])
{
int i;
float sum = 0.0, sumx = 0.0;
for (i = 0; i < ROW; i++)
{
sum += stu[i] * stu[i];
sumx += stu[i];
}
printf("Variance:%.2f  ", sum / 10 - (sumx / 10) * (sumx / 10));
}

int main()
{
int i = 0;
int j = 0;
int  arr[ROW][COL] = { 0 };
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
scanf("%d", &arr[i][j]);
}
}
printf("Full name\\curriculum  Class1  Class2  Class3  Class4  Class5\n");
for ( i = 0; i < ROW; i++)
{
printf("No.%d         ",i+1);
for (j = 0; j < COL; j++)
{
printf("%d       ", arr[i][j]);
}
printf("\n");
}
ave_stu_num(arr);
ave_cla_num(arr);
max_stu_num(arr);
arrange(arr);

return 0;
}```

Run result:

## 15. Write several functions:

(1) Names and employee numbers of 10 employees of the losing party;
(2) Sort the number of employees from small to large, and the order of names will be adjusted accordingly;
(3) Require the loser to have an employee number, find out the employee's name by halving the search method, and output the employee's name from the main function.

Parsing: This is a complicated problem. The difficulty lies in how to make arrays and strings join together. There are two main ways:

1. Create two arrays, one record number and one record name, which are sorted simultaneously.

2. Build the structure and keep all the data in it.

```/*①Names and numbers of 10 workers and staff members of the transferee;
②Sort the number of employees from small to large, and the order of names will be adjusted accordingly.
③Ask the loser to have an employee number and find out the employee's name by halving the number.
The number of the employee to be found by the input from the main function, and the name of the employee is output.*/
#define N 10
//(1) Names and employee numbers of 10 employees of the losing party;
void input(char name[N][10],int num[])
{
printf("Please enter the worker's number and name:>\n");
for (int i = 0; i < N; i++)
{
printf("No.");
scanf("%d",&num[i]);
getchar();
gets(name[i]);
}
}
//(2) Sort the number of employees from small to large, and the order of names will be adjusted accordingly;
void bubble(char name[N][10], int num[])
{
char temp2[10] = { 0 };
int index = 0;
for (int j = 0; j < N ; j++)
{
for (int i = 0; i < N-1 ; i++)
{
if (num[i] > num[i+1])
{
int temp = num[i];
strcpy(temp2, name[i]);
num[i] = num[i + 1];
strcpy(name[i], name[i + 1]);
num[i + 1] = temp;
strcpy(name[i + 1], temp2);
}
}
}
printf("After sorting:>\n");
for (int i = 0; i < N; i++)
{
printf("No.%d %s\n", num[i], name[i]);
}
}

int main()
{
char name[N][10] = { 0 };
int num[N] = { 0 };
input(name,num);//(1) Names and employee numbers of 10 employees of the losing party;
bubble(name, num);//(2) Sort the number of employees from small to large, and the order of names will be adjusted accordingly;
/*Ask the loser to have an employee number and find out the employee's name by halving the number.
The number of the employee to be found by the input from the main function, and the name of the employee is output.*/
int n = 0;
int up = 0, down = N-1;
int mid = 0;
printf("Please enter the employee number you are looking for:>");
scanf("%d", &n);
while (up < down)
{
mid = (up + down) / 2;
if (n == num[mid])
{
printf("No.%d  %s\n", n, name[mid]);
return 0;
}
else if (n < num[mid])
{
down = mid - 1;
}
else
{
up = mid + 1;
}
}
printf("No such person!\n");
return 0;
}```

Run result:

(Don't know these names. You're not familiar with them)

## 16. Write a function that inputs a hexadecimal number and outputs the corresponding decimal number.

Interpretation: This topic mainly examines the use of ASCII, and also the understanding of binary transformation, where the cardinality of each bit is 16 and where is the power of 16-1.

```//Enter a hexadecimal number and output the corresponding decimal number.
void change(char hex[10],int len)
{
int ten[10] ={0};
float n = len - 1;
float s = 0;
for(int i = 0; hex[i] != '\0'; i++)
{
if (hex[i] >= '0' && hex[i] <= '9')
{
ten[i] = pow(16 , (n-i)) * (hex[i] - '0');
}
if (hex[i] >= 'a' && hex[i] <= 'f')
{
ten[i] = pow(16, (n - i)) * (hex[i] - 'a' + 10);
}
if (hex[i] >= 'A' && hex[i] <= 'F')
{
ten[i] = pow(16, (n - i)) * (hex[i] - 'A' + 10);
}
}
for (int j = 0; ten[j] != '\0'; j++)
{
s += ten[j];
}
printf("Converted 10#Is: >%f ", s);
}
int main()
{
char hex[10] = { 0 };
gets(hex);
int len = strlen(hex);
change(hex,len);
return 0;
}```

Run result:

## 17. Recursively convert an integer n to a string. For example, input 483, should output string "483". The number of digits of n is uncertain and can be an integer of any number of digits.

Interpretation: This topic focuses on ASCII and recursion, and what we need to do is remove one lowest bit for each recursion.

```void convert(int n)
{
int i = 0;
if ((i = n / 10) != 0)
{
convert(i);
}
putchar(n % 10 + '0');
}

int main()
{
int i = 0;
printf("Please enter a number to convert:>");
scanf("%d", &i);
printf("Converted string:>");
if (i < 0)
{
putchar('-');
i = -i;
}
convert(i);
return 0;
}```

Run result:

## 18. Give the year, month and day, and calculate the day to be the day of the year.

Resolution: This is a simple mathematical calculation problem. We just need to create an array of how many days in a month. Of course, we also need to decide if this year is a leap year or another one if it is a leap year.

```//Gives the year, month and day, and calculates the day that is the day of the year.
void sum_day(int month_day[], int year, int month, int day)
{
int sum = 0;
//Calculate to last month, because this month is passing
for (int i = 1; i < month; i++)
{
sum += month_day[i];
}
//Add up the days that passed this month
sum += day;
//Determine if this year is a leap year and if the month is greater than two, or add it one more day
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
if (month > 2)
{
sum += 1;
}
}
printf("%d/%d/%d yes%d Year%d day!",year,month,day,year,sum);
}
int main()
{
int month_day[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int year, month, day;
printf("Please enter the year, month and day(0000/00/00):>");
scanf("%d %d %d", &year, &month, &day);
sum_day(month_day,year, month, day);
return 0;
}```

Run result:

Topics: C Algorithm