# C programming fourth edition after class exercises - Tan Haoqiang

```#include<stdio.h>
#include <string.h>
#include <math.h>
/*2.4.1 There are two bottles A and B. put vinegar and soy sauce respectively, and ask to exchange them*/
void swapaandb(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
/*Input 10 numbers at a time, and output the largest number.*/
void printMax(){
int max,i;
int arr[10];
printf("Please enter 10 numbers:");
scanf("%d\n",&arr[0]);
max=arr[0];
for(i=1;i<10;i++){
scanf("%d\n",&arr[i]);
if(arr[i]>max){
max=arr[i];
}
}
printf("The maximum value is:%d",max);
}
/*(3)There are three numbers a, B, C. they are required to be output in order of safety size.*/
void printFromMax2Min(int a,int b,int c){
int arr[3]={a,b,c};
int i,j,t;
for(i=0;i<2;i++){
for(j=1;j<3-i;j++){
if(arr[j]<arr[j-1]){
t=arr[j];
arr[j]=arr[j-1];
arr[j-1]=t;
}
}
}
for(j=2;j>=0;j--){
printf("%d\n",arr[j]);
}

}
/*Find 1 + 2 + 3 + · + 100*/
int sum100(){
return (1+100)*100/2;
}
/*(5)Judge whether a number n can be divided by 3 and 5 at the same time. 0 can, 1 can't*/
int is5and3(int n){
if(n%3==0 && n%5==0){
return 0;
}
return 1;
}
/*Determine whether it is a prime number*/
int isss(int n){
int len=sqrt(n),i=2;
for(;i<=len;i++){
if(n%i==0){
return 0;
}
}
return 1;
}
/*Output the prime numbers between 100 and 200*/
void printSs(){
int i=100;
for(;i<=200;i++){
if(isss(i)) printf("%d,",i);
}
}
/*Find the greatest common divisor of two numbers m and n.*/
int getMaxmandn(int n,int m){
int min=n,i;
if(m<n){
min=m;
}
for(i=min;i>0;i--){
if(n%i==0 && m%i==0){
return i;
}
}
return -1;
}
/*(7)Find the root of equation ax2+bx+c. Consider respectively: ① there are two unequal real roots; ② there are two equal real roots.*/
void printGen(){
float a,b,c;
printf("Please enter three heels a b c\n");
scanf("%f,%f,%f",&a,&b,&c);
printf("%f,%f,%f\n",a,b,c);
float flag=pow(b,2)-4*a*c;
printf("1:%f",flag);
float f1=-b/(2*a);
printf("2:%f",f1);
float f2=sqrt(flag)/(2*a);
printf("3:%f",f2);
if(flag>(1e-6)){
printf("one:%f\n",f1+f2);
printf("two:%f\n",f1-f2);
}else if(flag<=(1e-6)){
printf("only one:%f one:%f\n",f1,f1);
}else{
printf("none!");
}
}
/*Output 1900 -- the year in 2000 is leap year, and the year meeting one of the following two conditions is leap year.
(1) Divisible by 4 but not by 100 (2) divisible by 100 and divisible by 400.*/
void printyear(){
int i=1900;
for(;i<=2000;i++){
if((i%4==0 && i%100!=0) || (i%400==0)){
printf("%d is ruinian",i);
}
}
}
/*To translate "China" into a code, the decoding rule is: replace the original letter with the fourth letter after the original letter
For example, the fourth letter after the letter "A" is "E." E "replaces" A ". Therefore, "China" should be translated as "Glmre".
Please make a program to assign the initial value of cl, c2, c3, c4 and c5 variables as, 'C', 'h', 'i', 'n', 'a', respectively,
After operation, c1, c2, c3, c4 and c5 are changed into 'G', 'l', 'm', 'r' and 'e' respectively and output. */
void decodeScript(char str[]){
int i;
int len=strlen(str);
for(i=0;i<len;i++){
str[i]=str[i]+4;
}
}
/*Let the radius of the circle r=1.5, the height of the cylinder h=3, and calculate the circumference, area, surface area, volume and volume of the circle.
scanf is used to input data and output calculation results. When outputting, text description is required and two digits after decimal point are taken. Please program. */
void cicle(){
float r,h,res;
printf("Please enter the radius and height of the circle\n");
scanf("%f,%f",&r,&h);
printf("The circumference of a circle is%.2f\n",2*3.14*r);
printf("Round area is%.2f\n",3.14*r*r);
printf("The surface area of the sphere is%.2f\n",4*3.14*r*r);
printf("The volume of the sphere is%.2f\n",4/3*3.14*r*r*r);
printf("Cylinder volume is%.2f\n",3.14*r*r*h);
}
void printChar(){
char c1,c2;
c1=getchar();
c2=getchar();
putchar(c1);
putchar(c2);
int c3,c4;
c3=getchar();
c4=getchar();
putchar(c3);
putchar(c4);
printf("c1=%d;c2=%d\n",c1,c2);
}
/*4.4 There are three integers a, b and c, which are input by keyboard and output the largest number.*/
void printMax(){
int a,b,c;
scanf("%d,%d,%d",&a,&b,&c);
int max=a;
if(b>max){
max=b;
}
if(c>max){
max=c;
}
printf("max:%d\n",max);
}
void printSqrt(){
float a;
scanf("%f",&a);
while(a>=1000){
printf("Please re-enter the number less than 1000:\n");
scanf("%f",&a);
}
printf("Square root:%.2f\n",sqrt(a));
}
/*Given a positive integer with no more than 5 digits, the following requirements are required: ① find out how many digits it is; ② print out each digit separately; ③ print out each digit in reverse order. For example, if the original number is 321, 123 should be output.*/
void printBit(){
int a,c=0,arr[5];
printf("Please enter a positive integer a:");
scanf("%d",&a);
while(a>0){
arr[c++]=a%10;
printf("Sequential output: No%d Bits are%d\n",c,arr[c-1]);
a=a/10;
}
printf("This is a%d digit\n",c);
for(;a<c;a++){
printf("%d",arr[a]);
}
}
/*4.10 The bonus paid by the enterprise is based on the profit commission. When the profit I is less than or equal to 100 thousand yuan, the bonus can be deducted by 10%; when the profit is more than 100 thousand yuan and less than 200 thousand yuan (100000<I ≤ 200000),
Among them, 100000 yuan is subject to 10% commission, and 7.5% for the part higher than 100000 yuan; 200000 < I ≤ 400000, 200000 yuan is still subject to the above method (the same below),
5% for the part higher than 200000 yuan; 3% for the part higher than 400000 < I ≤ 600000; 1.5% for the part higher than 600000 < I ≤ 1000000;
I>1000000 1% for the part exceeding 1 million yuan. Input the profit I of the current month from the keyboard to calculate the total amount of bonus to be paid.
Requirements: (1) program with if statement; (2) program with switch statement.
Solution: when calculating profit, pay special attention to different percentage of different profits. For example, the profit is 150000 yuan, of which 100000 yuan is subject to 10% commission, and 50000 yuan is subject to 7.5% commission. */
void printBones(){
float bone[6]={0.1,0.075,0.05,0.03,0.015,0.01};
float ben[5]={1,1,2,2,4};
int b,i=0,offset=100000;
float res=0;
scanf("%d",&b);
while(b>ben[i]*offset && i<5){
res+=bone[i]*ben[i]*offset;
b-=ben[i]*offset;
i++;
}
res+=bone[i]*b;
printf("Should be issued%.2f\n",res);
}
/*Input 4 integers and output them in order of large to small.*/
void print4NumByOrder(){
int arr[4];
int i,j,t;
printf("Please enter 4 numbers");
scanf("%d,%d,%d,%d",&arr[0],&arr[1],&arr[2],&arr[3]);
for(i=0;i<3;i++){
for(j=1;j<4-i;j++){
if(arr[j]<arr[j-1]){
t=arr[j];
arr[j]=arr[j-1];
arr[j-1]=t;
}
}
}
for(j=3;j>=0;j--){
printf("%d\n",arr[j]);
}
}
/*There are four circular towers with the centers of (2,2), (- 2,2), (2, - 2), (- 2, - 2) and the radius of 1. The height of the four towers is 10 m respectively.
There are no buildings outside the tower. Now enter the coordinates of any point to find the building height of that point (the height outside the tower is zero).*/
void printfH(){
int h=10,x,y;
printf("Please enter a coordinate");
scanf("%d,%d",&x,&y);
int l1=pow(x-2,2)+pow(y-2,2);
int l2=pow(x+2,2)+pow(y-2,2);
int l3=pow(x-2,2)+pow(y+2,2);
int l4=pow(x+2,2)+pow(y+2,2);
if(l1>1 &&l2>1 &&l3>1 &&l4>1)h=0;
printf("Height is:%d",h);

}
/*5.3 Enter two positive integers m and n to find the maximum common divisor and the minimum common multiple. */
void printMm(){
int a,b,i;
printf("Please enter two positive integers:");
scanf("%d,%d",&a,&b);
int min=a;
int max=b;
if(b<a){
max=a;
min=b;
}
/*Maximum Convention*/
for(i=min;i>0;i--){
if(a%i==0 && b%i==0){
printf("The maximum common divisor is%d",i);
break;
}
}
/*Minimum common multiple*/
for(i=max;i<=a*b;i++){
if(i%a==0 && i%b==0){
printf("The minimum common multiple is:%d",i);
break;
}
}
}
/*5.4 Input a line of characters and count the number of English letters, spaces, numbers and other characters.*/
void countNum(){
char a;
int w=0,s=0,n=0,o=0;
printf("Please enter a line of characters:");
scanf("%c",&a);
while(a!='\n'){
if((a>='A' && a<='Z') ||(a>='a' && a<='z') ){
w++;
}else if(a==' '){
s++;
}else if(a>='0' && a<='9'){
n++;
}else{
o++;
}
scanf("%c",&a);
}
printf("English letter%d,Blank space%d,number%d,Other characters%d",w,s,n,o);
}
/*5.5 Find Sn=a+aa+aaa + +aa... A a a (with N A's), where a is a number. For example: 2 + 22 + 222 + 2222 + 22222 (n=5), n is input by keyboard. */
void printSn(){
int n,i=2,c=1;
long t=i,sum=i;
scanf("%d",&n);
while(c<n){
i=i*10;
t+=i;
sum+=t;
c++;
}
printf("Sn=%d\n",sum);
}
/*5.6 Seek, (that is, seek 1! + 2! + 3! + 4! + 5! + +20! */
void printSNnN(){
int n,i;
long sum=0,t=1;
scanf("%d",&n);
for(i=1;i<=n;i++){
t=t*i;
sum+=t;
}
printf("Sn=%d",sum);
}
/*Find the square of 1 + 2.. + 100 + 1 + 2 square... + 50 + 1 + 1 / 2 + 1 / 3... + 1 / 10*/
void printfS3(){
int i;
float sum=0;
for(i=1;i<=100;i++){
sum+=i;
if(i<=10){
sum+=1/i;
}
if(i<=50){
sum+=pow(i,2);
}
}
printf("Sn=%.2f\n",sum);
}
/*Print out all the "narcissus number". The so-called "narcissus number" refers to a three digit number, and the sum of its digit cubes is equal to itself.
For example: 153 is a narcissus number, because 153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3. */
int isShuiXianHua(int i){
int t=i,sum=0;
while(t>0){
sum+=pow(t%10,3);
t=t/10;
}
if(sum==i){
return 1;
}
return 0;
}
void printShuixianhua(){
int i=100;
for(;i<1000;i++){
if(isShuiXianHua(i)){
printf("%d ",i);
}
}
}
/*If a number is exactly equal to the sum of its factors, it is called a "perfect number".
For example, the factor of 6 is 1, 2, 3, and 6 = 1 + 2 + 3, so 6 is "perfect".
Program to find all the completions within 1000 and output their factors in the following format: 6 its factors are 1, 2, 3*/
int isWanshu(int n,int *arr){
int c=1,i=2,sum=1;
arr[0]=1;
for(;i<n;i++){
if(n%i==0){
arr[c++]=i;
sum+=i;
}
}
arr[c]=-1;

if(sum==n){
return 1;
}
return 0;
}
void printWs(){
int i,arr[100],c=1;
for(i=1;i<1000;i++){
if(isWanshu(i,arr)){
printf("%5d its　factors　are　1",i);
c=1;
while(arr[c]!=-1){
printf(",%d",arr[c++]);
}
printf("\n");
}
}
}
void printSum20(){
int i=0,n;
float sum=0,fz=2,fm=1,t;
scanf("%d",&n);
for(i=0;i<n;i++){
sum+=(fz/fm);
t=fz+fm;
fm=fz;
fz=t;
}
printf("sum=%f\n",sum);
}
/*5.11 A ball falls freely from a height of 100 meters, returns to half of its original height after landing each time, and then falls again. How many meters does it pass in the 10th landing? How high is the 10th bounce?*/
void printMh(){
int i,n;
float sum=100,h=100;
scanf("%d",&n);
for(i=1;i<n;i++){
h=h/2;
sum+=h*2;
}
printf("The first%d Pass through%.2f rice",n,sum);
printf("The first%d Secondary rebound%.2f rice",n,h/2);
}
/*5.12 Monkeys eat peaches. The monkey picked several peaches on the first day, and ate half of them immediately. He was not addicted to them, and ate another one. The next morning, I ate half of the rest peaches and another one.
Every morning I ate the rest of the day before. When I wanted to eat again on the 10th morning, I saw only one peach left. How many peaches to pick on the first day.*/
void printHowMany(){
int i=1,sum=1;
for(;i<10;i++){
sum=(sum+1)*2;
}
printf("sum=%d\n",sum);
}
void printSqrt(){
float x0,x1,n;
scanf("%f",&n);
x1=n/2;
do{
x0=x1;
x1=(x0+n/x0)/2;
}while(fabs(x1-x0)>1e-5);
printf("Square root:%f",x1);

}
/*Newton iterative method is used to find the roots of the equation near 1.5. Newton iteration: https://www.matongxue.com/madocs/205.html*/
void printfGenByNd(){
float x=1.5,y;
do{
y=2*x*x*x-4*x*x+3*x-6;/*Derivative of function y 6*x*x-8*x+3 */
x=x-y/(6*x*x-8*x+3);/*The value of x when tangent y=0*/
}while(fabs(y)>1e-6);
printf("1.5 Nearby roots are:%.2f\n",x);

}
/*Using dichotomy to find the root of equation between (- 10, 10)
The basic idea of dichotomy is: any two points X1 and X2, judge whether there is a real root in the interval (x1,x2). If f(x1) is opposite to f(x2), then there is a real root.
Then take the midpoint X of (x1,x2), check whether f(x) and f(x2) are the same number, if they are different, it means that the real root is between (x,x2), if they are the same number,
In comparison (x1,x), this reduces the scope by half, and then calls recursively according to the above methods until the interval is quite small (until the root is found)!  */
void printGenBy2divid(){
float x1=-10,x2=10,y1,y2,x,y;
y1=2*x1*x1*x1-4*x1*x1+3*x1-6;
y2=2*x2*x2*x2-4*x2*x2+3*x2-6;
if(y1*y2>0){
printf("Rootless\n");
return ;
}
do{
x=(x1+x2)/2;
y=2*x*x*x-4*x*x+3*x-6;
if(y1*y<0){
x2=x;
}else if(y2*y<0){
x1=x;
}
}while(fabs(y)>1e-6);
printf("-10,10 The root between is:%f",x);
printf("y by:%f",y);
}
void printfxingx(){
int n,i=1,j;
printf("Please enter how many lines:");
scanf("%d",&n);
for(;i<=n;i++){
for(j=0;j<n-i;j++)printf(" ");
for(j=0;j<(i*2-1);j++)printf("*");
printf("\n");
}
for(i=n-1;i>0;i--){
for(j=0;j<n-i;j++)printf(" ");
for(j=0;j<(i*2-1);j++)printf("*");
printf("\n");
}
}
int isSuShu(int n){
int i=2;
for(;i<=sqrt(n);i++){
if(n%i==0){
return 0;
}
}
return 1;
}
void printfShushu(){
int i,j,n;
printf("Please enter the prime number within the number:");
scanf("%d",&n);
for(i=1;i<n;i++){
if(isSuShu(i)){
printf("%d,",i);
}

}
}
/*Selection sort*/
void sortSelect(int arr[],int len){
int i,j,min,index;
for(i=0;i<len-1;i++){
min=arr[i];
index=i;
for(j=i+1;j<len;j++){
if(arr[j]<min){
min=arr[j];
index=j;
}
}
arr[index]=arr[i];
arr[i]=min;
}
}
/*3,Find the sum of diagonal elements of a 3 × 3 integer matrix.*/
int get44Sum(int arr[4][4]){
int i,sum;
for(i=0;i<4;i++){
sum+=arr[i][i]+arr[i][3-i];
}
return sum;
}
void insert_arr(int arr[],int len,int n){
int res[len+1],index=0,i,flag=1;
for(i=0;i<len;i++){
if(flag && n<arr[i]){
res[index++]=n;
flag=0;
}
res[index++]=arr[i];
}
for(i=0;i<len+1;i++){
printf("%d,",res[i]);
}
}
/*5,Stores the values in an array in reverse order. For example, the original order is 8, 6, 5, 4, 1. Requirements changed to 1, 4, 5, 6, 8.*/
void reSort(int arr[],int len){
int s=0,e=len-1,t;
while(s<e){
t=arr[s];
arr[s]=arr[e];
arr[e]=t;
s++;e--;
}
}
void printYh(){
int n,i,j;
printf("Please enter how many lines:");
scanf("%d",&n);
int arr[n];
arr[0]=1;
for(i=0;i<n;i++){
for(j=i-1;j>0;j--){
arr[j]=arr[j]+arr[j-1];
}
arr[i]=1;
for(j=0;j<=i;j++){
printf("%3d",arr[j]);
}
printf("\n");
}
}
/*Output odd magic square matrix
1.The first element is placed in the middle column of the first row
2.The next element is stored in the previous row and the next column of the current element.
3.If there is already content in the previous row and the next column, the storage location of the next element is the next row of the current column.
When looking for the previous row, the next row, or the next column, you must think of this matrix as convoluted.
For example:
8 1 6
3 5 7
4 9 2
*/
void printMagic(){
int n,nowr,nowl,i,t;
printf("Please enter how many lines");
scanf("%d",&n);
if(n%2==0){
return ;
}
int arr[n][n];
/*Initialize to 0*/
for(nowr=0;nowr<n;nowr++){
for(nowl=0;nowl<n;nowl++){
arr[nowr][nowl]=0;
}
}
arr[0][n/2]=1;
nowr=0;
nowl=n/2;

for(i=2;i<=n*n;i++){
t=(nowr==0)? n-1:(nowr-1)%n;
if(arr[t][(nowl+1)%n]==0){/*Previous row, next column, nothing*/
nowr=t;
nowl=(nowl+1)%n;
arr[nowr][nowl]=i;
}else{
nowr=(nowr+1)%n;/*Next row of current column*/
arr[nowr][nowl]=i;
}
}
/*Printing*/
for(nowr=0;nowr<n;nowr++){
for(nowl=0;nowl<n;nowl++){
printf("%3d",arr[nowr][nowl]);
}
printf("\n");
}
}
/*8,Find the saddle point in a two-dimensional array, that is, the element in the position is the largest on the row and the smallest on the column. There may be no saddle point.*/
void findANpot(int arr[5][4]){
int i,j,max,min,res1[5],res2[4];
/*Maximum value of each line*/
for(i=0;i<5;i++){
max=0;
for(j=1;j<4;j++){
if(arr[i][j]>arr[i][max]){
max=j;
}
}
res1[i]=max;/*arr[i][max]The value at is the maximum value of the current line i*/
}
/*Minimum value of each column*/
for(i=0;i<4;i++){
min=0;
for(j=1;j<5;j++){
if(arr[j][i]<arr[min][i]){
min=j;
}
}
res2[i]=min;/*arr[min][i]Minimum value at*/
}
for(i=0;i<5;i++){
if(i==res2[res1[i]]){
printf("pot=%d\n",arr[i][res1[i]]);
return ;
};
}
}
/*There are 15 numbers stored in an array from large to small. Enter a number, and use the half search method to find out that the number is the value of the elements in the array
. If the number is not in the array, no such number is output.*/
void findIndexBydivd2n(int arr[],int len){
int s=0,e,m,n;
printf("Please enter the number to find:");
scanf("%d",&n);
e=len-1;
while(s<=e){
m=(s+e)/2;
if(n>arr[m]){
s=m+1;
}else if(n<arr[m]){
e=m-1;
}else{
printf("%d Is the number of%d Element\n",n,m);
return;
}
}
printf("No such number\n");
}
int main(){
int arr[]={1,4,6,9,13,16,19,28,40,100};
int len=sizeof(arr)/sizeof(*arr);
findIndexBydivd2n(arr,len);
/*int i;
for(i=0;i<len;i++){
printf("%d,",arr[i]);
};*/
printf("end\n");
return 0;
}
/*11,Output the following patterns:
*  *  *  *  *
*  *  *  *  *
*  *  *  *  *
*  *  *  *  *
*  *  *  *  *
*/
void printxingx(){
int i,j,n;
printf("Please enter how many lines:");
scanf("%d",&n);
for(i=0;i<n;i++){
for(j=0;j<i;j++)printf("  ");
for(j=0;j<n;j++)printf("* ");
printf("\n");
}
}
/*12,There is a message that has been translated into a code according to the following rules:
A →Z   a →z
B →Y   b →y
C →X   c →x
That is, the first letter becomes the 26th letter, the ith letter becomes the (26-i+1) letter, and non alphabetic characters remain unchanged. The program is required to translate the password back to the original, and output the password and the original.*/
void printMm(char arr[]){
int len=strlen(arr),i;
char res[len];
for(i=0;i<len;i++){
if(arr[i]>='a' && arr[i]<='z'){
res[i]='z'-arr[i]+'a';
}else if(arr[i]>='A' && arr[i]<='Z'){
res[i]='Z'-arr[i]+'A';
}else{
res[i]=arr[i];
}

}
printf("The original code is:%s\n",res);
}
/*13,Make a program to connect the two strings instead of using the strcat function.*/
void strCatFT(char *str1,char *str2){
int len1=strlen(str1);
int len2=strlen(str2);
int i=0;
for(;i<len2;i++){
str1[len1+i]=str2[i];
}
}
/*14,Make a program to compare the two strings s1 and s2. If s1 > s2, output a positive number; if s1=s2, output 0; if s1 < s2, output a negative number.
Do not use the strcpy function. Two strings are read in with the gets function. The absolute value of the output positive or negative number should be the difference between the ASCII codes corresponding to the two strings being compared.
For example, "A" should output A negative number because "A" < "C" compared to "C" and "- 2" because the ASCII difference between "A" and "C" is 2.
Similarly: "And" Aid "comparison. According to the comparison result of the second character," n "is 5 larger than" i ", so" 5 "should be output.*/
int compareStr(){
char s1[100],s2[100];
gets(s1);
gets(s2);
int len1=strlen(s1);
int len2=strlen(s2),min=len1,i;
if(len2<min){
min=len2;
}
for(i=0;i<min;i++){
if(s1[i]==s2[i]){
continue;
}
return s1[i]-s2[i];
}
return s1[i]-s2[i];
}
/*Write a program to copy all the characters in the character array s2 to the character array s1. Do not use the strcpy function. When copying, characters after '/ 0' are not copied.*/
void copyStrff(){
char s1[200],s2[200];
scanf("%s",s2);
int i;
do{
s1[i]=s2[i];
}while(s2[i++]!='\0');
printf("s1=%s\n",s1);
}
/*Find the root of the equation, use three functions to find the root when b2-4ac is greater than 0, equal to 0, and less than 0, and output the result. Input the values of a, B and c from the main function. */
void printGenOver0(float a,float b,float c){
float t=sqrt(pow(b,2)-4*a*c);
printf("x1=%.2f,x2=%.2f\n",(-b+t)/(2*a),(-b-t)/(2*a));
}
void printGenLow0(float a,float b,float c){
float ti=sqrt(4*a*c-pow(b,2))/(2*a);
float t=-b/(2*a);
printf("x1=%.2f+%.2fi,x2=%.2f+%.2fi\n",t,ti,t,ti);
}
void printGenEqual0(float a,float b,float c){
float t=sqrt(pow(b,2)-4*a*c);
printf("x1=%.2f,x2=%.2f\n",(-b+t)/(2*a),(-b-t)/(2*a));
}
/*7.4 Write a function to transpose a given two-dimensional array (4 × 4), that is, row column interchange. */
void reversArrs(int arr[4][4]){
int i,j,t;
for(i=0;i<3;i++){
for(j=i+1;j<4;j++){
t=arr[i][j];
arr[i][j]=arr[j][i];
arr[j][i]=t;
}
}
}
/*7.5 Write a function to store the input string in reverse order and input the output string in the main function.*/
void reverseStr(char arr[]){
int e=strlen(arr)-1;
int s=0;
char t;
while(s<e){
t=arr[s];
arr[s]=arr[e];
arr[e]=t;
e--;s++;
}
}
/*7.10 Write a function, input a line of characters, and output the longest word in this string. */
void printWordLong(){
char str[100];
printf("Please enter a line of string:");
scanf("%[^\n]",str);
int i=0,t[2],max=0,s=0;
int len=strlen(str);
for(;i<len;i++){
if(str[i]==' '){
if(i-s>max){
max=i-s;
t[0]=s;
t[1]=i;
}
s=i;
}
}
/*Last word*/
if(i-s>max){
max=i-s;
t[0]=s;
t[1]=i;
}
for(i=t[0];i<t[1];i++){
printf("%c",str[i]);
}
}
/*7.11 Write a function to use bubbling method to arrange the input characters from small to large.*/
void sort_bubble(char arr[]){
int len=strlen(arr),i=0,j=0;
char t;
for(i=0;i<len-1;i++){
for(j=1;j<len-i;j++){
if(arr[j-1]>arr[j]){
t=arr[j-1];
arr[j-1]=arr[j];
arr[j]=t;
}
}
}
}
/*Newton iteration is used to find the root. The equation is:, the coefficients a, b, c, d are input by the main function. Find a real root of X near 1. It is output by the main function.*/
float getGenByNiuDun(float a,float b,float c,float d){
float x,y;
x=1;
do{
y=a*pow(x,3)+b*pow(x,2)+c*x+d;
x=x-y/(3*a*x*x+2*b*x+c);

}while(y>1e-6);
return x;
}
/*7.13 The recursion formula of n-order Legendre polynomials is */
float lrddn(int n,float x){
if(n==0){
return 1;
}
if(n==1){
return x;
}
return ((2*n-1)*x-lrddn(n-1,x)-(n-1)*lrddn(n-2,x))/n;
}
/*7.13 Solving Legendre polynomials of order n by dynamic method*/
float lrddnd(int n,float x){
int i;
float pn1=x,pn2=1,t;
for(i=2;i<=n;i++){
t=((2*i-1)*x-pn1-(i-1)*pn2)/i;
pn2=pn1;
pn1=t;
}
return pn1;
}
```

