18 classic programs (including source code) that must be memorized in C language

1. C language must memorize 18 classic programs

The thousands or even tens of thousands of lines of C language program codes you see are all written with some basic statements and keywords. It’s just that their logic functions are different, so how to quickly get started with C language codes, it is recommended to read more and write more. The following is the 18 classic programs in C language compiled by the editor.

2. Display of 18 classic programs that must be memorized in C language

1. Output 9*9 formula formulas. A total of 9 rows and 9 columns, i controls the row, and j controls the column.

#include "stdio.h"
main()
{int i,j,result;
 for (i=1;i<10;i + + )
   { for(j=1;j<10;j++)
       {
          result=i*j;
          printf("%d*%d=%-3d",i,j,result);/*-3d means left alignment, occupying 3 digits*/
       }
      printf("\
");/*New line after each line*/
   }
}

2. The function of the following program is to rotate a 4×4 array 90 degrees counterclockwise and then output it. The data of the original array is required to be randomly input, and the new array is output in the form of 4 rows and 4 columns. Please fill in the blank space program.

#include <stdio.h>
main()
{ int a[4][4],b[4][4],i,j; /*a stores the original array data, b stores the rotated array data*/
   printf("input 16 numbers: ");
/*Enter a set of data and store it in array a, then rotate and store it in array b*/
   for(i=0;i<4;i ++ )
       for(j=0;j<4;j++)
       { scanf("%d", &a[i][j]);
          b[3-j][i]=a[i][j];
        }
   printf("array b:\
");
   for(i=0;i<4;i ++ )
      { for(j=0;j<4;j++)
         printf("m",b[i][j]);
         printf("\
");
       }
}

3. Classical questions

There is a pair of rabbits, a pair of rabbits will be born every month from the third month after birth, and a pair of rabbits will be born every month after the third month. If the rabbits are not dead, ask the rabbits of each month What is the total?
The law of the rabbit is the sequence 1,1,2,3,5,8,13,21…

#include <stdio.h>
main()
{
long f1, f2;
int i;
f1=f2=1;
for(i=1;i<=20;i ++ )
  { printf("ld ld",f1,f2);
     if(i%2==0) printf("\
");/*control output, four per line*/
     f1=f1 + f2; /*Add the first two months and assign it to the third month*/
     f2=f1 + f2; /*Add the first two months and assign it to the third month*/
   }
}

4. Judge how many prime numbers there are between 101-200, and output all prime numbers and the number of prime numbers.

Program analysis: The method of judging the prime number: divide 2 to sqrt (this number) by a number, if it can be divisible, it means that the number is not a prime number, otherwise it is a prime number.

#include "math.h"
main()
{
  int m,i,k,h=0,leap=1;
  printf("\
");
  for(m=101;m<=200;m++)
   { k=sqrt(m + 1);
     for(i=2;i<=k;i + + )
       if(m%i==0)
          {leap=0;break;}
       if(leap) /*After the inner loop ends, leap is still 1, then m is a prime number*/
          {printf("%-4d",m);h++;
           if(h ==0)
               printf("\
");
          }
     leap=1;
   }
  printf("\
The total is %d",h);
}

5. If a number is exactly equal to the sum of its factors, this number is called a “perfect number”.

For example, 6=1+2+3. Program to find all the perfect numbers within 1000.

#include <stdio.h>
main()
{
  static int k[10];
  int i,j,n,s;
  for(j=2;j<1000;j++)
    {
     n=-1;
     s=j;
     for(i=1;i<j;i + + )
       {if((j%i)==0)
          { n++;
             s=s-i;
             k[n]=i;
          }
       }
  if(s==0)
   {printf("%d is a wanshu: ",j);
    for(i=0;i<n;i ++ )
        printf("%d,",k[i]);
    printf("%d\
",k[n]);
   }
}
}

operation result

6. Program to print right angle Yang Hui triangle

#include <stdio.h>
main()
{int i,j,a[6][6];
 for(i=0;i<=5;i ++ )
  {a[i][i]=1;a[i][0]=1;}
 for(i=2;i<=5;i + + )
    for(j=1;j<=i-1;j++)
     a[i][j]=a[i-1][j] + a[i-1][j-1];
 for(i=0;i<=5;i ++ )
    {for(j=0;j<=i;j++)
        printf("M",a[i][j]);
     printf("\
");}
}

7. Enter the grades of 3 students and 4 courses through the keyboard, and calculate the average grade of each student and the average grade of each course.

All grades are required to be put into an array of 4 rows and 5 columns. When entering, use spaces between the data of the same person, and carriage returns for different people. The last column and the last row respectively put the average grade of each student and the average grade of each course and class average.

#include <stdio.h>
#include <stdlib.h>
main()
{ float a[4][5], sum1, sum2;
  int i,j;
  for(i=0;i<3;i ++ )
    for(j=0;j<4;j++)
      scanf("%f", &a[i][j]);
  for(i=0;i<3;i ++ )
  { sum1=0;
    for(j=0;j<4;j++)
      sum1 + =a[i][j];
      a[i][4]=sum1/4;
  }
  for(j=0;j<5;j++)
  { sum2=0;
     for(i=0;i<3;i ++ )
       sum2 + =a[i][j];
       a[3][j]=sum2/3;
   }
   for(i=0;i<4;i ++ )
   { for(j=0;j<5;j++)
      printf("%6.2f",a[i][j]);
      printf("\
");
   }
}

8. Improve the program to output the input string in reverse order, such as inputting windows to output swodniw.

#include <string.h>
main()
{ char c[200],c1;
   int i,j,k;
   printf("Enter a string: ");
   scanf("%s",c);
   k=strlen(c);
   for (i=0,j=k-1;i<k/2;i + + ,j--)
     { c1=c[i];c[i]=c[j];c[j]=c1; }
   printf("%s\
",c);
}

Pointer method:

void invert(char *s)
{int i,j,k;
 char t;
 k=strlen(s);
 for(i=0,j=k-1;i<k/2;i ++ ,j--)
 { t=*(s + i); *(s + i)=*(s + j); *(s + j)=t; }
}
main()
{ FILE *fp;
char str[200],*p,i,j;
if((fp=fopen("p9_2.out","w"))==NULL)
     { printf("cannot open the file\
");
       exit(0);
     }
   printf("input str:\
");
gets(str);
   printf(“\
%s”, str);
fprintf(fp,"%s", str);
invert(str);
    printf(“\
%s”, str);
fprintf(fp,"\
%s", str);
  fclose(fp);
}

9. The function of the following program is to delete the characters stored in c from the character array s.

#include <stdio.h>
main()
{ char s[80],c;
   int j,k;
   printf("\
Enter a string: ");
   gets(s);
   printf("\
Enter a character: ");
   c=getchar( );
   for(j=k=0;s[j]!= '\0';j ++ )
   if(s[j]!=c)
      s[k + + ]=s[j];
   s[k]= '\0';
   printf("\
%s",s);
}

10. Write a void sort(int *x, int n) to sort the n data in the x array from large to small. n and array elements are entered in the main function. Display the result on the screen and output it to the file p9_1.out

#include<stdio.h>
void sort(int *x,int n)
{
int i,j,k,t;
for(i=0;i<n-1;i + + )
{
 k=i;
 for(j=i + 1;j<n;j + + )
   if(x[j]>x[k]) k=j;
   if(k!=i)
   {
    t=x[i];
    x[i]=x[k];
    x[k]=t;
   }
}
}
void main()
{FILE *fp;
     int *p,i,a[10];
     fp=fopen("p9_1.out","w");
    p=a;
printf("Input 10 numbers:");
for(i=0;i<10;i ++ )
  scanf("%d",p++);
p=a;
sort(p,10);
for(;p<a + 10;p + + )
 { printf("%d ",*p);
        fprintf(fp,"%d ",*p); }
        system("pause");
    fclose(fp);
}

output:

11. It is known that the elements in the array a are arranged in descending order. The function of the following program is to insert an input number into the array a. After insertion, the elements in the array a are still in ascending order Arrange

main()
    { int a[10]={0,12,17,20,25,28,30}; /*a[0] is the working unit, start storing data from a[1]*/
       int x , i, j=6; /*j is the number of elements*/
       printf("Enter a number: ");
       scanf("%d", &x);
       a[0]=x;
       i=j; /*Start from the last unit*/
       while(a[i]>x)
       { a[i + 1]=a[i]; i--; } /*Move the number greater than x to one position*/
       a[ + + i]=x;
       j + + ; /*Increase the total number of elements after inserting x*/
       for(i=1;i<=j;i ++ ) printf("?",a[i]);
       printf("\
");
}

output:

12. Write the function replace(char *s, char c1, char c2) to replace all characters c1 in the string pointed to by s with c2. The string, characters c1 and c2 are all input in the main function, and the The original string and the replaced string are displayed on the screen and output to the file p10_2.out

