A collection of 100 questions that must be brushed for beginners in C language (20-40)

Twenty-one: C language realizes printing rhombus.

Problem-solving ideas: The logic of this question is very simple. In essence, it is the nesting of loops, and then some simple mathematical logic. With the study of the heart-shaped confession of the previous question, it should be easy to understand this question . The rhombus is divided into two parts, the upper and lower parts of the rhombus.

C language realizes the printing of the first four lines:

for(i=0;i<4;i++)
  {
    for(j=0;j<=2-i;j++)
    {
      printf(" ");
    }
        for(k=0;k<=2*i;k++)/
        {
      printf("*");
    }
        printf("\n");
  }

Print the results individually:

#include<stdio.h>//头文件
int main()//主函数
{
  int i,j,k;//定义整型变量
  for(i=0;i<4;i++)//循环四次,打出前四行
  {
    for(j=0;j<=2-i;j++)//设定每行*号前面的空格,每行都是2-i个
    {
      printf(" ");//打印空格
    }
        for(k=0;k<=2*i;k++)//循环打出2*i-i个*号
        {
      printf("*");//打印*号
    }
        printf("\n");//打完一行后换行
  }
  for(i=0;i<=2;i++)//循环三次,打出后三行
  {
    for(j=0;j<=i;j++)//假设每行*号前面的空格,每行都是i个
    {
      printf(" ");//打印空格
    }
    for(k=0;k<=4-2*i;k++)//循环打出4-2*i个*号
    {
      printf("*");//打印*号
    }
    printf("\n");//打完一行后换行
  }
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

Twenty-two: C language implements the assignment of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 to the array elements in sequence, and then outputs in reverse order.

Problem-solving ideas: Obviously, we must first define an array with a length of 10. Since the assigned value is an integer, the array can be defined as an integer, and the value to be assigned is 0~9. There is a certain rule, and the value can be assigned by loop.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int a[10];//定义整型数组,数组的大小为10
  int i;//定义整型变量
  printf("原来的顺序:");
  for(i=0;i<10;i++)//赋值使a[0]~a[9]的值为0~9
  {
    a[i]=i;// 把i的值赋给数组a[i]
    printf("%d ",a[i]);//输出a[i],每个数之间加个空格隔开
  }
  printf("\n");//换行
  printf("逆序排列后:");
  for(i=9;i>=0;i--)//倒序输出
  {
    printf("%d ",a[i]);
  }
  printf("\n");//换行
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

原来的顺序:0 1 2 3 4 5 6 7 8 9
逆序排列后:9 8 7 6 5 4 3 2 1 0

--------------------------------
Process exited after 2.526 seconds with return value 0
请按任意键继续. . .

Note: The subscript of the array element starts from 0. If you use int a[10] to define the array, the maximum subscript value is 9, and there is no array element a[10].

Twenty-three: C language implements sorting of 10 numbers from small to large, requiring the use of bubble sorting.

Problem-solving ideas : There are two sorting rules: one is "ascending order", from small to large; the other is "descending order", from large to small.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int i,j,t;//定义整型变量
  int array[10];//定义数组大小
  printf("请输入十个数:");//提示语句
  for(i=0;i<10;i++)//手动往数组里输入10个数
  {
    scanf("%d,",&array[i]);//注意&符号
  }
  for(j=0;j<9;j++)//外层循环限制
  {
    for(i=0;i<9-j;i++)//内存循环
    if(array[i]>array[i+1])//如果前一个数比后一个数大
    {
      t=array[i]; //把小的数赋值给前面,大的数赋值给后面
      array[i]=array[i+1];
      array[i+1]=t;
    }
  }
  printf("按照从小到大的顺序排序:");//提示语句
  for(i=0;i<10;i++)//循环输出10个数
  {
    printf("%d ",array[i]);
  }
  printf("\n");//换行
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

请输入十个数:9 8 4 1 6 2 7 4 10 9
按照从小到大的顺序排序:1 2 4 4 6 7 8 9 9 10

--------------------------------
Process exited after 20.46 seconds with return value 0
请按任意键继续. . .

The above is the well-known "bubble sort", also known as "bubble sort". Through this example, it will inspire future learning of quick sort and heap sort. How to sort from largest to smallest?

Twenty-four: C language implements the exchange of elements in the rows and columns of a two-dimensional array and stores them in another two-dimensional array.

For example:

a数组的序列:
     1 2 3
     4 5 6
b数组的序列:
     1 4
     2 5
     3 6

Problem-solving ideas: You can define two arrays: array a has 2 rows and 3 columns, storing the specified 6 numbers. The array b has 3 rows and 2 columns, and no value is assigned at the beginning, as long as the element a[i][j] in the a array is stored in the b[j][i] element in the b array.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int i,j;//定义整型变量
  int a[2][3]={
   
   {1,2,3},{4,5,6}};//定义二维数组,且赋初值
  int b[3][2];//定义二维数组
  printf("横向数组的序列:\n");//提示语句
  for(i=0;i<2;i++)//外层for循环,限制行,共2行
  {
    for(j=0;j<3;j++)//内层for循环,限制列,共3列
    {
      printf("%6d",a[i][j]);//输出数组元素值,宽度为6
      b[j][i]=a[i][j];//赋值
    }
  printf("\n");//换行
  }
  
  printf("纵向数组的序列:\n");//提示语句
  for(i=0;i<3;i++)//外层for循环,限制行,3行
  {
    for(j=0;j<2;j++)//内层for循环,限制列,共2列
    {
      printf("%6d",b[i][j]);//输出数组元素值,宽度为6
    }
  printf("\n");//换行
  }
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

横向数组的序列:
     1     2     3
     4     5     6
纵向数组的序列:
     1     4
     2     5
     3     6

--------------------------------
Process exited after 0.04857 seconds with return value 0
请按任意键继续. . .

Twenty-five: C language implements the value of the largest element in the 3*4 matrix, as well as the row number and column number where it is located.

Problem-solving idea: Output the elements of the two-dimensional array, so that it is convenient to check whether the output result is striving for:

for(i=0;i<3;i++)//外层循环限制行,3行
  {
    for(j=0;j<4;j++)//外层循环限制列,4列
    {
      printf("%3d ",array[i][j]);//输出数组
    }
    printf("\n");//换行
  }

Note that these two lines of code add 1 after row and column, because array subscripts start from 0:

printf("行号是:%d\n",row+1);//行号
printf("列号是:%d\n",column+1);//列号

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int i,j;//定义整型变量
  int row,column,max;//定义行号、列号、最大值变量
  int array[3][4]={
   
   {1,2,3,4},{90,8,7,6},{-10,10,-5,2}};//定义二维数组且赋值
  for(i=0;i<3;i++)//外层循环限制行,3行
  {
    for(j=0;j<4;j++)//外层循环限制列,4列
    {
      printf("%3d ",array[i][j]);//输出数组,宽度为3 
    }
    printf("\n");//换行
  }
  printf("------------------\n");//分割开
  max=array[0][0];//先把数组的第一个数赋值给max
  for(i=0;i<3;i++)//外层循环限制行,3行
  {
    for(j=0;j<4;j++)//外层循环限制列,4列
    if(array[i][j]>max)//将数组中的每个数与第一个进行比较
    {
      max=array[i][j];//把大的赋值给max
      row=i;//把大的数的行号赋值给row
      column=j;//把大的数的列号赋值给column
    }
  }
  printf("max=%d\n",max);//输出最大的数
  printf("行号是:%d\n",row+1);//行号
  printf("列号是:%d\n",column+1);//列号
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

1 2 3 4
 90 8 7 6
-10 10 -5 2
------------------
max=90
行号是:2
列号是:1

--------------------------------
Process exited after 0.0816 seconds with return value 0
请按任意键继续. . .

Twenty-six: C language realizes the output of Yang Hui's triangle.

Problem-solving ideas: For this problem, it is divided into 3 parts to explain

The first part is to assign a characteristic number (the number at the beginning and end of each line is 1):

for(i=0;i<10;i++)//for循环
  {
    array[i][i]=1;//给二维数组的每一行的最后一个赋值为1
    array[i][0]=1;//第二维数组的每一行的开头赋值为1
  }

In the second part, assign a value to the middle number:

for(i=2;i<10;i++)//外层循环限制行
  {
    for(j=1;j<=i-1;j++)//内层循环限制列
    {
      array[i][j]=array[i-1][j]+array[i-1][j-1];//给中间的数赋值
    }
  }

The third part is to traverse and output the two-dimensional array after the above assignment;

for(i=0;i<10;i++)//外层循环限制行
  {
    for(j=0;j<=i;j++)//内层循环限制列
    {
      printf("%6d",array[i][j]);//输出二维数组,宽度为6
    }
  printf("\n");//换行
  }

Source code demo:

#include<stdio.h>//头文件
int main()//主函数入口
{
  int i,j;//定义整型变量
  int array[10][10];//定义二维数组
  for(i=0;i<10;i++)//for循环
  {
    array[i][i]=1;//给二维数组的每一行的最后一个赋值为1
    array[i][0]=1;//第二维数组的每一行的开头赋值为1
  }
  
  for(i=2;i<10;i++)//外层循环限制行
  {
    for(j=1;j<=i-1;j++)//内层循环限制列
    {
      array[i][j]=array[i-1][j]+array[i-1][j-1];//给中间的数赋值
    }
  }
  
  for(i=0;i<10;i++)//外层循环限制行
  {
    for(j=0;j<=i;j++)//内层循环限制列
    {
      printf("%6d",array[i][j]);//输出二维数组,宽度为6
    }
  printf("\n");//换行
  }
  return 0;//函数返回值为0
}

Compilation and running results are as follows:

 Twenty-seven: The output of the following results in C language is required to be realized by function calls.

***************
I love you!
**************

Problem-solving idea: there is a line of "*" above and below the output text, obviously there is no need to repeat this code, use a function to realize the function of outputting a line of "*"

int special_Symbols()//自定义函数,功能是输出一行*符号
{
  printf("*****************\n");
}

The second function realizes the I love you in the middle of the output.

int text()//自定义函数,功能是输出I love you!\n
{
  printf("I love you!\n");
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int special_Symbols();//声明自定义的special_Symbols方法
  int text();//声明自定义的text方法
  special_Symbols();//调用special_Symbols方法
  text();//调用text方法
  special_Symbols();//调用special_Symbols方法
  return 0;//函数返回值为0
}
int special_Symbols()//自定义函数,功能是输出一行*符号
{
  printf("*****************\n");
}
int text()//自定义函数,功能是输出I love you!\n
{
  printf("I love you!\n");
}

Compilation and running results are as follows:

*****************
I love you!
*****************

--------------------------------
Process exited after 1.794 seconds with return value 0
请按任意键继续. . .

When customizing the functions special_Symbols and text, specify the type of the function as void, which means that the function has no type, that is, no function value, that is, after executing these two functions, no value will be brought back to the main function.

Twenty-eight: Input two integers and ask to output the one with the larger value. A function is required to find large numbers.

Problem-solving ideas: The logic of this problem is very simple, the main thing is to extract the logic of the comparison size. For the comparison size, please refer to the previous article

int max_Fun(int x,int y)//自定义比大小函数
{
  int temp;//定义中间变量
  temp=x>y?x:y;//把大的数赋值给temp
  return temp;//把temp的结果返回到函数调用处
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int max_Fun(int x,int y);//函数声明
  int a,b,max;//定义整型变量
  printf("请输入两个数:");//提示语句
  scanf("%d,%d",&a,&b);//键盘输入两个数,注意用逗号隔开
  max=max_Fun(a,b);//调用max_Fun
  printf("大的数是:%d",max);//输出结果
  return 0;//主函数返回值为0
}
int max_Fun(int x,int y)//自定义比大小函数
{
  int temp;//定义中间变量
  temp=x>y?x:y;//把大的数赋值给temp
  return temp;//把temp的结果返回到函数调用处
}

Compilation and running results are as follows:

请输入两个数:4,9
大的数是:9
--------------------------------
Process exited after 4.251 seconds with return value 0
请按任意键继续. . .

Note: When the keyboard enters two numbers, the comma in the middle should be in English, because the comma in the code is in English, and the scanf function keyboard input should be consistent with the code. If it is in Chinese, the following results will be output.

请输入两个数:4,9
大的数是:4
--------------------------------
Process exited after 2.026 seconds with return value 0
请按任意键继续. . .

Twenty-nine: There are 5 beauties sitting together, ask the 5th beauty how old she is, she says she is 2 years older than the 4th beauty; ask the 4th beauty how old she is, she says she is 2 years older than the 3rd beauty; Ask the third beauty how old she is, she says she is 2 years older than the second beauty; ask the second beauty how old she is, she says she is 2 years older than the first one. Finally, I asked the first beauty, she said she was 10 years old. How old are the 2nd, 3rd, 4th, and 5th beauties? It is required to be realized by programming in C language.

Problem-solving ideas : Need to find the age of the first beauty, the age function is called several times in total, the last time is called by the main function, and the rest are called in the age function.

Find the age function:

int age(int temp)//自定义递归函数,参数temp类型是整型
{
  int peple_Age;//定义变量
  if(temp==1)//如果temp=1
  {
    peple_Age=10;//年龄是10岁
  }
  else
  {
    peple_Age=age(temp-1)+2;//年龄等于比前一个大2岁
  }
  return peple_Age;//将年龄返回到age函数调用处
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int age(int temp);//函数声明
  int number;//定义变量
  int people_Age;//定义变量
  printf("输入想知道的第几个孩子:"); //提示语句
  scanf("%d",&number);//键盘输入想知道第几个函数
  people_Age=age(number);//调用age函数
  printf("第%d个学生的年龄是%d岁\n",number,people_Age);//输出年龄
  return 0;//主函数返回值为0
}
int age(int temp)//自定义递归函数,参数temp类型是整型
{
  int peple_Age;//定义变量
  if(temp==1)//如果temp=1
  {
    peple_Age=10;//年龄是10岁
  }
  else
  {
    peple_Age=age(temp-1)+2;//年龄等于比前一个大2岁
  }
  return peple_Age;//将年龄返回到age函数调用处
}

Compilation and running results are as follows:

输入想知道的第几个孩子:5
第5个学生的年龄是18岁

--------------------------------
Process exited after 1.828 seconds with return value 0
请按任意键继续. . .

The importance of recursive calls is not used much in actual development. According to the experience of participating in ACM and Blue Bridge Cup during Kobayashi University, there are more in the competition.

Example 30: Find n in C language! , which requires recursive implementation.

Problem-solving ideas: This problem is similar to the idea of ​​​​Example 29, and both are realized by recursion

Find the factorial function:

int factorial(int number)//自定义阶乘函数
{
  int temp;//定义整型变量
  if(number<0)//如果这个数小于0
  {
    printf("错误数据请,输入大于0的数!");//不符合条件,无法求
  }
  else if(number==0||number==1)//0或者1本身的阶乘是1
  {
    temp=1;
  }
  else
  {
    temp=factorial(number-1)*number;//否则求这个数与前一个数相乘的结果
  }
  return temp;//将temp返回到函数调用处
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int factorial(int number);//自定义阶乘函数声明
  int number,temp;//定义变量
  printf("输入要求阶乘的数:");//提示语句
  scanf("%d",&number);//键盘输入相求的数
  temp=factorial(number);//调用阶乘函数
  printf("%d!=%d",number,temp) ;//输出结果
  return 0;//主函数返回值为0
}
int factorial(int number)//自定义阶乘函数
{
  int temp;//定义整型变量
  if(number<0)//如果这个数小于0
  {
    printf("错误数据请,输入大于0的数!");//不符合条件,无法求
  }
  else if(number==0||number==1)//0或者1本身的阶乘是1
  {
    temp=1;
  }
  else
  {
    temp=factorial(number-1)*number;//否则求这个数与前一个数相乘的结果
  }
  return temp;//将temp返回到函数调用处
}

Compilation and running results are as follows:

输入要求阶乘的数:5
5!=120
--------------------------------
Process exited after 1.553 seconds with return value 0
请按任意键继续. . .

I defined the above code as an int type, because this number cannot be infinitely large. If it is particularly large, it will exceed the range of int, as follows:

输入要求阶乘的数:100
100!=0
--------------------------------
Process exited after 1.575 seconds with return value 0
请按任意键继续. . .

 Those who have obtained the 100-question document and more learning materials, and the actual source code of the project are welcome to join the fan programming learning exchange group! There are some materials in the group to help you learn better. If you encounter any problems in the process of learning C language, you can send them out for discussion. Everyone is learning C/C++, or changing careers, or college students. There are also front-end parties who want to improve their abilities at work. If you are a small partner who is learning C/C++, you can join the study.

Click the link to join the group chat [C language/C++ communication group two]

Thirty-one: C language uses the pointer method to sort 10 integers in descending order.

Problem-solving ideas: Define an array in the main function to store 10 integers, define an int * pointer variable p to point to a[0], and define a function sort to sort the elements in the array from large to small.

Sort function:

void sort(int x[],int n)//自定义排序函数
{
  int i,j,k,t;//定义整型变量
  for(i=0;i<9;i++)//外层for循环
  {
    k=i;//把i的值赋给k
    for(j=1+i;j<10;j++)//内层for循环
    {
      if(x[j]>x[k])//如果前一个数大
      {
        k=j;
      }
    }
    t=x[k]; //赋值
    x[k]=x[i];
    x[i]=t;
  }
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  void sort(int x[],int n);//函数声明
  int i,*p,a[10];//定义整型变量、指针变量、数组
  p=a;//读者需要注意这里a赋值
  printf("请输入十个数:");//提示语句
  for(i=0;i<10;i++)//输入10个数
  {
    scanf("%d,",p++);//注意每个数之间用英文逗号隔开
  }
  p=a;//读者需要注意这里a赋值
  sort(a,10);//调用sort排序
  printf("由大到小排序后的:");//提示语句
  for(p=a,i=0;i<10;i++)//输出排序后的数
  {
    printf("%d ",*p);
    p++;
  }
  printf("\n");//换行
  return 0;//主函数返回值为0
}
void sort(int x[],int n)//自定义排序函数
{
  int i,j,k,t;//定义整型变量
  for(i=0;i<9;i++)//外层for循环
  {
    k=i;//把i的值赋给k
    for(j=1+i;j<10;j++)//内层for循环
    {
      if(x[j]>x[k])//如果前一个数大
      {
        k=j;
      }
    }
    t=x[k]; //赋值
    x[k]=x[i];
    x[i]=t;
  }
}

Compilation and running results are as follows:

请输入十个数:0,4,6,1,8,12,78,34,67,4
由大到小排序后的:78 67 34 12 8 6 4 4 1 0

--------------------------------
Process exited after 22.77 seconds with return value 0
请按任意键继续. . .

As mentioned in the previous section, the address is assigned to the pointer variable, as follows:

int i,*p,a[10];
p=a;

But in the above code, it is assigned like this:

int i,*p,a[10];
p=&a;

It is because the defined a is an array. In C language, the array name can represent the address, so there is no need to add the address character &, readers need to understand.

Thirty-two: There is a class with 3 students, each studying 4 courses, C language programming realizes the calculation of the total average score and the grade of the nth student, and requires the use of pointers.

Problem-solving ideas : Today's sample problem is divided into 3 parts. The following is to find the third student. Readers, please think about how to change to find the nth student.

The first step: find the average score function:

void average(float *p,int n)//自定义求平均成绩函数
{
  float *p_end;//定义浮点类型指针变量
  float sum=0,aver;//定义浮点型变量
  p_end=p+n-1;//把地址赋给指针变量
  for(;p<=p_end;p++)//for循环,注意第一处分号
  {
    sum=sum+(*p);//总和
  }
  aver=sum/n;//平均分
  printf("平均数是:%f",aver);//输出平均分
  printf("\n");//换行
}

Step 2: Find the nth student grade function

void search_Grade(float (*p)[4],int n)//自定义求第n个学生成绩函数
{
  int i;//定义变量
  printf("第%d个学生的成绩是:",n+1);//输出,注意此处我写的是n+1,数组下标是从0开始的
  for(i=0;i<4;i++)//for循环
  {
    printf("%5.2f ",*(*(p+n)+i));
  }
}

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  void average(float *p,int n);//函数声明
  void search_Grade(float (*p)[4],int n);//函数声明
  float score[3][4]={
   
   {1,2,3,4},{5,6,7,8},{9,10,11,12}};//定义浮点型数组
  average(*score,12);//平均成绩
  search_Grade(score,2);//第3个学生的成绩,这里写2是因为按照数组从0开始
  return 0;//主函数返回值为0
}
void average(float *p,int n)//自定义求平均成绩函数
{
  float *p_end;//定义浮点类型指针变量
  float sum=0,aver;//定义浮点型变量
  p_end=p+n-1;//把地址赋给指针变量
  for(;p<=p_end;p++)//for循环,注意第一处分号
  {
    sum=sum+(*p);//总和
  }
  aver=sum/n;//平均分
  printf("平均数是:%f",aver);//输出平均分
  printf("\n");//换行
}
void search_Grade(float (*p)[4],int n)//自定义求第n个学生成绩函数
{
  int i;//定义变量
  printf("第%d个学生的成绩是:",n+1);//输出,注意此处我写的是n+1,数组下标是从0开始的
  for(i=0;i<4;i++)//for循环
  {
    printf("%5.2f ",*(*(p+n)+i));
  }
}