#### 7.14 input the scores of 5 courses of 10 students, and use the function to find:

① Average score of each student;
② Average score of each course;
③ Find out the students and courses corresponding to the highest score;
④ Find the average score variance: δ = [SXi2]/n-(SXi/n)2, xi is the average score of a student

```//① Average score of each student;
void getStuAvg10(float arr[10][5],float stu[10]){
int i,j;
float sum;
for(i=0;i<10;i++){
sum=0;
for(j=0;j<5;j++){
sum+=arr[i][j];
}
stu[i]=sum/5;
}
}
/*②Average score of each course;*/
void getCourseAvg5(float arr[10][5],float course[5]){
int i,j;
float sum;
for(j=0;j<5;j++){
sum=0;
for(i=0;i<10;i++){
sum+=arr[i][j];
}
course[j]=sum/10;
}
}
/*③Find out the students and courses corresponding to the highest score of all 50 scores;*/
void getCoursMax(float arr[10][5]){
int i,j,cno,sno;
float maxPoint=0;

for(i=0;i<10;i++){
for(j=0;j<5;j++){
if(arr[i][j]>maxPoint){
maxPoint=arr[i][j];
cno=j;
sno=i;
}
}
}
printf("%d Student%d The course is the highest score%.2f\n",sno,cno,maxPoint);
}
/*④Find the average score variance: δ = [SXi^2]/n-(SXi/n)^2, xi is the average score of a student */
float getFangcha(float arr[10][5]){
float stu[10],sum1=0,sum2=0;
getStuAvg10(arr,stu);
int i;
for(i=0;i<10;i++){
sum1+=stu[i];
sum2+=stu[i]*stu[i];
}
return sum2/10-pow((sum1/10),2);
}
int main(){
float arr[10][5]={{10,10 ,10,10 ,10},
{21,21 ,23,23 ,26},
{31,34 ,36,34 ,31},
{51,55 ,50,50 ,58},
{65,61 ,67,68 ,64},
{70,70 ,70,70 ,70},
{81,81 ,83,83 ,86},
{91,94 ,96,94 ,91},
{41,45 ,40,40 ,48},
{65,61 ,67,68 ,64}};
float stu[10];
float course[5];
getStuAvg10(arr,stu);
getCourseAvg5(arr,course);
getCoursMax(arr);
int i;
for(i=0;i<10;i++){
printf("%.2f,",stu[i]);
}
printf("\n The average score of no courses is:");
for(i=0;i<5;i++){
printf("%.2f,",course[i]);
}
printf("\n Variance is:%.2f\n",getFangcha(arr));
printf("end\n");
return 0;
}

```

