Variables and constants, input and output functions, and processing of garbage characters

Variables

Concept:

A value that may change during the execution of the program.

Definition:

Storage type Data type (example) Variable name (example)
auto (defaults to auto when omitted) int a
(auto) int a;

Initialization:

① Define first, then initialize:
(auto) int a; // definition
a = 6; // initialization (assignment)
② Initialize when defining:
(auto) int a = 6;

Variable name:

Follow naming conventions for identifiers.

Naming rules for identifiers:

1) Composed of letters, numbers, and underscores;
2) It cannot start with a number;
3) It cannot be repeated with keywords;

Exercise:

x y sum a100 _A7b_3x 3’a x*y @ b.8 while

Local variables and global variables

Data type

#include <stdio.h>
int main(int argc, char const *argv[])
{<!-- -->
    float a1 = 123.4567; // The highest precision of float is 7 significant digits
    float a2 = 123.456789;

    double b1 = 123456789.1234567;
    double b2 = 123456789.123456789; // The highest precision of double is 16 significant digits

    printf("%f\
", a1);
    printf("%f\
", a2);
    printf("%.12f\
", b1); // This machine only retains 7 digits after the decimal point
    printf("%.12f\
", b2);
    printf("%e\
", b1);
    printf("%e\
", b2);

    printf("%d\
", sizeof(char));
    printf("%d\
", sizeof(short));
    printf("%d\
", sizeof(int));
    printf("%d\
", sizeof(long));
    printf("%d\
", sizeof(float));
    printf("%d\
", sizeof(double));
    printf("%d\
", sizeof(long double));

    return 0;
}

The running results are as follows:

Constant

Concept:

A quantity that does not change while the program is running.

Category:

1. Character constant

A character enclosed in ‘ ‘. For example, ‘a’ represents the character a; and the pure letter a represents a variable.
After a number is defined as a character type, it can no longer participate in numerical operations. For example ‘5’ and 5 are different.

#include <stdio.h>
int main(int argc, char const *argv[])
{<!-- -->
    char ch = '5';
    printf("%c %d\
", ch, ch);

    return 0;
}

The running results are as follows:

Escape character

#include <stdio.h>
int main(int argc, char const *argv[])
{<!-- -->
    char v = 'V';
    char dec = 86; //decimal
    char oct = '\126'; //octal
    char hex = '\x56'; //hexadecimal

    printf("%c %c %c %c\
", v, dec, oct, hex); //decimal, octal/octonary, hexadecimal

    return 0;
}

The running results are as follows:

2. String constant

A string of characters enclosed by ” “. Double quotes only play a delimiting role, and the symbols in double quotes cannot be double quotes and backslashes.
In C language, when a string constant is stored in memory, the system automatically adds a “string end flag” at the end of the string, that is, the character NULL with an ASCII code value of 0, usually represented by “\0”. Therefore, a string constant of length n characters occupies n + 1 bytes of storage space in memory.

“Hola” is 5 characters, not 4.

#include <stdio.h>
int main(int argc, char const *argv[])
{<!-- -->
    char *str1 = "Hello!";
    char str2[5] = "Hola!"; // Any number >= 5 can be filled in the square brackets, or it can be left blank; otherwise, a warning will pop up

    printf("%s\
", str1);
    puts(str2);

    return 0;
}

The running results are as follows:

3. Integer constant

The representation of decimal integers is the simplest and does not require any prefix.
Octal integers need to start with “0” as the prefix; hexadecimal integers need to start with “0x” as the prefix.
Integer constants can be appended with “L” or “l” at the end to represent a long integer, and “U” or “u” to represent an unsigned integer.

4. Floating point constant

float (occupies 4 bytes) double (occupies 8 bytes)

In C language, there are only decimal real numbers, which can be represented in two ways: general form and exponential form. All floating-point constants are of double type by default.

5. Exponential constant

E(e)
The exponential form is usually used to represent very large or very small numbers, which is more concise and more readable. For example:
3e8 to represent 3108
2e-12 to mean 2
10-12

6. Identification constants

define
Macro definition: serves as an identifier
Name: Follow the naming rules for identifiers, but are generally expressed in uppercase letters.
Format: #define macro name constant or expression/replacement list
Features: It can only be replaced without calculation (replace as it is, then calculate after replacement)
#define N 2
#define M N + 3 // M = N + 3 = 2 + 3 != 5
#define NUM N + M/2 + 1

void main()
{<!-- -->
int a = NUM;
printf("%d\
", a); // The result is 6
}
// N + M/2 + 1 --> 2 + 2 + 3/2 + 1 // Remove the tail and get 6
#define HELLO hola // Replace all HELLO with hola

#define N 15 //Replace all N's with 15, often used in arrays
int arr[N];
#include <stdio.h>