Compilation and running results are as follows:

平均数是:6.500000
第3个学生的成绩是: 9.00 10.00 11.00 12.00
--------------------------------
Process exited after 0.07228 seconds with return value 0
请按任意键继续. . .

Thirty-three: There is a 3*4 two-dimensional array, and it is required to use C language to realize the pointer variable pointing to the element to output the value of the elements of the two-dimensional array.

Problem-solving ideas: The elements of the two-dimensional array are integers, which are equivalent to integer variables, and can be pointed to by int* type pointer variables. The elements of a two-dimensional array are stored in row order in the memory, that is, after all the elements in the row with the serial number 0 are stored, all the elements in the row with the serial number 1 are stored, and so on.

This example is to sequentially output the value of each element in the array, which is relatively simple. If a specified numerical element is to be output, the relative position of the element in the array should be calculated in advance.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int array[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};//定义二维数组,且赋初值
  int *p,m;//定义指针变量和普通变量
  for(m=0,p=array[0];p<array[0]+12;p++,m++)//for循环
  {
    if(m%4==0)//如果m%4的余数为0
    {
      printf("\n");//换行
    }
  printf("%4d",*p);//输出元素值,宽度为4
    }
    printf("\n");//换行
    return 0;//主函数返回值为0
}

Compilation and running results are as follows:

 Thirty-four: The C language implementation copies the string a to b, and then outputs b, requiring the use of pointers.