#### 7.15 write several functions:

① Input the names and employee numbers of 10 employees;
② According to the order of employee number from small to large, the order of name will be adjusted accordingly;
③ It is required to input an employee number, find out the name of the employee by half method, input the employee number to be searched from the main function, and output the name of the employee.

```/* structural morphology*/
typedef struct
{
int eno;
char name[20];
} Emp;
/*②According to the order of employee number from small to large, the order of name will be adjusted accordingly;*/
void sortByEno(Emp arr[10]){
int i,j;
Emp t;
/*Insertion sort*/
for(i=0;i<9;i++){
for(j=i+1;j>0;j--){
if(arr[j-1].eno>arr[j].eno){
t=arr[j-1];
arr[j-1]=arr[j];
arr[j]=t;
}else{
break;
}
}
}
}
/*③It is required to input an employee number, find out the name of the employee by half method, input the employee number to be searched from the main function, and output the name of the employee.*/
void getNameByNum(int eno,Emp arr[10],char res[]){
int i=0,j=9,m;
while(i<=j){
m=(i+j)/2;
if(arr[m].eno<eno){
i=m+1;
}else if(arr[m].eno>eno){
j=m-1;
}else{
strcpy(res,arr[m].name);
break;
}
}
}
int main(){
Emp arr[10];
int i;
for(i=0;i<10;i++){
Emp e;
e.eno=1100-i;
sprintf(e.name,"staff_%d",i);
arr[i]=e;
}
sortByEno(arr);
for(i=0;i<10;i++){
printf("number:%d,Full name:%s\n",arr[i].eno,arr[i].name);
}
char name[20];
getNameByNum(1094,arr,name);
printf("1094name=%s\n",name);
printf("end\n");
return 0;
}
```

#### 7.16 write a function, input a hexadecimal number, and output the corresponding decimal number. (various base conversion)

```/*7.16 Write a function, input a hexadecimal number, output the corresponding decimal number.*/
int hexToDec(char arr[]){
int i,len,c,res=0;
len=strlen(arr)-1;
for(i=len;i>=0;i--){
c=arr[i];
if(c>'9'){
c=10+c-'A';
}else{
c=c-'0';
}
res+=c*pow(16,len-i);
}
return res;
}
void DecToHex(int n){
char arr[n];
int t,i=0;
while(n>0){
t=n%16;
if(t>9){
arr[i]='A'+t%10;
}else{
arr[i]='0'+t;
}
i++;
n=n/16;
}
i--;
for(;i>=0;i--){
printf("%c",arr[i]);
}
}
int main(){
char arr[100];
int t;
scanf("%[^\n]",arr);
t=hexToDec(arr);
printf("%s The decimal of is%d\n16 Base is:",arr,t);
DecToHex(t);
printf("end\n");
return 0;
}
/*Binary to decimal*/
int binary2Decimal(long n){
int res=0,i=0,oz=0;
while(n>0){
oz=n%10;
res=res+oz*pow(2,i++);
n=n/10;
printf("n by%d\n",n);
}
return res;
}
/*Decimal to binary*/
long long decimal2Bin(int n){
int res=0,i=1,oz=0;
while(n>0){
oz=n%2;
res+=oz*pow(10,i);
i++;
n=n/2;
}
return res;
}
/*Octal to decimal*/
int octal2decimal(long long n){
int res=0,i=0,oz=0;
while(n>0){
oz=n%10;
res+=oz*pow(8,i);
i++;
n=n/10;
}
return res;
}
/*Decimal to octal*/
long long decimal2octal(int n){
int res=0,i=1,oz=0;
while(n>0){
oz=n%8;
res+=pow(10,i)*oz;
n=n/8;
i++;
}
return res;
}
/*Octal to binary*/
long long octal2bin(long long n){
int res=0,i=0,oz=0;
/*Eight turn ten*/
while(n>0){
oz=n%10;
res+=oz*pow(8,i);
n=n/10;
i++;
}
n=res;
res=0,i=1,oz=0;
/*Ten turn two*/
while(n>0){
oz=n%2;
res+=oz*pow(10,i);
n=n/2;
i++;
}
return res;
}
/*Binary to octal*/
long long bin2octal(long long n){
int res=0,i=0,oz=0;
/*Two turn ten*/
while(n>0){
oz=n%10;
res+=oz*pow(2,i);
i++;
n=n/10;
}
n=res;
res=0,i=1,oz=0;
/*Ten turn eight*/
while(n>0){
oz=n%8;
res+=oz*pow(10,i);
i++;
n=n/8;
}
return res;
}
```

#### 7.17 recursively convert an integer n to a string. For example, if you enter 486, the string "486" should be output. The number of digits of n is uncertain. It can be an integer of any number of digits.

```/**/
int i=0;
void numToStr(unsigned long n,char arr[]){
if(n==0){
return ;
}
numToStr(n/10,arr);
arr[i++]=n%10+'0';
}
int main(){
unsigned long t;
char arr[100];
printf("Please enter a number:");
scanf("%d",&t);
numToStr(t,arr);
arr[i]='\0';
printf("%s",arr);
printf("end\n");
return 0;
}
```

#### 7.18 give the year, month and day, and calculate the day as the day of the year.

```/*Determine if it is leap year 1 yes*/
int isRunyear(int i){
if((i%4==0 && i%100!=0) || (i%400==0)) return 1;
return 0;
}
/*7.18 Give the year, month and day, and calculate the day as the day of the year. */
int getHowMany(int y,int m,int d){
int arr[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(isRunyear(y)){
arr[1]=29;
}
int i=0,sum;
for(;i<m-1;i++){
sum+=arr[i];
}
sum+=d;
return sum;
}
int main(){
int y, m, d;
scanf("%d",&y);
scanf("%d",&m);
scanf("%d",&d);
printf("\n The first%d day\n",getHowMany(y,m,d));
printf("end\n");
return 0;
}
```

