Freshman Meng Xin can read the C language version (I)

Why_ does_ it_ work 2021-11-25 15:32:54

Catalog

c The framework of language

Variable

data type

Format output statement

Symbol

sentence

Conditional statements

Loop statement

Small statement

function

Array

The pointer

Pointers and functions

Pointers and arrays

c The framework of language

Simply speaking ,c The main components of the language are header file and main function , The header file is #include, The main function is int Function of type :int main

Variable

Variable in c Language has a high status , Words similar to our paragraph , adopt c The grammar of language together constitutes c Language

Of course, variables are variable quantities , We should all give it a name ( identifier ) The identifier only needs to be recognized by yourself , So when we use variables , We should define . Variables consist of three parts : Variable name , Variable values and storage units ( Address )

The format in our definition process is very simple : data type identifier ;

In the process of variable assignment, you can define variables first 1 To assign a value , You can also assign values and define ( Commonly used for)

int a;
for(a=1;a<10;a++)
for(int a=1;a<10;a++)

data type

In the process of variable definition and function definition , You can't lack the data type in the definition process

æ°æç±»ååç±»

The most common is the basic type

  • plastic :int, Used to store integers  

æ´å

  • Character :char, For storing characters
  • Floating point numbers : single :float: Use and to store one decimal place
  • Floating point numbers : many :double: Used to store more than one decimal place

Format output statement

In different data types , The symbols of the output statements are also different

%d : Decimal integer int Corresponding

%lld : Long integer longlong Corresponding

%c : character char Corresponding

%s : character string (c In language , A position is a character )char Array correspondence

%f : decimal float Corresponding

%lf : decimal double Corresponding

 printf(" Normal character output formatter ", Output item ); 

Again c In language , We can use an identifier as a constant

#define identifier Constant values  ( Writing format ) In fact, yes. const int identifier = The effect of constants is the same

Symbol


Some symbols are used to calculate , In fact, the main function of symbols is to simplify

1. Arithmetic operators are relatively simple, but there are several points to note

Symbols mainly include : Addition, subtraction, multiplication, division and remainder , Increase and decrease

  • If the two numbers divided are integers , Then the result is also an integer , Decimals are automatically omitted
  • If Division , One of the numbers is a decimal , Then the result is also a decimal
  • In the operation of taking remainder , Only two integers are allowed to remainder
  • Be sure to put parentheses when taking negative numbers
  • c Language has no power
  • And then the self increasing and self decreasing symbols ++ perhaps --, Putting variables in front is to calculate first and then take values , The latter is to take values first and then calculate
  • How to get the hundredth of a number , Ten and one

  • Hundreds of digits :num/100  You can get , because  int  It's an integer type , The decimal part will be omitted . such as  765/100  The result is 7
  • Ten digits :num%100/10 . such as 765%100 First get 65,65/10 obtain 6
  • Single digit :num%10.765%10 obtain 5

2. Assignment operator

In fact, the assignment operator is from the simplest assignment = At the beginning

+=、-=、*=、/=、%=

These evolved assignment operators , In fact, it is the omission in the assignment process , Because the assignment process is from the right to the left , Therefore, the operation of the preceding symbol is to calculate the variable value on the left and the variable value on the right, and then assign it to the left by being equal to

3. Relational operator

The greatest function of relational operators is to judge

å³ç³»è¿ç符

When you need to pay attention in the process of judgment , The operations omitted in the process of judgment are 1,0 Judge true and false

4. Logical operators

Logic is with , or , Not

And :&&( And in Mathematics )

or :||

Not :!

sentence

Statements are mainly divided into conditional statements and circular statements

Conditional statements

The core of conditional statements is if-else

if( Judgment statement ){
Judge where to execute
}else{
Judge where to execute
}

semantics : If the value of the expression is true , Then execute the code block 1, Otherwise, execute the code block 2;

if Nested statements , The meaning is : If the expression is true , execute , Otherwise, continue to judge , Until it is judged ;

Loop statement

There are three cycles in total :

while loop ;do-while loop ;for loop .

while()
{
Perform the operation
}

while A loop can be understood as : When ( Judge ) It's really a cycle , Otherwise output ;

do-while A loop can be understood as : One step ahead , When ( Judge ), If so, cycle , Otherwise, do not cycle ;