Problem-solving idea: define two character arrays a and b, and initialize the a array. Copy each character in array a to array b one by one. In the program, both a and b are defined as character arrays, and their array elements are accessed through addresses.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  char a[]="I love you";//定义字符数组且赋初值
  char b[20];//定义字符数组
  int i;//定义整型变量
  for(i=0;*(a+i)!='\0';i++)//for循环,!='\0'是指最后一个字符不是\0
  {
    *(b+i)=*(a+i);//赋值
  }
  *(b+i)='\0';//赋值
  printf("字符串a是:%s\n",a);//输出原来的
  printf("单个输出字符b:"); //提升语句
  for(i=0;b[i]!='\0';i++)//for循环
  {
    printf("%c",b[i]);//输出字符数组
  }
  printf("\n");//换行
  return 0;//主函数返回值为0
}

Compilation and running results are as follows:

字符串a是:I love you
单个输出字符b:I love you

--------------------------------
Process exited after 1.745 seconds with return value 0
请按任意键继续. . .

Thirty-five: C language programming to change the value of the pointer variable.

Problem-solving ideas: The value of the pointer p can be changed. When the printf function outputs a string, it starts from the element pointed to by the pointer variable p at that time, and outputs each character one by one until it encounters '\0'. Although the array name represents the address, it is a constant, and its value cannot be changed.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  char *p="I love C program language";//定义指针变量且赋值
  p=p+7;//指针变量p指向字符串的第8位
  printf("%s",p);//输出
  return 0;//主函数返回值为0
}

Compilation and running results are as follows:

C program language
--------------------------------
Process exited after 2.299 seconds with return value 0
请按任意键继续. . .

Special attention should be paid to:

char *p="I love C program language";

Although the array name represents the address, it is a constant and the value cannot be changed.

p=p+7;

Although it is +7, in C language, the subscript starts from 0.

Thirty-six: C language realizes the input of two integers, and then allows the user to choose 1 or 2, choose 1 to call max, and output the larger number of the two, and choose 2 to call min, and output the decimal of the two.

Problem-solving ideas : Define a function max and a function min to realize the calculation of the larger and smaller of the two integers.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  int max_Number(int ,int );//函数声明
  int min_Number(int x,int y);//函数声明
  int (*p)(int,int);//定义有参数的函数指针
  int a,b,c,d;//定义整型变量
  printf("请输入两个数:");//提示语句
  scanf("%d,%d",&a,&b);//键盘输入两个数,注意之间用英文逗号隔开
  printf("请选择1或者2:");//提示语句
  scanf("%d",&c);//键盘输入
  if(c==1)//如果是1
  {
    p=max_Number;//调用求大的函数
  }
  else if(c==2)//如果是2
  {
    p=min_Number;//调用求小的函数
  }
  d=(*p)(a,b);//给d赋值
  if(c==1)//如果是1
  {
    printf("max=%d",d);//输出大的
  }
  else
  {
    printf("min=%d",d);//否则输出小的
  }
  return 0; //主函数返回值为0
}
int max_Number(int x,int y)//自定义求两个数中的较大数
{
  return(x>y?x:y); //此处使用了三目运算符
}
int min_Number(int x,int y)//自定义求两个数中的较小数
{
  return (x>y?y:x);//此处使用了三目运算符
}