#### 8.1 input three integers and output them in the order of small to large. (Chapter 8 is all realized by pointer)

```/*10.1 Input three integers and output them in order of small to large. (bubbling Implementation)*/
void printFromMtoM(int *a,int *b,int *c){
int t;
if(*b<*a){
t=*a;*a=*b;*b=t;
}
if(*c<*b){
t=*c;*c=*b;*b=t;
}
if(*b<*a){
t=*a;*a=*b;*b=t;
}
printf("%d<%d<%d",*a,*b,*c);
}

int main(){
int a,b,c,*y, *m, *d;
printf("Please enter three numbers:");
scanf("%d,%d,%d",&a,&b,&c);
y=&a;
m=&b;
d=&c;
printFromMtoM(y,m,d);
printf("end\n");
return 0;
}
```

#### 8.2 input three strings and output them in order of small to large

```/**/
void printStrFromMtoM(char *a,char *b,char *c){
char *t;
if(strcmp(a,b)>0){
t=a;a=b;b=t;
}
if(strcmp(b,c)>0){
t=c;c=b;b=t;
}
if(strcmp(a,b)>0){
t=a;a=b;b=t;
}
printf("%s<%s<%s\n",a,b,c);
}
int main(){
char a[20],b[20],c[20];
printf("Please enter three strings:");
scanf("%s%s%s",a,b,c);
printStrFromMtoM(a,b,c);
printf("end\n");
return 0;
}

```

#### 8.3 input 10 integers, and exchange the minimum number with the first number, and the maximum number with the last number. Write three functions, ① input 10 numbers, ② process, ③ output 10 numbers.

```/**/
void changeArr(int *arr,int len){
int i=1,max=0,min=0;
if(len <=0){
return ;
}
for(;i<len;i++){
if(arr[i]>arr[max]){
max=i;
}else if(arr[i]<arr[min]){
min=i;
}
}
i=arr[max];
arr[max]=arr[len-1];
arr[len-1]=i;
i=arr[min];
arr[min]=arr[0];
arr[0]=i;

}
void changeArr(int *arr,int len){
if(len <=0){
return ;
}
int i=1,*max,*min;
max=arr,min=arr;
for(;i<len;i++){
if(arr[i]>*(max)){
max=arr+i;
}else if(arr[i]<*(min)){
min=arr+i;
}
}
i=*(max);
*(max)=*(arr+len-1);
*(arr+len-1)=i;
i=*(min);
*(min)=*(arr);
*(arr)=i;
}
int main(){
int arr[]={5,8,1,2,4,3,6,9,0,10,7};

int len=sizeof(arr)/sizeof(*arr);
printf("len=%d\n",len);
changeArr(arr,len);
int i;
for(i=0;i<len;i++){
printf("%d,",arr[i]);
};
printf("end\n");
return 0;
}

```

#### 8.4 there are n integers, so that the front numbers move backward m positions, and the last m numbers become the front m numbers

```/*Input n numbers and output adjusted n numbers in the main function.*/
void  changeArrIndex(int *arr,int n,int m){
int i=0,res[n];
for(;i<n;i++){
*(res+(i+m)%n)=*(arr+i);
}
for(i=0;i<n;i++){
*(arr+i)=*(res+i);
}
}
int main(){
int arr[]={5,8,1,2,4,3,6,9,0,10,7};

int len=sizeof(arr)/sizeof(*arr);
printf("len=%d\n",len);
changeArrIndex(arr,len,1);
int i;
for(i=0;i<len;i++){
printf("%d,",arr[i]);
};
printf("end\n");
return 0;
}

```

#### 8.5 there are n people in a circle, and the number is arranged in sequence. Report from the first person, from the first to the third. Anyone who reports to the third exits the circle and asks which number is left.

```/*josephus problem
*/
int getLast(int n){
int arr[n],i=0,c=0,res,l=n;
while(l>1){
if(arr[i]!=-1){
if(c==2){
arr[i]=-1;
l--;
}else{
res=i;
}
c=(c+1)%3;

}
i=(i+1)%n;
}
return res+1;

}
int main(){
printf("last=%d\n",getLast(10));
printf("end\n");
return 0;
}

```

#### 8.7 has a string of n characters. Write a function to copy all characters in this string from the m-th character to another string.

```/**/
void getCopyFromm(char *from,char *to,int m){
int len=strlen(from),i;
for(i=m;i<len;i++){
to[i-m]=from[i];
}
to[i-m]='\0';
}
int main(){
char *from="hello wojdh!",to[50];
getCopyFromm(from,to,5);
printf("to=%s\n",to);
printf("end\n");
return 0;
}

```

#### 8.10 put the largest element in a 5 * 5 matrix in the center, and put the four corners in the four smallest elements (from left to right, from top to bottom, from small to large), write a function to implement, and call with the main function

```/*10.10*/
void changeArrs(int arr[5][5]){
int res[5],i,j,k,l=0,t,temp[25];

for(i=0;i<5;i++){
for(j=0;j<5;j++){
temp[l++]=arr[i][j];
}
}
/*Bubble sort*/
for(i=0;i<25;i++){
for(j=1;j<25-i;j++){
if(temp[j]<temp[j-1]){
t=temp[j];
temp[j]=temp[j-1];
temp[j-1]=t;
}
}
}
res[4]=temp[24];
printf("res=%d\n",res[4]);
for(i=0;i<4;i++)res[i]=temp[i];

/*Store from left to right and from top to bottom*/
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if(arr[i][j]==res[0]){
t=arr[0][0];
arr[0][0]=res[0];
arr[i][j]=t;
res[0]=-1;
i=0,j=0;
}else if(arr[i][j]==res[1]){
t=arr[0][4];
arr[0][4]=res[1];
arr[i][j]=t;
res[1]=-1;
i=0,j=0;
}else if(arr[i][j]==res[2]){
t=arr[4][4];
arr[4][4]=res[2];
arr[i][j]=t;
res[2]=-1;
i=0,j=0;
}else if(arr[i][j]==res[3]){
t=arr[4][0];
arr[4][0]=res[3];
arr[i][j]=t;
res[3]=-1;
i=0,j=0;
}else if(arr[i][j]==res[4]){
t=arr[2][2];
arr[2][2]=res[4];
arr[i][j]=t;
res[4]=-1;
i=0,j=0;
}
}
}
}
int main(){
int array[5][5] ={{5,4,0,15,65},
{6,7,9,14,16},
{98,75,66,47,32},
{10,53,1,13,19},
{120,99,35,39,28}};
changeArrs(array);
int i,j;
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
printf("end\n");
return 0;
}
```

#### 8.11 enter 12 equal length strings in the main function. Sort them with another function. Then output the 12 sorted strings in the main function.

```/**/
void sortArr(char arr[12][10]){
int i,j;
char t[10];
for(i=0;i<11;i++)
{
for(j=0;j<12-i;j++){
if(strcmp(arr[j],arr[j-1])<0){
strcpy(t,arr[j]);
strcpy(arr[j],arr[j-1]);
strcpy(arr[j-1],t);
}
}
}
}
int main(){
char str[12][10] = {"January","February","March","April",
"May","June","July","August","September","October",
"November","December"};
sortArr(str);
int i,j;
for(i=0;i<12;i++){
printf("%s\n ",str[i]);

}
printf("end\n");
return 0;
}

```

#### 8.12 handle the previous problem with pointer array, the string is not equal in length.

```/**/
void sortArr(char *arr[12]){
int i,j;
char *t;//test
for(i=0;i<11;i++)
{
for(j=1;j<12-i;j++){
if(strcmp(arr[j],arr[j-1])<0){
t=arr[j];
arr[j]=arr[j-1];
arr[j-1]=t;
}
}
}
}
int main(){
char *str[12],*temp[12]={"January","February","March","April",
"May","June","July","August","September","October",
"November","December"};
int i,j;
for (i=0; i<12; i++){
str[i]=(char *)malloc(10*sizeof(char));      //Allocate memory dynamic space for pointer array
str[i]=temp[i];
}
sortArr(str);
for(i=0;i<12;i++){
printf("%s\n ",str[i]);

}
printf("end\n");
return 0;
}
```

#### 8.13 use the rectangular method to find the general function of the definite integral, and find 1.sinx, 2.cosx,3.e^x respectively

```/**/
double getJifen(double top,double bottom,int func){
double (*fun)(double);//Define function pointer
switch (func){
case 1:
fun=sin;
break;
case 2:
fun=cos;
break;
case 3:
fun=exp;
break;
}
double sum=0;
int i,offset=200000;
double o=(top-bottom)/offset;
double x=bottom;
for(i=1;i<=offset;i++){
x=x+o;
sum+=(*fun)(x)*o;
}
return sum;
}
int main(){
double pi = 3.141592;
printf("%f\n ",getJifen(pi,0,1));//2.000
printf("end\n");
return 0;
}
```

