1 Charactor arrays

  • Know the difference between Char arrays and strings.
  • Define the common string functions which are included in string.h
// write your own common string functions
#include <stdio.h>
#include <string.h>

int strlen_def(char *str){
    int i=0;
    while(str[i]!='\0') i++;
    return(i);
}

void strcat_def(char *a1, char *a2){
    int i, len_a1 = strlen_def(a1);
    int len_a2 = strlen_def(a2);
    //a1[len_a1++] = ' ';
    for (i = 0; i <= len_a2; i++){
        a1[len_a1 + i] = a2[i];
    }
    a1[len_a1+i] = '\0';
}

void strcpy_def(char *a1, char *a2){
    int i, len_a1 = strlen_def(a1);
    int len_a2 = strlen_def(a2);
    if(len_a1<len_a2+1)
        printf("The length of the first string must be longer than the second.");
    else{
        for (i = 0; i < len_a2; i++){
            a1[i] = a2[i];
        }
        a1[i] = '\0';
    }
}

int strcmp_def(char *a1, char *a2){
    int i=0, len_a1 = strlen_def(a1);
    int len_a2 = strlen_def(a2), minlen = (len_a1>len_a2)?len_a2:len_a1;
    while(i<minlen){
        if(a1[i]<a2[i]) return -1;
        else if(a1[i]>a2[i]) return 1;
        else i++;
    }
    return 0;
}

void strlwr_def(char *a1){
    int i=0;
    while(a1[i]!='\0'){
        if(a1[i]>='A'&& a1[i]<='Z') a1[i]+=32;
        i++;
    }
}

void strupr_def(char *a1){
    int i=0;
    while(a1[i]!='\0'){
        if(a1[i]>='a' && a1[i]<='z') a1[i]-=32;
        i++;
    }
}

void gets_def(char *a1){
    int i=0;
    char c;
    scanf("%c",&c);
    while(c!='\n'){
        a1[i++] = c;
        scanf("%c",&c);
    }
    a1[i] ='\0';
}

void puts_def(char *a1){
    int i=0;
    while(a1[i]!='\0')
        printf("%c",a1[i++]);
}

int main()
{
    char str1[100] = "I am a student.";
    char str2[] = "I am Chinese.";
    strcpy_def(str1,str2);
    //strcat_def(str1,str2);
    //strlwr_def(str1);
    //gets_def(str1);
    printf("%s\n",str1);
    //puts_def("I am a student.\nI am Chinese.");

    //printf("%d\t%d\n",strlen_def(str1),strlen(str1));
    //printf("%d\n",strcmp_def(str1,str2));

    return 0;
}
  • Write a function that can input continuously many sentences from I/O system.
#include <stdio.h>
#include <string.h>

void inputstr(char *p){
    int i = 0;
    char temp[1000];
    while (i<100){
        gets(temp);
        
        if (!(strcmp(temp, "The end!") && strcmp(temp, "the end") 
            && strcmp(temp, "the end!") && strcmp(temp, "end")))
            break;
        strcat(p, temp);
        strcat(p, " ");
        i++;
    }
}

int main()
{
    char str1[10000]={'\0'};
    inputstr(str1);
    printf("%s",str1);  

    fflush(stdin);
    getchar();
    return 0;
}

2 Functions

  • The syntax of functions
  • Declaration of functions following the #include <>
#include <stdio.h>
int max4(int a,int b,int c,int d);
int max2(int a,int b);

int main()
{
    int a,b,c,d,max;
    printf("Please enter 4 interger numbers:");
    scanf("%d %d %d %d",&a,&b,&c,&d);
    max=max4(a,b,c,d);
    printf("max=%d \n",max);
    return 0;
}

int max4(int a,int b,int c,int d)
{
    int m;
    m=max2(a,b);
    m=max2(m,c);
    m=max2(m,d);
    return(m);
}

int max2(int a,int b)
{  if(a>=b)
        return a;
    else
        return b;
}

3 Sugar functions

3.1 There are 10 students with 5 courses.

  • Calculate the average score of each student.
  • Calculate the average score of each course.
  • Find the highest score and the corresponding student and course
  • Calculate the varance of the student’s average scores. \[\begin{align} \sigma = \frac{1}{n}\sum_{i=1}^n x_i^2 - \left(\frac{1}{n}\sum_{i=1}^n x_i\right)^2 \end{align}\] where \(x_i\) is the student’s average score.
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#define N 10
#define M 5
float score[N][M];
float a_student[N],a_course[M];
int r,c;