Compilation and running results are as follows:

请输入两个数:6,9
请选择1或者2:1
max=9
--------------------------------
Process exited after 7.124 seconds with return value 0
请按任意键继续. . .

Thirty-seven: C language implementation puts a student's information (including student number, name, name, address) in a structure variable. Then output the student's information.

Problem-solving ideas: first create a structure type in the program, including the members of the student information. Then use it to define the structure variable and assign the initial value at the same time.

When defining a structure variable, its members can be initialized. The initialization list is some constants enclosed in curly braces, and these constants are assigned to each member of the structure variable in turn.

Source code demo:

#include<stdio.h>//头文件
int main()//主函数
{
  struct student_Information   //定义学生结构体
  {
    int num; //学号
    char name[20];//名字
    char sex[20];//性别
    char address[20]; //地址
  }
  student_Information={8888,"刺客567","男生","广州市"};//赋值
  printf("学号是:%d\n",student_Information.num);//输出学号
  printf("姓名是:%s\n",student_Information.name);//输出名字
  printf("性别是:%s\n",student_Information.sex);//输出性别
  printf("住址是:%s\n",student_Information.address);//输出住址
  return 0;//主函数返回值为0
}

Compilation and running results are as follows:

学号是:8888
姓名是:刺客567
性别是:男生
住址是:广州市

--------------------------------
Process exited after 2.791 seconds with return value 0
请按任意键继续. . .

The stored array is a string, not a single character. If the %c format control character is used, the output will be as follows:

学号是:8888
姓名是:?
性别是:?
住址是:?

--------------------------------
Process exited after 1.785 seconds with return value 0
请按任意键继续. . .

Thirty-eight: There are three candidates, and each voter can only vote for one person. It is required to compile a program for counting votes in C language, input the names of the candidates one by one, and finally output the results of each person's votes.

Problem-solving idea : It is necessary to design a structure array, which contains 3 elements, and the information in each element should include the candidate's name and the number of votes.

Source code demo:

#include<stdio.h>//头文件
#include<string.h>//引入strcmp
 struct people//定义结构体变量
 {
   char name[20];//定义字符数组
   int number;//定义整型变量
 } leader[3]={"li",0,"zhang",0,"sun",0}; /*数组的定义和引用不一样,把姓赋给数组name 把0赋给 shu*/
 int main()//主函数
 {
   int i,j;//定义整型变量
   char leader_name[20];//定义字符数组
   for(i=1;i<10;i++)//for循环,循环9次
   {
     printf("请输入人名\n");//提示语句
     scanf("%s",leader_name);//键盘输入名字
     for(j=0;j<3;j++)
    if(strcmp(leader_name,leader[j].name)==0)//比较两个字符串,如果名字相等
     {
       leader[j].number++;//票数加1
     }
   }
   printf("结果是:\n");//提示语句
   for(i=0;i<3;i++)//for循环
   {
      printf("%s票数:%d\n",leader[i].name,leader[i].number);//输出名字和票数
  }
   return 0;//主函数返回值为0
 }