#### 8.14 arrange N numbers in reverse order according to the order of input, and use function to realize

```/*8.14 N numbers are arranged in reverse order according to the order of input, which is realized by function*/
double backWardRank(int *arr,int n){
int i,t;
n--;
for(i=0;i<n;i++,n--){
t=*(arr+i);
*(arr+i)=*(arr+n);
*(arr+n)=t;
}
}
int main(){
int arr[]={5,8,1,2,4,3,6,9,0,10,7};

int len=sizeof(arr)/sizeof(*arr);
backWardRank(arr,len);
int i;
for(i=0;i<len;i++){
printf("%d,",arr[i]);
};
printf("end\n");
return 0;
}
```

#### Enter a string containing numeric and non numeric characters. For example, A123X456Y7A, 302ATB567BC, an integer composed of all consecutive numbers (excluding non numeric characters) in the print string.

```/**/
int getNums(char *str,long long res[]){
char *t=str,nums[11];
int i,j=0;
long long num;
while(*t!='\0'){
i=0;
while(*t>='0' && *t<='9'){
nums[i++]=*t;
t++;
}
nums[i]='\0';
num = atol(nums);
if(num>0){//0 is not considered here
res[j++]=num;
}
t++;
}
return j;
}
int main(){
char *arr={"A123X456Y7A，302ATB567BC"};
long long res[100];
;
int i;
int len=getNums(arr,res);
for(i=0;i<len;i++){
printf("%d,",res[i]);
};
printf("end\n");
return 0;
}

```

#### Implementation of strcpy

```/*String copy: value copy*/
void stringcopy1(char *to,char *from){
int i;
for(;from[i]!='\0';i++){
to[i]=from[i];
}
to[i]='\0';
}
/*String copy: value copy*/
void stringcopy2(char *to,char *from){
int i;
for(;from[i]!='\0';i++){
*(to+i)=*(from+i);
}
to[i]='\0';
}
int main(){
char p[]="A123X456Y7A，302ATB567BC";
char *arr;
arr=p;
char res[100];
stringcopy1(res,arr);
printf("%s\n",res);
*(arr)='b';
stringcopy2(res,arr);
printf("%s\n",res);
printf("end\n");
return 0;
}

```

#### Implementation of strcmp

```/*17,Make a program to compare the two strings s1 and s2. If s1 > s2, output a positive number; if s1=s2, output 0; if s1 < s2, output a negative number.
Do not use the strcpy function. Two strings are read in with the gets function. The absolute value of the output positive or negative number should be the difference between the ASCII codes corresponding to the two strings being compared.
For example, "A" should output A negative number because "A" < "C" compared to "C" and "- 2" because the ASCII difference between "A" and "C" is 2.
Similarly: "And" Aid "comparison. According to the comparison result of the second character," n "is 5 larger than" i ", so" 5 "should be output.*/
int strcmp1(char *s1,char *s2){
int len1=strlen(s1);
int len2=strlen(s2);
int min=len1,i;
if(len1>len2){
min=len2;
}
for(i=0;i<min;i++){
if(s1[i]!=s2[i]){
break;
}
}
return s1[i]-s2[i];
}
int main(){
char *s1="A123X";
char *s2="A123X";

printf("%d\n",strcmp1(s1,s2));

printf("end\n");
return 0;
}

```

#### 8.18 write a program, input the month number, and output the English name of the month number. For example, input 8 and test output "August" require pointer array processing

```/*8.18 Write a program, input the month number, output the English name of the month number. For example, input 8 and test output "August" require pointer array processing.*/
void printfEn(int num){
char *str[12] = {"January","February","March","April",
"May","June","July","August","September","October",
"November","December"};
printf("%s\n",*(str+num-1));

}
int main(){
printfEn(12);
printf("end\n");
return 0;
}
```

#### Exercise 8.19 (1) write a function new to open up a continuous storage space for n characters. This function should return a pointer (address), pointing to the space at the beginning of the string. New (n) means to allocate n bytes of memory space (2) to release free;

```/*Exercise 8.19 (1) write a function new to open up continuous storage space for n characters. This function should return a pointer (address),
Space pointing to the beginning of the string. new (n) means to allocate n bytes of memory space*/
char *news(int n){
char *p;
p=(char *)malloc(n*sizeof(char));
return p;
}
int main(){
char *t=news(12);
char s='a';
for(;s<'l';s++){
*t=s;
t++;
}
*t='\0';
printf("k=%c\n",*(t-1));
printf("str=%s\n",t-11);
printf("str=%s\n",t-11);
printf("end\n");
return 0;
}

```

#### Sort 5 strings by pointer and output

```/*Sort 5 strings by pointer and output*/
void sortArr(char **str){
int len=12;
char *t,**p1,**p2;

for(p1=str;p1<str+len-1;p1++)//Bubbling
{
for(p2=str+1;p2<str+len;p2++){
if(strcmp(*(p2),*(p2-1))<0){
t=*p2;
*p2=*(p2-1);
*(p2-1)=t;
}
}
}
}
int main(){
int i;
char str[12][10] = {"January","February","March","April",
"May","June","July","August","September","October",
"November","December"};
char *str1[12],**s;
for(i=0;i<12;i++){
str1[i]=str[i];
};
s=str1;
sortArr(s);
for(i=0;i<12;i++){
printf("%s,",*(s+i));
};
printf("end\n");
return 0;
}
```

#### 8.21 sort and output n integers by pointer. Requires sorting to be written as a single function. N and integers are entered in the main function. Finally, output in the main function.

```/*8.21 Sort and output n integers by pointer. Requires sorting to be written as a single function. N and
Integers are entered in the main function. Finally, output in the main function.
*/
void sortArrByPoint(int *arr,int len){
int t,*p1,*p2;

for(p1=arr;p1<arr+len-1;p1++)//Bubbling
{
for(p2=arr+1;p2<arr+len;p2++){
if(*p2<*(p2-1)){
t=*p2;
*p2=*(p2-1);
*(p2-1)=t;
}
}
}
}
int main(){
int arr[]={5,8,1,2,4,3,6,9,0,10,7};

int len=sizeof(arr)/sizeof(*arr);
sortArrByPoint(arr,len);
int i;
for(i=0;i<len;i++){
printf("%d,",arr[i]);
};
printf("end\n");
return 0;
}

```

#### 9.1 define a structure variable (including year, month and day). Calculate the day in this year, pay attention to leap year.

```/*9．1 Define a structure variable (including year, month, day). Calculate the day in this year, pay attention to leap year.*/
typedef struct{
int y;
int m;
int d;
}Data;
/*Determine if it is leap year 1 yes*/
int isRunyear(int i){
if((i%4==0 && i%100!=0) || (i%400==0)) return 1;
return 0;
}
/*Calculate the day in this year, pay attention to leap year. */
int getHowMany(Data d){
int arr[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(isRunyear(d.y)){
arr[1]=29;
}
int i=0,sum;
for(;i<d.m-1;i++){
sum+=arr[i];
}
sum+=d.d;
return sum;
}
int main(){
Data d;
d.y=2020;
d.m=12;
d.d=31;
printf("The first%d day\n",getHowMany(d));
printf("end\n");
return 0;
}
```

#### Write a function print, print an array of students' scores, in which there are 5 students' data records

```/*9.3 Write a function print to print an array of students' scores, in which there are 5 students' data records,
Each record includes num, name and sore[3], which are input by main function and output by print function.
Write a function input to input the data records of 5 students.*/
typedef struct{
int num;
char name[20];
int score[3];
}stu;
void printfStu(stu *s,int len){
int i;
stu *p,t;
for(p=s;p<s+len;p++){
t=*p;
printf("Student ID:%d,Full name:%s,",t.num,t.name);
for(i=0;i<3;i++){
printf("The first%d Door score is%d",i+1,t.score[i]);
}
printf("\n");
}
}
void input1(stu *s,int len){
int i,j;
for(i=0;i<len;i++){
s[i].num=1000+i;
sprintf(s[i].name,"%s_0%d","Student",i);//Student _0i
for(j=0;j<3;j++){
s[i].score[j]=rand()%50+50;
}
}
}
int main(){
stu ss[10];
input1(ss,10);
printfStu(ss,10);
printf("end\n");
return 0;
}
```

#### There are 10 students, and the data of each student includes student number, name and scores of 3 courses