int main()
{
    int i,j,seed = 1;
    float h;
    float var();
    float highest();
    void input_student(int seed);
    void aver_student();
    void aver_course();

    input_student(seed);
    aver_student();
    aver_course();
    printf("\n  NO.      course1    course2   course3   course4   course5   aver\n");
    for(i=0;i<N;i++){
        printf("\n NO %2d ",i+1);
        for(j=0;j<M;j++)
            printf("%10.2f",score[i][j]);
        printf("%10.2f\n",a_student[i]);
    }
    printf("\naverage:");
    for (j=0;j<M;j++)
        printf("%8.2f",a_course[j]);
    printf("\n");
    h=highest();
    printf("highest:%7.2f   NO. %2d   coursese %2d\n",h,r,c);
    printf("variance %8.2f\n",var());
    return 0;
}

void input_student(int seed)
{
    int i,j;
    printf("\nthe scores of students:\n");
    srand(seed);
    for(i=0;i<N;i++){
        for (j=0;j<M;j++)
          score[i][j] = 60+rand()%40;
    }
}


void aver_student()
{
    int i,j;
    float s;
    for(i=0;i<N;i++){
        for (j=0,s=0;j<M;j++)
            s+=score[i][j];
        a_student[i]=s/5.0;
    }
}

void aver_course()
{
    int i,j;
    float s;
    for(j=0;j<M;j++){
        s=0;
        for(i=0;i<N;i++)
            s+=score[i][j];
        a_course[j]=s/(float)N;
    }
}

float highest()
{
    int i,j;
    float high = score[0][0];
    for(i=0;i<N;i++)
        for(j=0;j<M;j++){
            if(score[i][j]>high){
                high=score[i][j];
                 r=i+1;
                 c=j+1;
            }
        }
    return(high);
}

float var()
{
    int i;
    float sumx = 0.0, sumxn = 0.0;
    for(i=0;i<N;i++){
        sumx+=a_student[i]*a_student[i];
        sumxn+=a_student[i];
    }
    return(sumx/N-(sumxn/N)*(sumxn/N));
}
  • or
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#define N 10
#define M 5

int main()
{
    int i,j,seed = 1;
    int r,c;
    float h, score[N][M],a_student[N],a_course[M];
    float var(float *a_student);
    float highest(float score[N][M], int *r, int *c);
    void input_student(float score[N][M], int seed);
    void aver_student(float score[N][M], float *a_student);
    void aver_course(float score[N][M], float *a_course);

    input_student(score, seed);
    aver_student(score,a_student);
    aver_course(score, a_course);
    printf("\n  NO.      course1    course2   course3   course4   course5   aver\n");
    for(i=0;i<N;i++){
        printf("\n NO %2d ",i+1);
        for(j=0;j<M;j++)
            printf("%10.2f",score[i][j]);
        printf("%10.2f\n",a_student[i]);
    }
    printf("\naverage:");
    for (j=0;j<M;j++)
        printf("%10.2f",a_course[j]);
    printf("\n");
    h=highest(score, &r, &c);
    printf("highest:%7.2f   NO. %2d   coursese %2d\n",h,r,c);
    printf("variance %8.2f\n",var(a_student));
    return 0;
}

void input_student(float score[N][M],int seed)
{
    int i,j;
    printf("\nthe scores of students:\n");
    srand(seed);
    for(i=0;i<N;i++){
        for (j=0;j<M;j++)
          score[i][j] = 60+rand()%40;
    }
}


void aver_student(float score[N][M], float *a_student)
{
    int i,j;
    float s;
    for(i=0;i<N;i++){
        for (j=0,s=0;j<M;j++)
            s+=score[i][j];
        a_student[i]=s/M;
    }
}

void aver_course(float score[N][M], float *a_course)
{
    int i,j;
    float s;
    for(j=0;j<M;j++){
        s=0;
        for(i=0;i<N;i++)
            s+=score[i][j];
        a_course[j]=s/N;
    }
}

