Keywords: C

# Chapter V

## EG 4

Among the 1000 students in the Department, collecting charitable donations will end when the total amount reaches 100000 yuan. Count the number of donations at this time and the average number of donations per person.

Problem solving idea: obviously, it should be handled by circulation. The actual number of cycles cannot be determined in advance. You can set the maximum value (1000) to accumulate the total number of donations in the cycle body, and use the if statement to check whether it reaches 100000 yuan. If it reaches 100000 yuan, you will not continue to execute the cycle, terminate the accumulation, and calculate the per capita donation.

```#include<stdio.h>
# define SUM  100000
void main()
{
double num,total=0.0;
int i=1;
while(i)
{
printf("Please enter the number:\n");
scanf("%lf",&num);
total+=num;
i++;
if(total>=SUM)
{
printf("Number of contributions=%d,Average number of contributions=%lf",i,total/i);
break;
}
else continue;
}
}
```

## EG 5

100-200 numbers that cannot be divided by 3

## EG 7

Find pai ```#include <stdio.h>

#include <math.h>
int main(){
double num=1,pi,tmp=1.0;
int sign=1;

while(fabs(num)>=1e-6){
pi+=num;
tmp+=2;
sign=-sign;
num=sign/tmp;
}
pi=4*pi;
printf("pi The value of is:%.6f\n",pi);
}
```

## EG 8

Find the first 40 numbers of Fibonacci sequence

```#include <stdio.h>

int main()
{
int f1=1,f2=1,i=1;
for(;i<=20;i++)
{
printf("%10d\t%10d\t",f1,f2);
f1=f1+f2;
f2=f1+f2;
if(i%2==0)
{
printf("\n");
}

}
return 0;
}
```

## EG 9

Enter a number to judge whether it is a prime number

```#include <stdio.h>
void sushu(int n);
int main()
{
int n;
scanf("%d",&n);
sushu(n);
//   main();
return 0;
}
void sushu(int n)
{
int count = 0,i;
int k;
k=(int)sqrt(n);
for(i=2;i<=k;i++)
{
if(n%i==0)
{
printf("%d Not prime",n);
count = 1;
break;
}
}
if(count==0)
{
printf("%d It's a prime",n);
}

}
```

## EG 10

Find the prime between 100 – 200

• Even numbers are not prime numbers. Start from 101 and add 2 each time
```#include <stdio.h>
#include <math.h>
void main()
{
int i,j;
int k;            //Define loop variables
for(i=101;i<=200;i+=2)              //Defines the number of cycles from 100 to 200
{
k = (int)sqrt(i);
for(j=2;j<=k;j++)          //Determine whether the condition from (2) -- (k) can be divided by i
{
if(i%j==0) break;        //If you can, jump out of the loop, not prime
}
if(j>=k)                    //If J > = k, it is prime and output
printf("i =%d ,j = %d,k=%d\n",i,j,k);     //Output the results in tabular form
}
}

```

result: ## EG 11

To translate "China" into a password, 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 compile a program to make the values of cl, c2, c3, c4 and c5 respectively 'C', 'h', 'i', 'n' and 'a' by assigning initial values. After operation, c1, c2, c3, c4 and c5 become 'G', 'l','m ',' r 'and' e 'respectively and output.

input

China!

output

Encrypted China!

sample input

China!
sample output

Glmre!

```#include <stdio.h>
int main()
{
char c;
while((c=getchar())!='\n')
{
if((c>='A'&&c<='Z')||c>='a'&&c<='z')
{
c+=4;   //No matter three, seven, twenty-one, all conversion first;
// If it is the last four letters
// Pay attention to the difference between case and case!!
if((c>='Z'&&c<='Z'+4)||c>='z')
{
c=c-26;
}
}
printf("%c",c);
}
printf("\n");

}
``` ## Exercise 3

Find the maximum common divisor and the minimum common multiple

```
#include <stdio.h>
void main()
{
printf("Please enter two numbers:");
int n,m;
scanf("%d,%d",&n,&m);
int n1=n,m1=m;
if(m>n)
{
int tmp;
tmp = m;
m = n;
n = tmp;
}
while(m!=0)
{
int tmp;
tmp = n%m;
n = m;
m = tmp;

}
printf(" min = %d",n);
int max = n1*m1/n;
printf(" max = %d",max);

}
```

## Exercise 4

Count the number of input characters

```#include <stdio.h>
void main()
{
char c;
int word=0,num=0,empty = 0,other=0;
while((c=getchar())!='\n')
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) word++;
else  if((c>='0'&&c<='9'))
{
num++;
}
else if ((c==' '))
{
empty++;
}
else other++;
}
printf("Number of letters:%d\n",word);
printf("Number of numbers:%d\n",num);
printf("Number of spaces:%d\n",empty);
printf("Number of others:%d\n",other);
}
```