```/*9.5 There are 10 students, each student's data includes student number, name, and scores of 3 courses. It is required to print out the total average scores of 3 courses, as well as the data of the highest score students (including student number, name, and scores of 3 courses)*/
double *getAvgScore(stu *s,int len){
double *p;
p=(double *)malloc(3*sizeof(double));
int i,j;
for(i=0;i<len;i++){
for(j=0;j<3;j++){
p[j]+=s[i].score[j];
}
}
for(j=0;j<3;j++){
p[j]=p[j]/len;
}
return p;
}
int main(){
stu ss[10];
input1(ss,10);
double *p=getAvgScore(ss,10);
int j;
for(j=0;j<3;j++){
printf("%f\n",p[j]);
}
printf("end\n");
return 0;
}
```

#### 9.7-9.9 addition, deletion and modification of linked list

```/*9.7-9.9 Addition, deletion and modification of linked list*/
struct Stu{//structural morphology
int no;
float score;
struct Stu *next;
}stu;
struct Stu * creatStu(int n){//Create a linked list with n nodes
while(n>0){
t=malloc(sizeof(stu));
t->no=1100-n;
t->score=rand()%50+50;
last->next=t;
last=t;
n--;
}
}
void printfStu(struct Stu *s){//Print stu
struct Stu *t;
t=s->next;
while(t!=NULL){
printf("Student ID%d,Fraction%.2f\n",t->no,t->score);
t=t->next;
};
}
struct Stu *t;
t=s;
while(t->next!=NULL){
t=t->next;
};
struct Stu *news=malloc(sizeof(stu));
news->no=t->no+1;
news->score=rand()%50+50;
t->next=news;
}
void delStu(struct Stu *s,struct Stu *del){//Delete the specified node
struct Stu *t,*pre;
t=s->next;
pre=s;
printf("Student ID%d,Fraction%.2f\n",del->no,del->score);
while(t!=NULL){
if(t->no==del->no){
pre->next=t->next;
break;
}
pre=t;
t=t->next;
};
}
int main(){
int n=10;
struct Stu *s=creatStu(n),*t;
printfStu(s);
printf("end\n");
struct Stu *news=malloc(sizeof(stu));
news->no=1098;
delStu(s,news);
printfStu(s);
printf("end\n");
return 0;
}
```

#### 9.10 merge two linked lists, arrange them in ascending order of student number, and merge s2 into s1

```/*Sort by student number in ascending order*/
void sortLinkListAsc(struct Stu *s){
struct Stu *min,*news,*t;
int no;
float score;
news=s->next;
while(news!=NULL){//Selection sort
min=news;
t=news->next;
while(t!=NULL){
if(t->no<min->no){
min=t;
}
t=t->next;
}
no=min->no;
score=min->score;

min->no=news->no;
min->score=news->score;
news->no=no;
news->score=score;
news=news->next;
}
}
/*9.10 Merge the two linked lists in ascending order of student number, and merge s2 into s1*/
void mergeStuAndSort(struct Stu *s1,struct Stu *s2){
struct Stu *t;
t=s1;
while(t->next!=NULL){
t=t->next;
}
t->next=s2->next;

}

int main(){
int n=10;
struct Stu *s1=creatStu(n),*s2=creatStu(3);
mergeStuAndSort(s1,s2);
printfStu(s1);
printf("end\n");
return 0;
}

```

#### 9.11 there are two linked lists a and b. the setting node includes student number and name. Delete those nodes with the same student number from A-list and b-list

```/*9.11 There are two linked lists a and b. the set node contains student number and name. Delete those nodes with the same student number from A-list and b-list*/
void delBfromA(struct Stu *a,struct Stu *b){
struct Stu *t1,*t2,*pre;
t1=a->next;
t2=b->next;
pre=a;
while(t1!=NULL){
t2=b->next;
while(t2!=NULL){
if(t1->no==t2->no){
pre->next=t1->next;
t1=pre;
break;
}
t2=t2->next;
}
pre=t1;
t1=t1->next;
};
}
int main(){
int n=10;
struct Stu *s1=creatStu(n),*s2=creatStu(3);
delBfromA(s1,s2);
printfStu(s1);
printf("end\n");
return 0;
}

```

#### 9.12 establish a link list. Each node includes student number, name, gender and age. Enter an age. If the age of the node in the linked list is equal to this age, delete this node.

```/*9.12 Establish a link list, each node includes: student number, name, gender, age. Enter an age,
If the age of the node in the linked list is equal to this age, the node will be deleted.*/
struct Student{//structural morphology
int no;
char name[10];
int sex;
int age;
struct Student *next;
}student;
struct Student * creatStu1(int n){//Create a linked list with n nodes and a linked list with head nodes
while(n>0){
t=malloc(sizeof(student));
t->no=Total--;
sprintf(t->name,"%s_0%d","Student",n);//Student _0i
t->sex=rand()%2;
t->age=10+n%5;
last->next=t;
last=t;
n--;
}
}
void printfStu1(struct Student *s){//Print stu
struct Student *t;
t=s->next;
while(t!=NULL){
printf("Student ID%d,Full name%s,Gender%d,Age%d\n",t->no,t->name,t->sex,t->age);
t=t->next;
};
}
void delLinkedListByage(struct Student *s,int age){
struct Student *t,*pre;
t=s->next;
pre=s;
while(t!=NULL){
if(t->age==age){
pre->next=t->next;
t=pre;
}
pre=t;
t=t->next;
};
}
int main(){
int n=10;
struct Student *s1=creatStu1(n);
printfStu1(s1);
printfStu1(s1);
printf("end\n");
return 0;
}
```

#### 10.4 input a string from the keyboard, convert all lowercase letters into uppercase letters, and then output it to a disk file "test" for saving. The input string ends with "!"

```/*10.4 Enter a string from the keyboard to convert all lowercase letters into uppercase letters,
Then output to a disk file "test" to save. The entered string ends with "!".*/
void inputAllUpcase(char strs[]){
int i,len=strlen(strs);
while(strs[i]!='!'){
if(strs[i]>='a' && strs[i]<='z'){
strs[i]=strs[i]-32;
}
i++;
}
FILE *f;
f=fopen("./test","a+");
fputs(strs,f);
fclose(f);
}
void printfFile(FILE *f){
if(f==NULL){
printf("The input file does not exist!");
exit(0);
}
fseek(f,0,SEEK_END);//Move the file pointer to the end of the file
long size=ftell(f);//Gets the length from the file header to the file pointer
char buff[size+1];
fseek(f,0,SEEK_SET);//Move the file pointer to the file header
fread(buff,sizeof(*buff),size,f);//Read all the contents of the document
printf("file content is:%s\n",buff);
fclose(f);
}
int main(){
char strs[100];
printf("Please enter string on!End");
scanf("%s",strs);//gets(strs); new version error!
inputAllUpcase(strs);
FILE f=fopen("./test","r+");
printfFile(f);
printf("end\n");
return 0;
}
```

#### 10.5 there are two disk files "A" and "B", each storing A line of letters. It is required to combine the information in these two files, arrange them in alphabetical order, and output them to A new file "C".

```void printfFile(FILE *f){
if(f==NULL){
printf("The input file does not exist!");
exit(0);
}
fseek(f,0,SEEK_END);//Move the file pointer to the end of the file
long size=ftell(f);//Gets the length from the file header to the file pointer
char buff[size+1];
fseek(f,0,SEEK_SET);//Move the file pointer to the file header
fread(buff,sizeof(*buff),size,f);//Read all the contents of the document
printf("file content is:%s\n",buff);
fclose(f);
}
/*Read all contents in the file, return string*/
char *getAllFileContent(FILE *f){
if(f==NULL){
printf("The input file does not exist!");
exit(0);
}
fseek(f,0,SEEK_END);//Move the file pointer to the end of the file
long size=ftell(f);//Gets the length from the file header to the file pointer
char *buff=malloc((size+1)*sizeof(char));//Allocate memory on the heap, because after the function stack ends, the data in the local variables are allocated in the stack memory space. Once the function stack ends, the memory will be released, there will be garbled code, or allocated to other functions
fseek(f,0,SEEK_SET);//Move the file pointer to the file header
fread(buff,sizeof(*buff),size,f);//Read all the contents of the document
fclose(f);
return buff;
}
/*Sort by letter size*/
sortByWord(char *str){
int i,j,len=strlen(str)-1;
char t;
for(i=0;i<len-1;i++){//Bubbling
for(j=1;j<len-i;j++){
if(str[j]<str[j-1]){
t=str[j];
str[j]=str[j-1];
str[j-1]=t;
}
}
}
}
void merge2C(char *a,char *b){
int i=0,j=0;
char t;
FILE *f;
f=fopen("./C","a+");
while((a[i]!='\0' && a[i]!='\n') || (b[j]!='\n' && b[j]!='\0')){
if(a[i]>b[j] && b[j]!='\0' && b[j]!='\n' ){
t=b[j];
j++;
}else{
t=a[i];
i++;
}
fputc(t,f);
}
printfFile(f);
}

/*13.5 There are two disk files "A" and "B", each with A line of letters. It is required to merge the information in the two files in alphabetical order,
Output to a new file "C".*/
void mergeAndSortAndSave(){
FILE *fa,*fb;
fa=fopen("./A","r+");
fb=fopen("./B","r+");
char *a=getAllFileContent(fa);
char *b=getAllFileContent(fb);
sortByWord(a);
sortByWord(b);
printf("a is:%s\n",a);
printf("b is:%s\n",b);
merge2C(a,b);
free(a);//Heap memory allocated through malloc needs to be freed manually!
free(b);
}

int main(){
mergeAndSortAndSave();
printf("end\n");
return 0;
}
```