float highest(float score[N][M], int *r, int *c)
{
    int i,j;
    float high = score[0][0];
    for(i=0;i<N;i++)
        for(j=0;j<M;j++){
            if(score[i][j]>high){
                high=score[i][j];
                 *r=i+1;
                 *c=j+1;
            }
        }
    return(high);
}

float var(float *a_student)
{
    int i;
    float sumx = 0.0, sumxn = 0.0;
    for(i=0;i<N;i++){
        sumx+=a_student[i]*a_student[i];
        sumxn+=a_student[i];
    }
    return(sumx/N-(sumxn/N)*(sumxn/N));
}

3.2 Calculate \(m\) to power \(n\)

  • that is, \(m^n\), where both \(m\) and \(n\) are positive integers.
/*pow(M,N)*/
#include<stdio.h>
#define M 2
#define N 100
#define L 1000
void fun(int arr[]){
    int i,a,b=0;
    for(i=L-1;i>=0;i--){
        a=arr[i]*M+b;
        arr[i]=a%10;
        b=a/10;
    }
}

int main(){
    int i,j,a[L]={0};
    a[L-1]=M;
    for(i=1;i<N;i++) fun(a);
    for(i=0;i<L;i++){
        if(a[i]>0){
            j=i;
            break;
        }
    }
    printf("pow(%d,%d)=",M,N);
    for(j=i;j<L;j++)
        printf("%d",a[j]);
    printf("\ni=%d\n",i);
    return 0;
}

4 Problem in the previous week

// Calculate the first 10 pairs (p,q) of Pell's equation.
#include<stdio.h>
void pf8iter(int max_iter){
    int p=3,q=1,count=1,tmp1;
    printf("(p,q) = (%d,%d)\n",p,q);
    while(count<max_iter){
        tmp1 = 3*p+8*q;
        q = 3*q+p;
        p=tmp1;
        count++;
        printf("(p,q) = (%d,%d)\n",p,q);
    }
}

int pf8int1(int max_iter){
    int p=1,q=1,count=0,times=0,f0=p*p-8*q*q-1;
    while(count<max_iter){
        times++;
        if(f0<0){
            f0=f0+4*(p+1);
            p+=2;
        }
        else if(f0>0){
            f0=f0-8*(2*q+1);
            q++;
        }
        else{
            printf("(p,q) = (%d,%d)\n",p,q);
            count++;
            f0=4*(p+1)-8*(2*q+1);
            p+=2;
            q++;
        }
    }
    printf("times = %d\n",times);
    return times;
}

int ifsquare(int x) {
    // if x is a square number, return its square root; else return 0;
    int i = (int) sqrt((float) x);
    int isquare = i * i;
    while (isquare < x) { isquare = isquare + 2 * i + 1; i++; }
    if (isquare == x) return i;
    else return 0;
}

int pf8new(int max_iter) {
    int t, p, q, tsquare, i, indicator,times=0;
    i = 0, t = 1, tsquare = t * t;
    while (i < max_iter) {
        times++;
        // tsquare = t*t; test if (tsquare+1)/2 is a square number;
        indicator = ifsquare( (tsquare + 1) / 2 );
        if (indicator)
        {
            p = tsquare * 2 + 1;
            q = t * indicator;
            printf("(p,q) = (%d,%d)\n",p,q);
            i++;
        }
        else {
            // if we define x = tsquare - 1, then x + 1 is a square number.
            // test if x/2 (which equal to (tsquare - 1)/2) is a square number;
            indicator = ifsquare( (tsquare - 1) / 2 );
            if (indicator)
            {
                p = tsquare * 2 - 1; // p = x * 2 + 1;
                q = t * indicator;
                printf("(p,q) = (%d,%d)\n",p,q);
                i++;
            }
        }
        tsquare = tsquare + t * 4 + 4; // set tsquare = (t + 2)*(t + 2);
        t = t + 2;
    }
    printf("times = %d\n",times);
    return times;
}

int main(){    
    pf8int1(10);
    pf8new(10);
    pf8iter(10);
    
    return 0;
}

5 Problems

  • A magic square is a square grid (where n is the number of cells on each side) filled with distinct positive integers in the range. such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal, where the sum equals \(n(n^2+1)/2\).

  • find the first fifty pairs \((p,q)\) satisfying \(p^2-8q^2=1\). More details about Pell’s equation can be found at https://en.wikipedia.org/wiki/Pell%27s_equation.