for The loop is divided into three steps ( After the initialization of the variable, make a judgment , If true, cycle , Then increment or decrement the variable , When you know that the judgment statement is false, output the statement

Multiple cycles

In loop nesting

We should first consider parent and child loops, or there are grandchildren , The biggest cycle is one step , The next small step of the cycle will be completed

In loop nesting , The easiest thing we can do is print , Can make nested loops more intuitive

example 1: rectangular

#include<stdio.h>
int main()
{
// 3 That's ok 4 Column rectangle
// The outer loop controls the number of rows
for (int i = 0; i < 3; i++) {
// The inner loop controls the number of columns
for (int j = 0; j < 4; j++) {
printf("*");
}
printf("\n");
}return 0;
}

Run the following

example 2: triangle : The conditional expression of the inner loop follows that of the outer loop i Value change

#include<stdio.h>
int main()
{
/*
Print up to 5 That's ok
Print up to 5 Column
because : Number of columns <= Row number
*/
for(int i = 0; i< 5; i++) {
for(int j = 0; j <= i; j++) {
printf("*");
}
printf("\n");
}return 0;
}

Running results :

If you bring the triangle over : The initialization expression of the inner loop follows that of the outer loop i Value change

The initial value is 0, Cycle five times ,1 Cycle four times , So the initial value increases with i change

#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
printf("*");
}
printf("\n");
}
return 0;
}

  Running results

  Bubble sort

