Learning C Language Part Three

1. Common Input and Output Functions

Understanding input and output functions is sufficient; being able to use one method is enough.

Because input and output directly interact with the terminal, in actual development, there are basically no programs that directly interact with the terminal.

1.1 putchar()/getchar()

putchar()

Prototype:

int putchar(int c);

Function:

Outputs a character to the terminal

Parameter:

c The character to be output

Return Value:

Returns the character that has been output to the terminal—can be ignored

#include <stdio.h>int main(){    // Can directly use putchar to output characters    putchar('H');    // H    putchar(10);// New line    // Can also pass the ASCII code of a character    putchar(65);    // A    putchar('\n');// New line    // Can also pass an expression    putchar('A'+3);    // D    putchar(10);    return 0;}

getchar()

Prototype:

int getchar(void);

Function:

Gets a character from the terminal

Parameter:

void Indicates no parameters

Return Value:

Returns the actual character obtained

#include <stdio.h>int main(int argc, const char *argv[]){    // Get a character from the terminal    // Need to define a char type variable to receive the obtained character    char value1 = getchar();    printf("value1 = [%d]  [%c]\n", value1, value1);    getchar();// getchar when used consecutively will be affected by garbage characters \n    // Can add a getchar() in between to consume the enter key of each input    char value2 = getchar();    printf("value2 = [%d]  [%c]\n", value2, value2);    getchar();// This getchar is also used to clean up garbage characters    // But it is the last input, can be added or not    return 0;}

1.2 puts()/gets()

puts()

Prototype:

int puts(const char *s);

Function:

Outputs a string to the terminal, automatically adds a new line

Parameter:

s The address of the string to be output

Return Value:

Success: returns the number of characters actually written to the terminal

Failure: -1

#include <stdio.h>int main(int argc, const char *argv[]){    // Can directly output a string, automatically adds a new line    puts("hello world");    // Can also directly output an array that stores a string    char arr[32] = "www.baidu.com";    puts(arr);    // Can also output a pointer to a string    char *p = "www.hqyj.com";    puts(p);    // puts outputs the string until it encounters \0, then stops processing    char s[32] = "北京市\0海淀区\n";    puts(s);    return 0;}

gets()

Prototype:

char *gets(char *s);

Function:

Gets a string from the terminal

Parameter:

s The address of the space used to save the obtained string

Return Value:

Returns s

#include <stdio.h>int main(int argc, const char *argv[]){    // Note when using gets: the space used to save the input string must be large enough    // Otherwise, out-of-bounds access will cause a segmentation fault    char arr[32];    // gets can input strings with spaces    gets(arr);    puts(arr);    return 0;}

1.3 printf()/scanf()

printf()

Function:

Outputs a string to the terminal in a specific format, —- formatted output

Header File:

#include <stdio.h>

Function Prototype:

int printf(const char *format, …);

Parameter:

format : Format

%c Output character

%d Output decimal integer

%u Output unsigned decimal integer

%o Output octal integer

%x Output hexadecimal integer

%f Output floating point

%e Output in exponential form

%% Output %

Additional Format Description:

l Used when outputting long or long long or double

# Outputs leading symbols 0 or 0x when outputting octal or hexadecimal

m m is an actual number, indicating the width of the output data

0 If the width is insufficient, fill with 0

– Left align

+ Include a positive sign when outputting positive numbers

.n Keep n decimal places

…: Variable arguments

#include <stdio.h>int main(int argc, const char *argv[]){    unsigned int value = 4294967295;    printf("value = %%d  = %d    %%u = %u\n", value, value);    int hour = 10;    int min = 6;    int sec = 9;    printf("%d:%d:%d\n", hour, min, sec);        //10:6:9    printf("%2d:%2d:%2d\n", hour, min, sec);    //10: 6: 9    printf("%02d:%02d:%02d\n", hour, min, sec);    //10:06:09    printf("%10d\n", min);// Right align    printf("%-10d\n", min);// Left align    printf("%+d\n", 1314);    printf("%+d\n", -1314);// If it is negative, the + sign will be ineffective    return 0;}

scanf()

Function:

Gets data from the terminal in a specific format, —- formatted input

Header File:

#include <stdio.h>

Function Prototype:

int scanf(const char *format, …);

Parameter:

format: Format, similar to printf’s format

The format of scanf must match the input, otherwise it cannot be obtained