#include<stdio.h>
replace(char *s,char c1,char c2)
{ while(*s!='\0')
   { if (*s==c1)
         *s=c2;
         s++;
   }
}
main()
{ FILE *fp;
  char str[100],a,b;
   if((fp=fopen("p10_2.out","w"))==NULL)
      { printf("cannot open the file\
");
       exit(0); }
   printf("Enter a string:\
");
    gets(str);
    printf("Enter a & amp; & amp; b:\
");
    scanf("%c,%c", &a, &b);
printf("%s\
", str);
fprintf(fp,"%s\
", str);
replace(str,a,b);
printf("The new string is----%s\
", str);
fprintf(fp,"The new string is----%s\
",str);
fclose(fp);
}

13. Search for a substring s2 in a string s1, if it exists, return the starting position of the substring in the main string
, returns -1 if it does not exist.

main()
{char s1[6]="thisis";char s2[5]="is";
printf("%d\
",search(s1,s2));
system("pause");
}
int search(char s1[], char s2[])
{int i=0,j,len=strlen(s2);
while(s1[i]){
 for(j=0;j<len;j++)
 if(s1[i + j]!=s2[j]) break;
 if(j>=len) return i;
 else i ++ ;
 }
return -1;
}

14. Use pointer variables to output structure array elements.

struct student
{
 int num;
 char *name;
char sex;
int age;
}stu[5]={<!-- -->{1001,"lihua",'F',18},{1002,"liuxing",'M',19},{1003,"huangke",' F',19},{1004,"fengshou",'F',19},{1005,"Wangming",'M',18}};
main()
{int i;
struct student *ps;
printf("Num \tName\t\t\tSex\tAge\t\
");
/*Output structure array elements with pointer variable. */
for(ps=stu;ps<stu + 5;ps + + )
printf("%d\t%-10s\t\t%c\t%d\t\
",ps->num,ps->name,ps->sex,ps->age);
/* Use the array subscript method to output the student number and age of the structure array elements. */
for(i=0;i<5;i ++ )
printf("%d\t%d\t\
",stu[i].num,stu[i].age);
}

15. Create a simple linked list with three nodes:

#define NULL 0
struct student
{
int num;
char *name;
int age ;
struct student *next;
};
void main()
{
struct student a,b,c,*head,*p;
a.num=1001; a.name="lihua"; a.age=18; /* Assign values to node members */
b.num=1002; b.name="liuxing"; b.age=19;
c.num=1003; c.name="huangke"; c.age=18;
head= & amp;a; /* Create a linked list, a is the head node */
a.next= &b;
b.next= &c;
c.next=NULL;
p=head; /* output linked list */
do {
printf("],%s,=\
",p->num,p->name,p->age);
p=p->next;
}while(p!=NULL);
}

16. Bubble sorting, from small to large, the sorted results are output to the screen and file myf2.out

#include<stdio.h>
void fun(int a[],int n)
{int i,j,t;
for(i=0;i<=n-1;i ++ )
  for(j=0;j<i;j++)
    if(a[j]>a[j + 1]) {t=a[j];a[j]=a[j+1];a[j+1]=t;}
}
main()
{int a[10]={12,45,7,8,96,4,10,48,2,46},n=10,i;
FILE *f;
if((f=fopen("myf2.out","w"))==NULL)
   printf("open file myf2.out failed!\
");
fun(a,10);
for(i=0;i<10;i ++ )
   {printf("M",a[i]);
    fprintf(f,"M",a[i]);
   }
fclose(f);
}

output

17. Input a character string and judge whether it is a palindrome. A palindromic string is a string that reads exactly the same from left to right as from right to left.

#include <stdio.h>
#include <string.h>
#include <string.h>
main()
{ char s[100];
  int i,j,n;
  printf("Enter string:\
");
  gets(s);
  n=strlen(s);
  for(i=0,j=n-1;i<j;i ++ ,j--)
    if(s[i]!=s[j]) break;
  if(i>=j) printf("is a palindrome\
");
  else printf("Not a palindrome\
");
}

18. Write the function countpi and use the formula to calculate the approximate value of π

When the value of a certain item is less than 10-5, it is considered that the accuracy requirement is met, please complete the function. Display the result on the screen and output to the file p7_3.out.

#include<stdio.h>
double countpi(double eps) /*eps is the allowable error*/
  {
    int m=1;
     double temp=1.0,s=0;
     while(temp>=eps)
     { s + = temp;
        temp=temp*m/(2*m + 1);
        m++;
     }
     return(2*s);
  }
main()
{FILE *fp;
     double eps=1e-5,pi;
     if((fp=fopen("p7_3.out","w"))==NULL)
   { printf("cannot open the file\
");
     exit(0);
   }
   pi= countpi(eps);
   printf("pi=%lf\
",pi);
fprintf(fp,"pi=%lf\
",pi);
fclose(fp);
}