Compilation and running results are as follows:

请输入人名
li
请输入人名
zhang
请输入人名
sun
请输入人名
sun
请输入人名
li
请输入人名
li
请输入人名
li
请输入人名
sun
请输入人名
sun
结果是:
li票数:4
zhang票数:1
sun票数:4

--------------------------------
Process exited after 23.01 seconds with return value 0
请按任意键继续. . .

Thirty-nine: There are n students' information (including student number, name, and grades), and C language programming realizes outputting the students' information in the order of grades.

Problem-solving idea: Use the structure array to store n student information, use the selection method to sort each element, initialize when defining the structure array, and wrap each student's information in a pair of curly braces for clarity.

Source code demo:

#include<stdio.h>//头文件
struct student //学生结构体
{
  int num; //学号
  char name[20]; //姓名
  float score; //成绩
} ;
int main()//主函数
{
  //定义结构体变量且赋值
  struct student stu[5]={
   
   {10010,"Tom",78},{10011,"Jon",98.5},{10012,"Lisi",100},{10013,"zhangsan",99},{10014,"wangwu",10}};
  struct student t;
  int i,j,k;//定义整型变量
  printf("成绩由大到小排序:\n");//提示语句
  for(i=0;i<4;i++)//外层for循环
  {
    k=i;//把i的值赋给k
    for(j=i+1;j<5;j++)//内层for循环
    {
      if(stu[j].score>stu[k].score)//挑出分数高的
      {
        k=j;//把相应的j赋值给k
      }
    }
    t=stu[k]; //把成绩高的放到前面
    stu[k]=stu[i];
    stu[i]=t;
  }
  for(i=0;i<5;i++)//循环输出5个人的成绩
  {
    printf("%d,%10s,%6.2f分\n",stu[i].num,stu[i].name,stu[i].score);//输出结果
  }
  return 0;//主函数返回值为0
}