#### 10.6 there are 5 students, each student has 3 course scores, input the above data from the keyboard, including student number, name, three course scores, calculate the average score, store the original data and the calculated average score in the disk file student

```/*10.6 There are 5 students, each student has 3 course scores, input the above data from the keyboard, including student number, name, three course scores,,
Calculate the average score, and store the original data and the calculated average score in the disk file stud ent. */
typedef struct{
int num;
char name[20];
int score[3];
}stu;
void inputStuData(stu s[],int len){
int i;
printf("Please input the student number, name and the scores of the three courses in turn,Use space between data!\n");
for(i=0;i<len;i++){
scanf("%d %s %d %d %d",&s[i].num,&s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2]);
}
}
void outPutFile(stu s[],int len){
int i;
float sum;
FILE *f;
f=fopen("./stud","a+");
fprintf(f,"%s %s %s %s %s %s\n","Student ID","Full name","First door","Second door","Third door","Average");
for(i=0;i<len;i++){
sum=s[i].score[0]+s[i].score[1]+s[i].score[2];
fprintf(f,"%-4d %-4s %-6d %-6d %-6d %-6.2f\n",s[i].num,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],sum/3);
}//%-4d% format, - left aligned, right aligned by default, 4 bytes wide, d is a decimal integer
fclose(f);
}
int main(){
stu s[5];
inputStuData(s,5);
outPutFile(s,5);
printf("end\n");
return 0;
}
```

#### 10.7 sort the student data in the student file of the previous question according to the average score, and store the sorted student data in a new file stu sort

```/*10.7 Sort the student data in the student file of the previous question according to the average score, and store the sorted student data in a new file stu sort*/
FILE *f;
char tmp[255];
int i=0;
f=fopen("./stud","r+");
fgets(tmp,255,f);
while(!feof(f)){
fscanf(f,"%d%s%d%d%d%f",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2],&s[i].avg);
i++;
}
fclose(f);
}
void sortByAvg(stu s[],int len){
int i,j;
stu t;
for(i=0;i<len-1;i++){
for(j=1;j<len-i;j++){
if(s[j].avg<s[j-1].avg){
t=s[j];
s[j]=s[j-1];
s[j-1]=t;
}
}
}

}
void outPutSortFile(stu s[],int len){
int i;
FILE *f;
f=fopen("./stu-sort","a+");
fprintf(f,"%s %s %s %s %s %s\n","Student ID","Full name","First door","Second door","Third door","Average");
for(i=0;i<len;i++){
fprintf(f,"%-4d %-4s %-6d %-6d %-6d %-6.2f\n",s[i].num,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],s[i].avg);
}//%-4d% format, - left aligned, right aligned by default, 4 bytes wide, d is a decimal integer
fclose(f);
}
int main(){
stu s[5];
sortByAvg(s,5);
outPutSortFile(s,5);
printf("end\n");
return 0;
}
```

#### 10.8 insert the student's score file sorted by the previous question. Insert a student's 3 course scores, the program first calculates the average scores of the newly inserted students, then inserts it in the order of the average scores from low to high, and creates a new file after inserting.

```/*10.8 Insert the student's score file sorted by the previous question. The program first calculates the average scores of the newly inserted students,
Then insert it in the order of average score from low to high, and then create a new file.*/
typedef struct{
int num;
char name[20];
int score[3];
float avg;
}stu;
void inputStuData(stu s[],int len){
int i;
printf("Please input the student number, name and the scores of the three courses in turn,Use space between data!\n");
float sum;
for(i=0;i<len;i++){
scanf("%d %s %d %d %d",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2]);
sum=s[i].score[0]+s[i].score[1]+s[i].score[2];
s[i].avg=sum/3;
}
}
void readStud(stu s[],char *filename){
FILE *f;
char tmp[255];
int i=0;
f=fopen(filename,"r+");
fgets(tmp,255,f);
while(!feof(f)){
fscanf(f,"%d%s%d%d%d%f",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2],&s[i].avg);
i++;
}
fclose(f);
}
void outPutSortFile(stu s[],int len,char *filename){
int i;
FILE *f;
f=fopen(filename,"a+");
fprintf(f,"%s %s %s %s %s %s\n","Student ID","Full name","First door","Second door","Third door","Average");
for(i=0;i<len;i++){
fprintf(f,"%-4d %-4s %-6d %-6d %-6d %-6.2f\n",s[i].num,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],s[i].avg);
}//%-4d% format, - left aligned, right aligned by default, 4 bytes wide, d is a decimal integer
fclose(f);
}
void insertNew(stu ss[],stu s,int len){
int i;
len--;
for(i=0;i<len;i++){
if(s.avg<ss[i].avg){
while(i<len){
ss[len]=ss[len-1];
len--;
}
break;
}
}
ss[i]=s;
}
int main(){
stu s1[1],s[6];
char *fileName,*newFileName;
fileName="./stu-sort";
newFileName="./nstu-sort";
inputStuData(s1,1);//New student information
readStud(s,fileName);//Read the student information in the file
/*insert*/
insertNew(s,s1[0],6);
outPutSortFile(s,6,newFileName);//Save new file
printf("end\n");
return 0;
}

```

#### 10.9 the results of the previous question are still stored in the original stu sort file without creating a new one.

```/*10.9 The results of the previous question are still stored in the original stu sort file without creating a new one.*/
typedef struct{
int num;
char name[20];
int score[3];
float avg;
}stu;
void inputStuData(stu s[],int len){
int i;
printf("Please input the student number, name and the scores of the three courses in turn,Use space between data!\n");
float sum;
for(i=0;i<len;i++){
scanf("%d %s %d %d %d",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2]);
sum=s[i].score[0]+s[i].score[1]+s[i].score[2];
s[i].avg=sum/3;
}
}
void readStud(stu s[],char *filename){
FILE *f;
char tmp[255];
int i=0;
f=fopen(filename,"r+");
fgets(tmp,255,f);
while(!feof(f)){
fscanf(f,"%d%s%d%d%d%f",&s[i].num,s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2],&s[i].avg);
i++;
}
fclose(f);
}
void outPutSortFile(stu s[],int len,char *filename){
int i;
FILE *f;
f=fopen(filename,"w");
fprintf(f,"%s %s %s %s %s %s\n","Student ID","Full name","First door","Second door","Third door","Average");
for(i=0;i<len;i++){
fprintf(f,"%-4d %-4s %-6d %-6d %-6d %-6.2f\n",s[i].num,s[i].name,s[i].score[0],s[i].score[1],s[i].score[2],s[i].avg);
}//%-4d% format, - left aligned, right aligned by default, 4 bytes wide, d is a decimal integer
fclose(f);
}
void insertNew(stu ss[],stu s,int len){
int i;
len--;
for(i=0;i<len;i++){
if(s.avg<ss[i].avg){
while(i<len){
ss[len]=ss[len-1];
len--;
}
break;
}
}
ss[i]=s;
}
int main(){
stu s1[1],s[6];
char *fileName,*newFileName;
fileName="./stu-sort";
inputStuData(s1,1);//New student information
readStud(s,fileName);//Read the student information in the file
/*insert*/
insertNew(s,s1[0],6);
outPutSortFile(s,6,fileName);//Save new file
printf("end\n");
return 0;
}

```

#### 10.12 input several lines of characters from the keyboard, each line is not the same length, and store them in a disk file after input. Then read in the data from the file, convert the lowercase letters into uppercase letters, and output them on the display.

```/*13.12 Input several lines of characters from the keyboard, each line is not the same length, and store them in a disk file after input. Then read in the data from the file, convert the lowercase letters into uppercase letters, and output them on the display.*/
void getStringAndSave(){
FILE *f;
f=fopen("./test","a+");
int flag=1;
char c;
char str[255];
while(flag==1){
printf("input string:\n");
gets(str);
fprintf(f,"%s ",str);
printf("continue?");
c=getchar();
if(c=='N' || c=='n'){
flag=0;
}
getchar();
}
fclose(f);
f=fopen("./test","r+");
int i;
while(!feof(f)){
fscanf(f,"%s",str);
for(i=0;str[i]!='\0';i++){
if(str[i]>='a' && str[i]<='z'){
str[i]=str[i]-32;
}

}
printf("%s\n",str);

}
fclose(f);
}
int main(){
getStringAndSave();
printf("end\n");
return 0;
}
```
91 original articles published, 75 praised, 80000 visitors+

Tags: less ascii REST

Posted on Thu, 12 Mar 2020 03:16:16 -0700 by tryingtolearn