… : Variable arguments, need to write the address to store the input, need to use &

#include <stdio.h>int main(int argc, const char *argv[]){#if 0    //-----int----    int a = 0;    int b = 0;    int c = 0;    // When inputting consecutively, use space or enter to distinguish    scanf("%d%d%d", &a, &b, &c);    // scanf("%d:%d:%d", &a, &b, &c);// If written this way, the input format must follow the :    // So be careful not to mess with the format in scanf, and do not casually add \n    printf("a = %d , b = %d , c = %d\n", a, b, c);#endif#if 0    //-------------char-----------    char value = 0;    scanf("%c", &value);    printf("%d  ----  %c  \n", value, value);#endif#if 0    //---------------float---------    float f = 0;    scanf("%f", &f);    printf("f = %f\n", f);#endif    //-----------string-----------    char s[64];    // If it is an array, directly write the array name in the variable argument position, no need to add &    // scanf("%s", s);    // puts(s);    // scanf cannot input strings with spaces    // If inputting strings with spaces, can use gets    // Or can use the following method    scanf("%[^
]", s);// Regular expression style, generally not used    puts(s);    return 0;}

1.4 Handling Garbage Characters

#include <stdio.h>int main(int argc, const char *argv[]){    // Scenarios where garbage characters appear    // Scenario 1: Using getchar multiple times consecutively#if 0    // Scenario 2: Using scanf(%c) multiple times consecutively    char a,b,c;    scanf("%c", &a);    getchar();// Handling method    scanf("%c", &b);    getchar();// Handling method    scanf("%c", &c);    getchar();// Handling method    printf("a = [%d]  [%c]\n", a, a);    printf("b = [%d]  [%c]\n", b, b);    printf("c = [%d]  [%c]\n", c, c);#endif    // Scenario 3: Using multiple %c in scanf    char a,b,c;    // scanf("%c%c%c", &a, &b, &c);    // Can use suppression symbols to handle -- not commonly used because if it is normal input, the suppression symbol will also consume characters    // scanf("%c%*c%c%*c%c", &a, &b, &c);    // Can also use space to clean up garbage characters --- commonly used    scanf("%c %c %c", &a, &b, &c);    printf("a = [%d]  [%c]\n", a, a);    printf("b = [%d]  [%c]\n", b, b);    printf("c = [%d]  [%c]\n", c, c);    // Note that %d does not need to consider garbage characters    return 0;}

2. Branch Control Statements

The program structure of C language has three types: sequential structure, branch structure (selection structure), and loop structure.

2.1 if..else Statement

2.1.1 Format

1. Simplified Format    if(Condition){        // Code block    }    Execution Logic: If the condition is true, execute the code block, otherwise do not execute the code block    if(Condition){        // Code block 1    }else{        // Code block 2    }    Execution Logic: If the condition is true, execute code block 1, otherwise execute code block 2.2. Ladder Format    if(Condition 1){        // Code block 1    }else if(Condition 2){        // Code block 2    }else if(Condition n){        // Code block n    }else{        // Other branches    }    Execution Logic: If condition 1 is true, execute code block 1, otherwise check condition 2, if true, execute code block 2, and so on... If all previous conditions are false, it will go to the last else branch.3. Nested Format    if(Condition 1){        if(Condition 11){            // Code block 11        }else if(Condition 12){            // Code block 12        }else{            // 1 other        }    }else if(Condition 2){        // Code block 2    }else if(Condition n){        if(Condition n1){            // Code block n1        }else if(Condition n2){            // Code block n2        }else{            // n other        }    }else{        // Other branches    }    // The nested format is equivalent to the ladder format nested within the ladder format    // The execution logic is basically the same as the ladder format

For example:

#include <stdio.h>int main(){    int value = 0;    scanf("%d", &value);#if 0    // Simplified Format    if(value > 0){        printf("yes\n");    }    printf("-----------------------------\n");    if(value > 0){        printf("yes\n");    }else{        printf("no\n");    }#endif    printf("-----------------------------\n");    // Ladder Format    if(value>20){        printf("v>20\n");    }else if(value > 10){        printf("v>10\n");    }else if(value > 0){        printf("v>0\n");    }else{        printf("other\n");    }    printf("----end-----\n");    return 0;}

2.1.2 Notes

1. If the code block after the if..else statement has only one line, {} can be omitted, but note that if {} is not written, the if condition only applies to the line below it.

2. There must be an if corresponding to else, it cannot appear alone, otherwise it will report an error.

3. else is combined with the nearest if at the same level.

4. Regarding the expression inside if(), generally, it is composed of relational operators and logical operators. (The result is generally a bool type.)

If there are special cases, pay attention to the following writing:

if(a=b) // Mistakenly wrote an equal sign to judge equality, at this time the result of the expression depends on the value of b

When b is 0, the expression is false, when b is non-zero, the expression is true

It is recommended to write the constant on the left when comparing equality with variables, such as if(100==a).

if(a) // At this time, the result of the expression is related to the value of a Equivalent to if(a != 0)

if(!a) Equivalent to if(0==a)

5. In the following writing, the two if statements are unrelated and do not affect each other.

if(){}

if(){}

6. if..else is a branch control statement, only one branch can be executed.

int x = 20;if(x>10){    printf("AA\n");    x = -10;}else if(x<=0){    printf("BB\n");}printf("end\n"); // The output result of the above code: //AA //end

2.1.3 if..else Statement Exercises:

1. Programming Task:

Input a student’s score from the terminal and output the corresponding grade:

[90,100] –> A

[80,90) –> B

[70,80) –> C

[60,70) –> D

Other scores –> Fail

#include <stdio.h>int main(){    int score = 0;    scanf("%d", &score);    if(score>=90 && score<=100){        printf("A\n");    }else if(score>=80 && score<90){        printf("B\n");    }else if(score>=70 && score<80){        printf("C\n");    }else if(score>=60 && score<70){        printf("D\n");    }else{        printf("Fail\n");    }    return 0;}

2. Programming Task:

Input the length, width, and height of a cube, and output whether it is a cube or a rectangular prism.

#include <stdio.h>int main(int argc, const char *argv[]){    int c=0 , k=0 , g=0;    scanf("%d%d%d", &c, &k, &g);    if(c==k && k==g){        printf("Cube\n");    }else{        printf("Rectangular Prism\n");    }    return 0;}

3. Write a program:

Input the lengths of the three sides of a triangle,

Determine if a triangle can be formed, if so

Output what kind of triangle it is

Equilateral: all three sides are equal

Isosceles: two sides are equal

Right-angled: Pythagorean theorem

Ordinary triangle

#include <stdio.h>int main(int argc, const char *argv[]){    int a = 0;    int b = 0;    int c = 0;    printf("Please enter the lengths of the three sides of the triangle:");    scanf("%d%d%d", &a, &b, &c);    if(a+b>c && a+c>b && b+c>a){        printf("Can form a triangle\n");        if(a==b && b==c){            printf("Equilateral Triangle\n");        }else if(a==b || a==c || b==c){            printf("Isosceles Triangle\n");        }else if((a*a+b*b==c*c) || (b*b+c*c==a*a) || (a*a+c*c==b*b)){            printf("Right-angled Triangle\n");        }else{            printf("Ordinary Triangle\n");        }    }else{        printf("Cannot form a triangle\n");    }    return 0;}

4. Write a program:

Input a year, output whether it is a common year or a leap year.

Leap year: divisible by 4 but not by 100, or divisible by 400

Test:

2004 Leap

2000 Leap

1900 Common

#include <stdio.h>int main(int argc, const char *argv[]){    int year = 0;    scanf("%d", &year);    if( (year%4==0 && year%100!=0) || year%400==0 ){        printf("%d is a leap year\n",year);    }else{        printf("%d is a common year\n",year);    }    return 0;}

5. Implement swapping two numbers

int a = 10;

int b = 20;

printf(“a = %d , b = %d\n”, a, b); //20,10

#include <stdio.h>int main(){    int a = 10;    int b = 20;    // Swap using a third variable    int c = a;    a = b;    b = c;    return 0;}

How to swap two variables without using a third variable.

#include <stdio.h>int main(){    unsigned int a = 10;    unsigned int b = 20;    #if 0    // Method 1    // This writing is unsafe because if both a and b are very large    // It may exceed the storage range of a, resulting in data loss    a = a+b;//30  20    b = a-b;//30  10    a = a-b;//20  10    #endif    // Method 2    // Swap two numbers using XOR    a = a^b;    b = a^b;    a = a^b;    return 0;}

Leave a Comment