#include <stdio.h>
int a[10];
int cont = 0;
int main() {
// Initialization of an array
for (int i = 0; i < 10; i++) {
printf(" Please enter the first %d digit :", i);
scanf("%d", &a[i]);
}
// Sort
for (int i = 10; i > 0; i--) { // The first cycle is just to control the number of times
for (int j = 0; j < i - 1; j++) {
if (a[j] > a[j + 1]) {
cont = a[j];
a[j] = a[j + 1];
a[j + 1] = cont;
}
}
}
for (int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
}

It should be noted that after the double loop, there is an operation called assignment sorting, which uses variables as an intermediary to sort the size

Perform assignment operation .

Small statement

1.break

break The function of is to jump out of the current cycle , So first break Must exist in the loop , Then the current loop means , In nested statements , Can only jump out of break One of the small loops

2.continue

continue The function of is to end the current cycle and proceed to the next cycle

break Is to jump out of the current whole cycle ,continue Is to end this cycle and start the next cycle .

3.swich-case

switch( expression ){
case Constant expression 1:
sentence 1;
break;
case Constant expression 2:
sentence 2;
break;
case Constant expression n:
sentence n;
break;
default:
sentence n+1;
break;
}

Example :

#include <stdio.h>
int main() {
int num = 3;
switch(num){
case 1:
printf(" Monday \n");
break;
case 2:
printf(" Tuesday \n");
break;
case 3:
printf(" Wednesday \n");
break;
case 4:
printf(" Thursday \n");
break;
case 5:
printf(" Friday \n");
break;
case 6:
printf(" Saturday \n");
break;
case 7:
printf(" Sunday \n");
break;
default:
printf(" Go back to Mars \n");
break;
}
}

Be careful :default It can be omitted , however break Don't omit !!

if and swich The difference between :if The target range is relatively strong ,swich For special values, it has strong pertinence

function

Before that , All our operations are performed in the main function , Input and output , Loop judgment and other operations , Can we build a function ourselves , To simplify the repeated operations in the main function

Self creation of function :

data type   The name of the function ( Shape parameter )

{

      Execute code ;

return expression ;

}

The most important thing to note is that return: The value obtained by executing the program segment in the function body and returned to the calling function .

return It can be followed by an expression to evaluate , It can also be a variable that returns .

Example , front 100 And recursion

#include <stdio.h>
int sum(int n) {
if(n==1){
return n ;
}return n + sum(n - 1);
}
int main() {
printf("%d", sum(100));
return 0;
}

Array

An array is a storage space , Data is stored inside the array , This space is the address of the data

An array is from 0 Start , The first thing to master should be the initialization operation and output of the array

#include <stdio.h>
int main() {
int i, a[10];
for (i = 0; i <= 9; i++)
a[i] = i;
for (i = 9; i >= 0; i--)
printf("%d", a[i]);
return 0;
}

It's routine 0123456789 The inverse output of

We can also assign values to the array and output

int a[10];
for (int i = 0; i < 10; i++) {
printf(" Please enter the first %d digit :", i);
scanf("%d", &a[i]);
}
for (int i = 0; i < 10; i++) {
printf("%d ", a[i]);
}

This operation is to input each item of the array , Then output according to what you write

Be careful : In the process of array definition , It should be noted that , The array length is too long, so use longlong Define an array

Two dimensional array

Two dimensional arrays are similar to one-dimensional arrays , You need two cycles to define

example 1: If you define a two-dimensional array , And input x,y You can find the position of the array ( Because the array defaults from 0 Start , The value of the array subtracts 1 Is the position of the element

#include<stdio.h>
int a[10][10];
int main()
{
int n,m;
printf(" Each row and column is controlled as :");
scanf("%d,%d",&n,&m);
printf(" The two-dimensional array is :\n");
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
int x,y;
printf(" Want to know :\n");
scanf("%d,%d",&x,&y);
printf(" This element is ");
printf("%d",a[x-1][y-1]);
// Array int a[m][n] The element at the maximum range is a[m–1][n–1].
return 0;
}

This string of code first enters a two-dimensional array ( I created an array myself ), Find the position of any item in this array

The pointer

In fact, when I first touched the pointer , One point we've always wondered about is what the pointer is , What exactly does it want to do , Let's slowly uncover the mystery of the pointer !

When we just met c When it comes to language , In fact, the pointer has appeared , Variable , Variables consist of three components : Variable name , Variable values and storage units ( Address ), that , What is? The pointer

  • In a computer, all data is stored in memory cells , Each memory cell has a corresponding address , The data stored in the corresponding unit can be found through this address .

  • Because the required variable unit can be found through the address , So we say that the address points to the variable unit . Visualize the address as “ The pointer ”

Pointer to memory unit ( Address ) And the content of memory unit are two different concepts .

however , Is the address the pointer we usually use ?

In fact, when we use pointers , Pointers also need to be defined —— Pointer to the variable , It's the same as most variables , Is a variable , But in the process of using pointers , What we're talking about is what this pointer points to ( What do you mean ), Actually The pointer variable points to the variable value , What a variable stores is the address that points to the value of the variable

The definition of a pointer variable : The data type pointed to * identifier

int *p

But in the process of writing programs , The problem comes again

* and &

We can understand that ,* Is part of a pointer variable , Table to

                                    Value symbols ( Represents the storage space pointed to by the access pointer )

                                 & It's the address symbol

int a = 5;
int *p = &a;
printf("a = %d", *p); // Access pointer variables

In the process of using , Be sure to assign values to pointer variables , Even if it is Null

int a = 5;
int *p;
p=&a;
int *p=NULL;
int *q=0;

It must be noted that , Pointer variables can only store addresses , Cannot store other ( So we are scanf Missing in the process & There's no mistake , Because it will bring & Use the back of as the address )

Pointers and functions

A function pointer , Its essence is a pointer variable , This pointer points to this function . In conclusion , A function pointer is a pointer to a function .

int (*fun)(int x,int y);

 ( I'm not much of a )

  Pointer variables are function parameters

int swap(int *p1,int *p2)
#include <stdio.h>
void swap(int *p1, int *p2) {
int p;
p = *p1;
*p1 = *p2;
*p2 = p;
}
int main() {
int a, b;
int *c, *d;
scanf("%d,%d", &a, &b);
c = &a;
d = &b;
if (a < b) {
swap(c, d);
}
printf("%d,%d", a, b);
return 0;
}

Pointers and arrays

stay When we study arrays, it's not hard to imagine : When defining an array , We also treat the array as a variable , Array, we have always regarded it as a database to hold data , It's not hard to think of pointers .

How can arrays be represented by pointers ?

Let's first analyze arrays and pointers :int a[i] ( Definition a Is an array containing ten integer array data )

                                                int *p     ( Definition p Is a pointer variable to an integer variable )

                                        if p=&a[0] Will be a[0] The address of the element is given to p( What's the use ?) In fact, when the compiler defines an array a It's the address of the first element

                                              therefore p=a. Is the conversion of array to pointer .

The veil of array is lifted , Is there another method when we define an array :

          We can think of it this way : We will a As the address of the first variable ,i As an offset address, so

int a[i];
// Some compilers don't let this name ,[] Only constants can be written in
int *(a+i);

( You don't need to know , Just remember )a and i Move down ,a=p

And finally , Are arrays exactly the same as pointers ? Even if they all point to the address , But the array is still a string of numbers, and the point is stable , But a pointer is a variable , It can change at any time .

Operate the pointer to print the array !

#include <stdio.h>
int main() {
int a[10];
int i;
int *p;
for (i = 0; i < 10; i++) {
scanf("%d", &a[i]);
}
printf("\n");
for (p = a; p < (a + 10); p++) {
printf("%d", *p);
}
return 0;
}

The liver doesn't move ( Playing games )... Continue tomorrow !!!

Because the content is too simple , I hope the boss can give some advice fan、、

Please bring the original link to reprint ,thank
Similar articles

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25

2021-11-25