#define M 57
#define Max m>n?m:n
#define Min(m, n) m<n?m:n

int main(int argc, char const *argv[])
{<!-- -->

    int m, n;
    scanf("%d %d", & amp;m, & amp;n); // If the values of m and n are not specified, the result will be random

    printf("%c\
", M);
    printf("%d\
", Max);
    printf("%d\
", Min(m, n));

    return 0;
}

The running results are as follows:

const

Formatted output function printf

Terminal input: man 3 printf. It can be seen that the return value of printf is an integer.

Function prototype:

int printf(const char *format, …);

Function:

Formatted string output (output to the terminal according to the specified format)

Parameters:

format: Specify the output format, output as a string. “…” represents several variables/expressions to be output.

Return value:

Successfully returns the number of correctly output characters.

#include <stdio.h>
int main(int argc, char const *argv[])
{<!-- -->
    int a = 5, b = 15, c = 155;
    char d = 126;

    int count1 = printf("%d\
", a);
    int count2 = printf("%d\
", b);
    int count3 = printf("%d\
", c);
    int count4 = printf("%c\
", d);

    printf("%d\t%d\t%d\t%d\
", count1, count2, count3, count4);

    return 0;
}

The running results are as follows:

Formats supported by printf

Modifiers of format specifiers supported by printf

Exercise:

Printf commonly used escape characters

Terminal input: man printf

Formatted input function scanf

Terminal input: man scanf

Function prototype:

int scanf(const char *format, …);

Function:

Input from the terminal according to the format, store it in the specified storage unit of the address table, and press the Enter key to end.
The data is considered to end when encountering the following situations: ① space, Tab or carriage return; ② end of width; ③ illegal input.

Parameters:

format: Specify the input format, “…” represents the address table of several variables to be input.

Return value:

Successfully returns the number of correct input variables; when illegal input is encountered, the return value will be less than the actual number of variables.

Formats supported by scanf

Modifiers of format specifiers supported by scanf

Character output function putchar

Terminal input: man putchar

Function prototype:

int putchar(int c); // The brackets can be decimal integer, ‘single character’, ‘\octal number’, ‘\xhexadecimal number’

Function:

Output a character to the terminal.

Parameters:

The ASCII value of the character constant to be output. Can also be an expression.

Return value:

The ASCII value of the character to be output.

Character input function getchar

Terminal input: man getchar

Function prototype:

int getchar (void);

Function:

Enter a character from the terminal.

Parameters:

none

Return value:

Returns the ASCII value of the character read.

//Use getchar and putchar to convert uppercase and lowercase letters
#include <stdio.h>

int main(int argc, char const *argv[])
{<!-- -->
    int ch = getchar();
    if(ch >= 65 & amp; & amp; ch <= 90)
        putchar(ch + 32);
    else if(ch >= 97 & amp; & amp; ch <= 122)
        putchar(ch - 32);
    else
        putchar(ch);
    
    putchar('\
');

    return 0;
}

Garbage character recycling

When using scanf to input data, the data is considered to end when the following conditions are encountered:
① Space, Tab or Enter; ② End of width; ③ Illegal input.

char ch1, ch2;
scanf("%c%c", & amp;ch1, & amp;ch2); // Enter a, space, b,
printf("ch1=%c ch2=%c\
", ch1, ch2); // will output ch1=a ch2=space

The running results are as follows:

Method 1: Add spaces

Can recycle one or more spaces, tabs and carriage returns.

char ch1, ch2;
scanf("%c %c", & amp;ch1, & amp;ch2); // Enter a, 3 spaces, b,
printf("ch1=%c ch2=%c\
", ch1, ch2); // will output ch1=a ch2=b

The running results are as follows:

Method 2: %*c

A %*c can only recycle one character.

char ch1, ch2;
scanf("%c%*c%c", & amp;ch1, & amp;ch2); // Enter a, 2 spaces, b,
printf("ch1=%c ch2=%c\
", ch1, ch2); // will output ch1=a ch2=space

The running results are as follows:

char ch1, ch2;
scanf("%c%*c%*c%c", & amp;ch1, & amp;ch2); // Enter a, 2 spaces, b,
printf("ch1=%c ch2=%c\
", ch1, ch2); // will output ch1=a ch2=b

The running results are as follows:

Method 3: getchar();

Only one character can be recycled and is generally used in loops.

#include <stdio.h>

int main(int argc, char const *argv[])
{<!-- -->
    while (1){<!-- -->
        char ch;
        scanf("%c", & amp;ch);
        printf("%c\
", ch);
        while (getchar() != '\
') // If this loop is not added, it will be as shown in Figure 2 below. Adding getchar(); can also be used instead.
        {<!-- -->
         /* code */
        }
    }

    return 0;
}

The running results are as follows: