C Language Programming
All code shows the code inside the main function
Computer thinking
Rolling-Rotating Division
int u = 32; int v = 32; //If v=0, at the end of the calculation, u is the greatest common divisor //v!=0 calculates the remainder of u/v so that u=v=the remainder while(v!+0) { int temp = u%v; u = v; v = temp; } printf("%d",u);
From Computer to Program to Algorithms
The idea and advantage of computers is to list all the possibilities one by one (enumerate)
Dividing further simplifies operations and improves algorithm efficiency
Program Execution
Interpretation: With a program, that program can try to understand your program and then follow your requirements
Compile: With a program, that program can translate your program into machine language and execute it
Differences between Compilation and Interpretation
- Language is not compiled or interpreted
- Whether a language is compiled or interpreted depends more on how it is commonly executed
- Explanatory languages have special computing power
- Compiled languages have deterministic performance
Case: Find zero
Requirements:
- Have a place to put the number you entered
- Have a way to enter numbers
- The number entered participates in the operation
int price = 0; printf("Please enter amount (Yuan)"); scanf("%d",&price); int change = 100 - price; printf("Find you%d Yuan.\n",change);
optimization
- Easy to modify and maintain
- Reduce meaningless numbers
int price = 0; const int AMOUNT = 100; printf("Please enter amount(element)"); scanf("%d",&price); int change = AMOUNT - price; printf("Find you%d Yuan.\n",change);
const
Const is a modifier, preceded by int, const modifier variables cannot be modified once initialized, and can be re-optimized to allow the user to enter the value of that variable instead of a fixed 100
variable
The general form of variable definition is: <type name><variable name>;
In mathematics a=b and b=a have exactly the same meaning, but they have the opposite meaning in programming
All variables should be assigned (initialized) before they are first used
<Type Name><Variable Name>=<Initial Value>;
About scanf
scanf("%d",&price);
Ask the scanf function to read in the next integer and assign the result to price
Time-formatted string in double quotes,%d for reading integers
Beware of &before price, add &before scanf variable
Case: Calculating time difference
int hour1,minute1; int hour2,minute2; scanf("%d %d",&hour1,&minute1); scanf("%d %d",&hour2,&minute2); int t1 = hour1*60 + minute1; int t2 = hour2*60 + minute2; int t = t1 + t2; printf("The time difference is%d hour%d branch",t/60,t%60); //Use t/60 to abstract hours and t%60 to abstract minutes
Case study: average two integers
int a,b; scanf("%d %d",&a,&b); //Floating-point numbers are used to represent all numbers with decimal points. When floating-point numbers and integers are combined, c converts integers to floating-point numbers and then performs floating-point operations. double c = (a+b)/2.0; printf("%d and%d Average value is%lf",a,b,c);
data type | Chinese Name | Format string |
---|---|---|
double | Double | "%lf" |
float | Single-precision floating-point | "%f" |
int | integer | "%d" |
Case study: swapping two variables
int a = 5; int b = 6; int t = 0; t = a; a = b; b = t; printf("a=%d b=%d",a,b);
Compound Assignment
+= -= *= /= %= ++ –
These symbols are because the c language inherits the machine language of the past
count ++; count += 1; count = count + 1;
All three of them mean one plus one
A++ denotes adding a previous value
++ a denotes the value after adding one
But after these two operations, the next line, a, is the added value
Judgement Operation
/*if(Conditions are true){ ...; }*/ // ==Equal!=Inequality>Greater than>Greater than or equal to<Less than<=Less than or equal to //When the relationship between two values meets the expectation of the relational operator, the result of the relational operation is 1, otherwise 0 printf("%d\n",5==3); printf("%d\n",5>3); printf("%d\n",5<3); //All relational operators have lower priority than arithmetic but higher priority than assignment 7 >= 3+4; int r = a>0; //Determine if equal priority is lower than others //Continuous relational operations run from left to right
Case: Find Zero Calculator
//Initialization int price = 0; int bill = 0; //read in data printf("Please enter amount"); scanf("%d",&price); printf("Please enter the face"); scanf("%d",&bill); printf("You should be found:%d\n",bill-price);
But the program on top of us can't tell if we have enough money, that is, we can't tell if we have enough par space.
We make a logical judgment to optimize the program
//Initialization int price = 0; int bill = 0; //read in data printf("Please enter amount"); scanf("%d",&price); printf("Please enter the face"); scanf("%d",&bill); if(bill>=price) { printf("You should be found:%d\n",bill-price); } else { printf("Not enough money:%d\n",price-bill); }
Case: Size of comparison number
Case 1: Ratio of two numbers
int a,b; printf("Please enter two positive integers:"); scanf("%d %d",&a,&b); int max = 0; if(a>b) { max = a; } else { max = b; } printf("%d and%d The maximum value is%d",a,b,max);
Case 2: Ratio of three numbers (if nested method)
int a,b,c; scanf("%d %d %d",&a,&b,&c); int max = 0; if(a>b) { if(a>c) { max = a; } else { max = c; } } else { if(b>c) { max = b; } else { max = c; } } printf("Maximum is%d",max);
Case 2 can also be solved by other methods, such as bubble sorting, etc.
Programming habits tips
- Else always matches its nearest if, so it's recommended that you write an if instead of an else
- Indentation does not imply a match for else!!! Indentation does not imply a match for else!!! Indentation does not imply a match for else!!!
- You can use curly brackets when only a single line statement follows if, but they are recommended for overall style coordination
Case study: expression of piecewise function (if-else if-else)
The following piecewise functions require a program to be designed with input x and output y
f(x) = -1 x<0
f(x) = 0 x=0
f(x) = 2x x>0
//Show only if section if(x<0) { f = -1; } else if(x=0) { f = 0; } else { f = 2*x; }
Programming habits tips
- Note else alignment when indenting (cascade structure)
- Code as single export as possible, multiple encapsulation to reduce export (f above)
Common errors in if statement
- Forget to add braces
- if followed by a semicolon
- Misuse==
- else is not canonical
switch structure
If there are too many cascades, the execution efficiency will be very low, and a switch structure is available
switch(Control expression){ case Constant: Sentence; break; case Constant: Sentence; break; default: Sentence break; }
A control expression can only be the result of an integer type
Constant expressions can be constants or expressions
A switch statement can be viewed as a calculation-based jump, with multiple values corresponding to one statement
Case: Performance Conversion
A score greater than or equal to 90
A score greater than or equal to 80 is B
A score greater than or equal to 70 is C
A score greater than or equal to 60 is D
E for results less than 60
int grade; scanf("%d",&grade); grade /= 10; //We only abstract 10 digits for operation, so we can use the switch structure switch(grade) { case 10: case 9: printf("A\N"); break; case 8: printf("B\N"); break; case 7: printf("C\N"); break; case 6: printf("D\N"); break; default: printf("E\N"); break; }
Judge from top to bottom when cascading >
Judge from bottom to top when cascading <
Case: Number of digits (while cycle)
int x; int n = 0; scanf("%d",&x); //This line of code guarantees that the number of output bits for input 0 is 1 n++; x /= 10; while(x>0) { n++; x /= 10; } printf("%d\n",n);
tips
- The circulatory body must have the opportunity to change the circulating conditions
- When interrupting points test their own program, commonly used bounded data, valid ranges, special multiples of test data
- Adding comments and printf testing to your program can improve program feasibility and readability
optimization
Many of our situations require a cycle of judgment and execution
do-while executes a do-while and then determines the loop
int x; int n = 0; scanf("%d",&x); do { n++; x /= 10; } //Make sure to have a semicolon after this while while(x>0); printf("%d\n",n);
Extended Case: Count Cycle
int count = 100; while(count>=0) { //These two lines determine what the data for the first and last output is count--; printf("%d\n",count); } printf("launch\n");
Case: Guess Cycle
The computer thinks of a number and lets the user guess
Remind me if it's too big or too small to guess
Supplementary knowledge
- Each call to rand() yields a random integer
- The result of x%n is an integer of [0,n-1]
- x%100 means that x takes over 100, that is, there are only 10 bits left
Programming Thought
- Store the number of user inputs and set a loop that you can't go out without guessing
- Judging whether it's too big or too small
- How many times a variable was created to be stored
- optimization
srand(time(0)); int number = rand()%100+1; int count = 0; int a = 0; printf("I've got one in mind-100 Integer"); do{ printf("Please enter this 1-100 Integer"); scanf("%d",&a); count++; if(a>number) { printf("Big"); } else { printf("Small"); } } while(a!=number); prinf("Used%d The number was guessed%d",count,number);
Case: Average
Ask the user to enter a series of positive integers, end with -1, and the program calculates the average and number of these numbers
Programming Thought
- Use loops to keep users typing, and do not loop when -1 is equal
- Create a variable to store the number of digits
- Use 1.0 to force data types to float
int number; int sum = 0; int count = 0; scanf("%d",&number); while(number!=-1) { sum +=number; count++; scanf("%d",&number); } printf("%f\n",1.0*sum/count);
Case: Decomposition of Integers
Enter a positive integer (an integer in the int range) and output a number in reverse order
Programming Thought
- Get bits for an integer%10, 10 bits for an integer/10%10, and so on
- Reverse Sequence Processing
- Processing with 0 at the end
int x = 0; int sum = 0; int t = 0; scanf("%d",&x); int count = 0; //Prevent x changes Operating with a variable instead of X t = x; //So let's first get how many digits x is, so in order to prevent the input from being zero, we need to do a calculation first t /= 10; count++; while(t!=0) { t /= 10; count++; } //Reverse Sequence Processing //Operate several times with a few digits for(int i=0;i<count;i++) { //Abstract the last digit and leave x one less to the right int a = x % 10; x /= 10; //Using j=count-i-1 to abstract how many times a bit needs to change to the front by X 10, this method can also solve the problem that ends with 0 because 0*any number is 0 for(int j=count-i-1;j>0;j--) { a *= 10; } //Calculate Sum sum += a; } printf("%d",sum);
for loop summary
Case 1: Calculating factorials
int n; scanf("%d",&n); int fact = 1; int i = 1; for(i=1;i<=n;i++) { fact *= i; } printf("%d",fact);
Case 2: Is it a prime number
int x; scanf("%d",x); int i; int isPrime = 1; for(i=2;i<x;i++) { if(x%i == 0) { isPrime = 0; break; } else { continue; } } if(isPrime = 0) { printf("%d Not a prime number",x); } else { printf("%d prime number",x); }
About for Loop
- for loops are like counting loops: Initialization - Loop Conditions - Repeated Execution and Adjustment
- Each expression in for can be omitted
- for(; condition;)=while (condition)
tips
- If there is a fixed number of times use for
- do_while must be executed once
- Use while for the rest
Case study: Coins (how to get out of a nested loop)
How to use 1.2.5 cents to make up an amount less than 10 yuan
Option 1: Relay break
int x; int one,two,five; int exit = 0; scanf("%d",&x); for(one=1;one<x+10;one++) { for(two=1;two<x*10/2;two++) { for(five=1;five<x*10/5;five++) { if(one+two*2+five*5==x*10) { printf("%d1 horn%d2 horn%d5 horn",one,two,five); //Set a variable as an exit condition to create a relay break exit = 1; break; } if(exit == 1) { break; } } if(exit == 1) { break; } } }
Option 2:goto
int x; int one,two,five; int exit = 0; scanf("%d",&x); for(one=1;one<x+10;one++) { for(two=1;two<x*10/2;two++) { for(five=1;five<x*10/5;five++) { if(one+two*2+five*5==x*10) { printf("%d1 horn%d2 horn%d5 horn",one,two,five); goto FLAG; } } } } FLAG: return 0;
Case: Positive Ordinal Decomposition Integer
Enter a non-negative integer, output each bit in positive order, with a space between each bit, and no space at the end
Programming Thought
- Judge how many digits there are first
- Abstract positive ordinals per bit with space intervals
- Handle last non-space
int x; scanf("%d",&x); int mask = 1; while(t>9) { t /= 10; mask *= 10; } do { int d = x / mask; printf("%d",d); if(mask>9) { printf(" "); } x %= mask; mask /= 10; } while(mask>0); printf("\n");
Case: Maximum common divisor (enumeration divided by rolling)
Method 1: Set t to 2. If u and V are all divisible, write down t. Repeat the second step after t++ until it is equal to the minimum of u and v, then the largest t ever written down is goc
int a,b; int min=0; scanf("%d %d",&a,&b); if(a>b) { max = a; } else { max = b; } int ret = 0; for(int i=0;i<=min;i++) { if(a%i==0) { if(b%i==0) { ret == i; } } } printf("%d",ret);
Method 2: Rolling-Rotating Division
int u = 32; int v = 32; //If v=0, at the end of the calculation, u is the greatest common divisor //v!=0 calculates the remainder of u/v so that u=v=the remainder while(v!+0) { int temp = u%v; u = v; v = temp; } printf("%d",u);
Data type and language characteristics of C
C is a typed language and must be defined and typed before use
C Language development in two directions in the future
- C++/Java emphasizes types more and checks types more strictly
- Javascrip,Python,PHP don't care about types, and don't even need to define them
Types of C Language
- integer
- char
- short
- int
- long
- long long
- Floating point number
- float
- double
- long double
- logic
- bool
- Pointer
- Custom Type
sizeof
sizeof is an operator that calculates how many bytes an expression takes in memory
Be careful
- sizeof is a static operator whose operators are predefined at compile time
- Do not use parentheses in sizeof
Internal representation of integers
Everything inside the computer is binary
So how do we express negative numbers?
In decimal, our minus sign actually operates independently of numbers
Then there are three options for binary negative numbers
- Imitate decimal with a special flag
- Take the middle number 0, greater than it is an integer less than it is a negative number
- Complement Code
But the first two are understandable for humans, but they are complex in computer design.
Design with upper limit of digits
0->00000000
1->00000001
-1->11111111
Whole is 255 when treated as pure binary and -1 when treated as complement
The meaning of a complement is that taking the complement and the code adds up an overflow of 0
Range of integers
char c = 255; int i = 255; printf("c=%d,i=%d",c,i);
Output result c has a value of -1 and i 255
So different types have different ranges
A negative number range is one more than an integer range
unsigned
If we don't want to use complements, we can use the unsigned keyword to make variables pure binary
The range of positive numbers is expanded, negative numbers are no longer expressed
unsigned is not meant to extend the range that numbers can express, but to do pure binary operations, to shift
Case: Calculate the maximum number of int types
Utilization Principle: Exceeding the upper limit will overflow into a negative maximum value, minus just after returning to the positive maximum value
int a = 0; int b = 0; while(++a>0); printf("int The maximum number of data types is:%d\n",a-1); b++; while((a=a/10)!=0) { b++; } printf("int The maximum number of digits in a data type group is:%d",b);
Formatting of Integers
Input and output of integers can only take two forms: int or long
A number starts with 0 and is 8-digit
A number starts with 0x and is hexadecimal
%0 for octal
%x for hexadecimal
There will always be binary in your computer, and the octets you write will be converted when you compile them
8 and 16 are just how numbers are expressed as strings, not how numbers are expressed internally
A hexadecimal bit is exactly a 4-digit, 2-digit number
Choose Integer Type
Why do integers have so many kinds, in order to accurately express memory, do the needs of underlying programs
But in general, choose int without special needs
- Now the word length of the cpu is generally 32 or 64 bits. Each memory read-write and calculation is an int. Choosing a shorter type may not be faster, but may be slower.
- Now the compiler designs memory alignment, so shorter types actually occupy an int size, although sizeof says it's smaller than an int
Unigned differs from whether it is just output, internal calculations are the same
Floating Point Type
double and float
float significant number is 7 bits
double Significant Number is 15 Bits
There is always a number close to 0 but not equal to 0 that we cannot express, that is, infinity close to 0 cannot express
Scientific Counting in E
Output Precision
Add.n between%and f to specify the number of decimal places after the output, so that the output can be rounded
printf("%.3f\n",-0.0049); printf("%.30f\n",-0.0049); printf("%.3f\n",-0.00049);