## Exercise 5 ```#include <stdio.h>
#include <math.h>
int main()
{
int n,a,i;   //n is the number of a
int   sum = 0, num = 0;
printf("Please enter n,a: ");
scanf("%d,%d", &n ,&a);
num=a;
sum=a;
printf("sum = %d",sum);
for (i = 1; i<n; i++)
{
num = num*10 +a;
sum += num;
printf(" +%d",num);
}
printf("\nsum = %d\n", sum);
//	main();
return 0;
}

```

Another solution

```#include <stdio.h>
#include <math.h>

int main()
{
//n is the number of a
int n;
double a, prev_sum = 0.0, total_sum = 0.0;
printf("Please enter a And n Value of: ");
scanf("%lf %d", &a, &n);
//Cycle n times to sum
for (int i = 0; i < n; i++)
{
prev_sum += a * pow(10, i);
total_sum += prev_sum;
}
printf("The sum is:%lf\n", total_sum);
return 0;
}

```
```Please enter n,a: 4,6
sum = 6 +66 +666 +6666
sum = 7404
```

## Exercise 6 The factorial of 20 is beyond the number range that the int type can represent, so use the double type in the code

```#include<stdio.h>
void main()
{
int i;
double sum = 0.0,num = 1.0;
for(i=1;i<=20;i++)
{
num*=i;
sum+=num;
}
printf("1~20 The sum of factorials of each number is:%lf\n",sum);
}
```
```1~20 The sum of factorials of each number is 256132749411820300.000000
```

## Exercise 7 ```#include<stdio.h>
void main()
{
int i=1;
double sum,sum1,sum2,sum3;
for(;i<=100;i++)
{
sum1+=i;
if(i<=50) sum2+=(i*i);
// Real division!!!
if(i<=10) sum3+=(1.0/i);
}
sum = sum1+sum2+sum3;
printf("sum = %lf",sum);
}
```
```sum = 47977.928968
```

## Exercise 8

Find the number of daffodils

```#include<stdio.h>
#include<math.h>
void main()
{
int a,b,c,n=100;
for(;n<1000;n++)
{
a = n / 100;
b = (n / 10) % 10;
c = n % 10;
if(pow(a,3)+pow(b,3)+pow(c,3) == n) printf("%d\n",n);
}
}
```

## Exercise 9

Perfect number

```#include <stdio.h>

void wanshu(int n);

void main()
{
int n;
printf("Enter number");
scanf("%d",&n);
wanshu(n);
}

void wanshu(int n)
{
int i;
int sum=0;
int k=0,j;
int a;
for(i=1;i<=n/2;i++)
{
if(n%i==0)
{
sum +=i;
a[k]=i;
k++;
}
if(sum==n)
{
j=k;
printf("%d its fators are ",n);
for(k=0;k<j;k++)
{
printf("%d,",a[k]);
}
}
}
}
```

### expand

Output all completions within 1000 and output their factors.

## Exercise 10 ```#include<stdio.h>
void main()
{
double sum, i=1.0,j=2.0;
int k = 20;
while(k)
{
int tmp;
sum+=(j/i);
tmp = j;
j+=i;
i=tmp;
k--;
}
printf("sum = %lf",sum);
}
``` ## Exercise 11

A ball falls freely from 100m height, bounces back to half of the original height after each landing, then falls and bounces again. Find out how many meters it passed on the 10th landing and how high it rebounded on the 10th.

The problem needs 10 cycles. In each cycle, you need to add up the falling height and rebound height. It should be noted that the 10th falling does not need to calculate the rebound distance, so it needs special treatment. When calculating each height, there will be decimals, so floating point numbers need to be selected

```#include<stdio.h>
void main()
{
double sum1=100,sum2=50;  //It has landed for the first time and began to rebound
int k = 9;   //Nine more landings are required
while(k)
{
sum1+=sum2*2;   //First calculate the distance of rebound and decline
sum2/=2;       //Landing, ready to rebound
k--;
}
sum2/2;   //Tenth landing, rebound height
printf("sum1 = %lf, sum2 = %lf",sum1,sum2);
}
```
```sum1 = 299.609375, sum2 = 0.097656
```

## Exercise 12

The monkey ate peaches. On the first day, the monkey picked several peaches and ate half of them immediately. It was not fun, so he ate another one; The next morning, he ate half of the remaining peaches and one more. Later, he ate the remaining half and one of the previous day every morning. When he wanted to eat again on the 10th morning, he saw only one peach left. He asked how many peaches there were on the first day

• Reverse thinking
```#include<stdio.h>
#include <stdlib.h>
int main(){
int n; //Days
int i;  //Peach number
int a = 1;
scanf("%d",&n);
for (i=1;i<=n;i++){
a++;
a*=2;
}
printf("%d",a);
return 0;
}
```
• Function recursion
```#include <stdio.h>
int fun(int n, int k)
{                    //Parameter n indicates the remaining peach trees on day n. parameter k indicates that the number of remaining peaches on day k is 1
int sum;//Define an integer variable sum
if (n == k)
{
sum = 1;
}
else
sum = 2 * (fun(n + 1, k) + 1);  //Call the recursive function, and then call the function inside the function
return sum;//Return sum
}

void main()
{
int k = 10, sum = 0;
printf("Please enter the number of days monkeys eat peaches\n Please enter k=");
scanf_s("%d", &k);
sum = fun(1, k);//
printf("Monkeys pick peaches for the first day=%d",sum);
}

```

## Exercise 13

1, Finding the square root of a number a can be approximated infinitely by iterative method.
The formula of iterative method is as follows

```X2 = (x1+a/x1)/2
```

1. First estimate a value x1, usually x1=a/2;
2. Bring in the iterative formula to get x2;
3. Calculate whether the absolute value of the difference between x1 and x2 meets the accuracy; If yes, x2 is the result; if no, enter S4;
4, x1 = x2, then repeat S2, S3 until the accuracy is met.

```#include <stdio.h>
#include <math.h>
int main()
{
double a;
double x1, x2;

printf("Please enter the number of square roots to be found:");
scanf("%lf",&a);
x1 = a/2;
x2 = (x1+a/x1)/2;
while(fabs(x1-x2)>=1e-8)
{
x1 = x2;
x2 = (x1+a/x1)/2;
}
printf("%f",x2);
}
```
```Please enter the number of square roots to be found: 99
9.949875
```

## Exercise 14

Use Newton iterative method to find the root of the following equation near the value equal to 2.0: 2x3-4x2+3x-6=0.

Iterative formula

```x2 = x1 - f(x1)/df(x1);
```
```#include <stdio.h>
#include <math.h>

double funY1(double x);
double funY2(double x);

int main() {
double  x1, x2;

x1 = 1.5;          //Find the root near 1.5
x2 = x1 - funY1(x1) / funY2(x1);
while (fabs(x2 - x1) >= 1e-5) {
x1 = x2;
x2 =  x1 - funY1(x1) / funY2(x1);
}
printf("%lf",x2);
}

// y function
double funY1(double x) {
double y1;
y1 = 2*pow(x,3) - 4*pow(x,2) + 3*x - 6;
return y1;
}

//First derivative of y
double funY2(double x) {
double y2;
y2 = 6*pow(x,2) - 8*x + 3;
return y2;
}

```

## Exercise 15

Find the root of equation 2x ^ 3 -4x^2+3x-6=0 between (- 10,10) by dichotomy

```#include <stdio.h>
#include <math.h>

//Function declaration
double fun(double x);

int main() {
double  x1=-10.0, x2=10.0,x0;
double y1,y2,y0;
y1 = fun(x1);
y2 = fun(x2);

do
{
x0=(x1+x2)/2;
y0 = fun(x0);
if ((y0*y1)<0)     //Indicates that the root is in this interval
{
x2=x0;         //Modulation endpoint
y2=y0;
}
else
{
x1=x0;
y1=y0;
}
} while(abs(y0)>1e-10);
printf("The root of the equation is%f",x0);
}

//   Function definition
double fun(double x)
{
double y1;
y1 = 2*pow(x,3) - 4*pow(x,2) + 3*x - 6;
return y1;
}

```

## Exercise 16

Enter the following graphics:

```   *
***
*****
*******
*****
***
*
```
```#include <stdio.h>

void main() {
int i,j,k;
for(i=1;i<=4;i++)
{
for(j=4-i;j>0;j--)
{
printf(" ");
}
for(k=1;k<=(2*i)-1;k++)
{
printf("*");
}
printf("\n");
}
for(i=3;i>=1;i--)
{
for(j=4-i;j>0;j--)
{
printf(" ");
}
for(k=1;k<=(2*i)-1;k++)
{
printf("*");
}
printf("\n");
}

}

```

## Exercise 17

The two table tennis teams play three each. Team a consists of a, B and c, and team B consists of x, y and Z. Lots have been drawn to decide the list of matches. The players were asked about the list of matches. A says he doesn't compete with x, c says he doesn't compete with x and Z. please program to find out the list of players of the three teams.

```#include <stdio.h>

void main() {
char a,b,c;
for(c='x';c<='z';c++)   //Judge from C
{
if((c!='x')&&(c!='z'))   // C doesn't fight X and Z
{
for(a='x';a<='z';a++)   //Judgement a
{
if(a!=c&&a!='x')    // ac has different opponents. a doesn't play with x
{
for(b='x';b<='z';b++)    //b is left
{
if(b!=a&&b!=c)    // b is different from a and C
printf("a=%c,b=%c,c=%c",a,b,c);
}
}
}
}
}

}

```

Posted by blindtoad on Sat, 20 Nov 2021 20:08:23 -0800