Compilation and running results are as follows:

成绩由大到小排序:
10012, Lisi,100.00分
10013, zhangsan, 99.00分
10011, Jon, 98.50分
10010, Tom, 78.00分
10014, wangwu, 10.00分

--------------------------------
Process exited after 0.05481 seconds with return value 0
请按任意键继续. . .

Example 40: C language implements the output of the information in the structure variable through the pointer variable variable pointing to the structure variable.

Problem-solving idea: declare the struct student type in the main function, then define a variable s_1 of struct student type, and define a pointer variable p, which points to an object of struct student type, and set the starting point of the structure variable s_1 Assign the address to the pointer variable p, that is, make p point to s_1, and then assign values ​​to each member of s_1.

Source code demo:

#include<stdio.h>//头文件
#include<string.h>//为了引用strcpy函数
int main(){//主函数
  struct student{  //学生结构体
    int num;
    char name[20];
    char sex;
    float score;
  };
  struct student s_1;//定义结构体变量
  struct student *p;//定义结构体指针变量
  p=&s_1;//将s_1得地址赋给指针变量
  s_1.num=10010;//赋值
  strcpy(s_1.name,"yan");//复制
  s_1.sex='M';//赋值
  s_1.score=100;//赋值
  printf("学号是:%d\n名字是%s\n性别是:%c\n成绩是:%f\n",
  s_1.num,s_1.name,s_1.sex,s_1.score); //输出结果
  printf("--------------------\n"); //隔开
  printf("学号是:%d\n名字是%s\n性别是:%c\n成绩是:%f\n",
  (*p).num,(*p).name,(*p).sex,(*p).score); //输出结果
  return 0;//主函数返回值为0
}

Compilation and running results are as follows:


学号是:10010
名字是yan
性别是:M
成绩是:100.000000
--------------------
学号是:10010
名字是yan
性别是:M
成绩是:100.000000

--------------------------------
Process exited after 1.116 seconds with return value 0
请按任意键继续. . .

Think about two questions, how to assign values ​​to structure variable members? How to access the members of the structure variable through the pointer to the structure variable?

Those who have obtained the 100-question document and more learning materials, and the actual source code of the project are welcome to join the fan programming learning exchange group! There are some materials in the group to help you learn better. If you encounter any problems in the process of learning C language, you can send them out for discussion. Everyone is learning C/C++, or changing careers, or college students. There are also front-end parties who want to improve their abilities at work. If you are a small partner who is learning C/C++, you can join the study.

Click the link to join the group chat [C language/C++ communication group two]

Guess you like

Origin blog.csdn.net/kxtxdy/article/details/126366044