C language notes

Posted by Megahertza on Mon, 31 Jan 2022 07:32:58 +0100

Notes on C language

4. Branching

Between 80 and 90! \n");
case 'C': printf("your score is between 70 and 80! \ n");
case'D ': printf("your score is between 60 and 70! \ n");
case 'F': printf("your score is below 60! \ n");
default: printf("please enter a valid grade \ n");
}
return 0;

}
Please enter score: A
Your score is above 90!
Your score is between 80 and 90!
Your score is between 70 and 80!
Your score is between 60 and 70!
Your score is below 60!
Please enter a valid grade rating

**Think: why do we execute statements we don't need?**

**because switch In a statement case It's just a tag. If you meet this tag, jump to this tag, execute the statement under the tag, and then continue*<font color=red>Go ahead</font>***,Will not jump out of the statement, so you need to add break!

```c
#include <stdio.h>

int main()
{
	int dj;
	
	printf("Please enter a score:");
	scanf("%c", &dj);
	
	switch(dj) 
	{
		case'A': printf("Your score is above 90!\n"); break;
		case'B': printf("Your score is 80~90 between!\n"); break;
		case'C': printf("Your score is 70~80 between!\n"); break;
		case'D': printf("Your score is 60~70 between!\n"); break;
		case'F': printf("Your score is below 60!\n"); break;
		default: printf("Please enter a valid grade rating\n") ; break;//In the end, you don't need to add it here. In order to maintain good programming habits, you still need to add it
	}
	return 0;	
}

Nesting of branch structures

if(expression)
	if(expression)    //Embedded if
		.....
	else
		......
else 
	if(expression)     //Embedded if
		......
	else
		......
		

Write code according to the flow chart

The flow chart uses some frames to represent various operations, which is intuitive and visual .

For example, the above program for judging whether the age is an adult can be drawn as a class: the "Y" and "N" on the left and right of the judgment box represent the two cases where the value of the expression is "true" and "false" respectively.

For another example, the above grade judgment program can be drawn as a class:

Question: what tools do I use to draw the flow chart?

Recommend Microsoft Visio

Examples of exercises:

The program code is:

#include<stdio.h>
int main()
{
    int a,b;
    printf("Please enter two integers:");
    scanf("%d %d",&a,&b);
    if(a!=b)
    {
        if(a>b)
        {
            printf("%d>%d\n",a,b);
        }
        else
        {
            printf("%d<%d\n",a,b);
        }
     
    }
    else
     {
         printf("%d=%d\n",a,b);
     }
    return 0;
}

On bug1 -- hanging else**

Please see a story: Dacheng from Class 3 likes Xiaoshi from class 4 and wants to make an appointment with Xiaoshi to go to Wanda for a movie at the weekend; At this time, there are two questions: is Xiaoshi free that day? Is it suitable to go out on that day in the Yellow calendar?

Obviously, the first problem is the main one, because the second one is too superstitious. We should believe in science!

We write this story as code:

#include<stdio.h>
int main()
{
    char isFree,isGood;
    printf("Are you free?(Y/N)");
    scanf("%c",&isFree);
    
    getchar();//When you enter, the second input value becomes a space! In this case, you need to use getchar(); Filter out the carriage return, otherwise an error will occur!
   
    printf("Is it suitable to go out?(Y/N)");
    scanf("%c",&isGood);
    
    if(isFree=='Y')
    	if(isGood=='N')
    		printf("Please believe in science!\n");
    else
    {
    	printf("I don't have time. I probably don't want to talk to you\n");
	}
    return 0;
}
Output:
Are you free?(Y/N)Y
 Is it suitable to go out?(Y/N)Y
 I don't have time. I probably don't want to talk to you
EMMM Why not when you're free, bug!

This is because the C language has a principle: else matches the if closest to it!

C language regardless of spaces (python spaces are very important), but we still need to form good programming habits and add spaces!

The solution is simple! Just add braces to the first if! So we should add braces whenever we have if in the future!

On the problems caused by bug2 - equal sign

Story continued: next, we need to judge whether Xiaoshi likes Dacheng?

#include<stdio.h>
int main()
{
    char isLike;
    printf("Xiaoshi, do you like Dacheng?(Y/N)");
    scanf("%c",&isLike);
       
    if(isLike='Y') //The '=' sign of the judgment expression is the assignment symbol, and the non-zero value compiler will default to true. We need to change it to the logical symbol '= ='
   {
   	printf("blessing\n");
   }
    else
    {
    	printf("There's still a chance\n");
	}
    return 0;
}
Output:
Xiaoshi, do you like Dacheng?(Y/N)N
 blessing
EMMM Why do you wish if you don't like it, bug!

It's simpler here. In the previous if judgment, the '=' sign of the expression is the assignment symbol, and the compiler will default to true. We need to change it to the logical symbol '= ='

5. Cyclic structure

while statement

while(expression)// If the expression is true, the contents in the loop body will be executed. The loop body can be a single statement or a program block
	Circulatory body

Example 1: calculate the result of 1 + 2 + 3 +... + 100.

Flow chart: [the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ec8cdn8e-1622461797848) (C: \ users \ Dell \ appdata \ roaming \ typora \ typora user images \ image-20200812194438440. PNG)]

Procedure:

#include<stdio.h>
int main()
{
    int i=1,sum=0;
	while(i<=100)
	{
	sum=sum+i;
	i=i+1;	//i + + has the same effect
	 } 
	printf("The result is:%d",sum);
    return 0;
}
i++ \++i == i=i+1
 difference
i++ Return the original value,++i Returns the value after adding 1.
i++ Cannot be an lvalue, and++i sure.
1,First, take it out alone++i and i++,The meaning is the same, that is i=i+1. 
2,If it's an operator, it's a=i++perhaps a=++i Such a form. The situation is different.
    First a=i++,This operation means to put i Value assignment a,Then in execution i=i+1;
    and a=++i,This means to execute first i=i+1,And then put i Value assignment a;
    For example, if at first i=4. Then execute a=i++After this statement, a=4,i=5;Then execute a=++i After this statement, i=5,a=5;Similarly, i--and--i The usage of is the same.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xrc8mx9m-1622461797848) (C: \ users \ Dell \ appdata \ roaming \ typora user images \ image-20200812195251331. PNG)]

Example 2: count the number of characters of a line of English sentence input from the keyboard (cycle once, times plus 1)

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-juk9jaku-1622461797848) (C: \ users \ Dell \ appdata \ roaming \ typora user images \ image-20200812195803029. PNG)]

getchar function

The getchar function gets the next character from the standard input stream (stdin).

This is equivalent to calling the getc(stdin) function.

#include <stdio.h>
...
int getchar()(void);

If the function call is successful, the obtained character is returned (its ASCII code is represented by integer).

If the return value is EOF, it indicates that the function call failed:

  • If the standard input stream is at the end position, the function returns EOF and sets the end flag of the standard input stream.
  • If there are other errors, the function also returns EOF and sets the error flag instead.

program

#include <stdio.h>

int main()
{
        int count = 0; //Initialize to 0

        printf("Please feel free to an English sentence:");

        while (getchar() != '\n') //As long as it is not carriage return, it is not the end until carriage return (line feed) stops the cycle
        {
                count = count + 1;
        }

        printf("You entered a total of%d Characters!\n", count);

        return 0;
}
Output:
Please feel free to an English sentence: I LOVE YOU
 You have entered a total of 10 characters!
//Spaces are also characters

do... while statement

do
	Circulatory body
while(expression);

If we compare the while statement to a cautious young man, then the do... While statement is a reckless man.

Because while is to judge the expression first. If the expression result is true, the contents in the loop body will be executed;

On the contrary, do... while, regardless of three, seven and twenty-one, first execute the contents of the loop body, and then judge whether the expression is true.

Note: do... While statements must use semicolons (;) after while Indicates the end of the statement.

It can be seen that when we need to verify that the password is correct, there is a do... whlie statement. We only need to write and enter the password once

#include<stdio.h>
int main()
{
    int i=1,sum=0;
	do
	{
	sum=sum+i;
	i=i+1;	//i + + has the same effect
	 } 
	while(i<=100);
	printf("The result is:%d",sum);
    return 0;
}

The while statement judges the expression at the entry, so it becomes an entry condition loop; The do... While statement judges the expression at the exit, so it becomes an exit condition loop; No matter whether the index expression is valid or not, the do... While loop body will be looped once

Basic structure of circulating body

int count=0;//Initialize counter
while(count<10)//Cycle condition
{
	printf("xxxx\n");
	count=count+1;  //count++;   Update counter
}

These three actions are scattered in different parts. If only they could be concentrated in the same place, then we have a for loop

for loop statement

for(Expression 1; Expression 2; Expression 3)
    /*Expression 1 is a loop initialization expression; Expression 2 is a circular judgment expression; Expression 3 is a loop adjustment expression*/
	Circulatory body
#include<stdio.h>
int main()
{
	int i,sum;
    for(i=1,sum=0;i<=100;i++)//Two expressions in the expression are separated by commas
    {
    	sum=sum+i;
	}	
	printf("The result is:%d",sum);
    return 0;
}

Exercise example: judge whether a number is a prime number. (a prime number is a natural number greater than 1, excluding 1 and a number that cannot be divided by other natural numbers)

#include<stdio.h>
int main()
{
	int i,num; 
	_Bool flag=1;//Use Boolean type to judge whether it can be divided by the number of 1 and itself
	printf("Please enter an integer:");
	scanf("%d",&num); 
    for(i=2;i<=num/2;i++) // Just num/2 here 
    {
    	if(num%i==0)
    	{
    		flag=0;	//If it can be divisible, the value is 0			
		}
	}
	if(flag)//If it is expressed as 1, it cannot be divided by whole, so it is a prime number 
	{
		printf("%d It's a prime\n",num);
		}	
	else{
		printf("%d Not prime\n",num);
	}
    return 0;
}

Flexible for statement

Expression 1, expression 2 and expression 3 can be omitted as needed (semicolon cannot be omitted)

for(Expression 1;Expression 2;Expression 3)
for(;Expression 2;Expression 3)
for(Expression 1;;Expression 3)
for(;;Expression 3)
for(;;)//Represents a cycle that is always true. Dead cycle
.........

loop nesting

Execute the inner loop first and then the outer loop

#include<stdio.h>
int main()
{
	int i,j;
    for(i=0;i<3;i++)
    {
    	for(j=0;j<3;j++)
    	{
    		printf("i=%d,j=%d\n",i,j);
		}
	}	
    return 0;
}
Output:
i=0,j=0
i=0,j=1
i=0,j=2
i=1,j=0
i=1,j=1
i=1,j=2
i=2,j=0
i=2,j=1
i=2,j=2

Practice example, print 99 multiplication table

#include<stdio.h>
int main()
{
	int i,j;
    for(i=1;i<=9;i++)
    {
    	for(j=1;j<=i;j++)
    	{
    		printf("%d*%d=%-2d  ",i,j,i*j);//%-2d means to align left in the form of two digits. To align right is% 2d
		}
		putchar('\n');//The inner loop determines the line and needs to wrap 
	}	
    return 0;
}
Output:
1*1=1
2*1=2   2*2=4
3*1=3   3*2=6   3*3=9
4*1=4   4*2=8   4*3=12  4*4=16
5*1=5   5*2=10  5*3=15  5*4=20  5*5=25
6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36
7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49
8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64
9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81

break statement

Jump out of loop

#include<stdio.h>
int main()
{
	long long i,num;//Use long long to test large numbers 
	_Bool flag=1;
	printf("Please enter an integer:");
	scanf("%d",&num); 
    for(i=2;i<=num/2;i++) // Just num/2 here 
    {
    	if(num%i==0)
    	{
    		flag=0;	//If it can be divisible, the value is 0	
			break;	//As long as it can be divided by 2, it must not be prime, so jump out of the loop	
		}
	}
	if(flag)//If it is expressed as 1, it cannot be divided by whole, so it is a prime number 
	{
		printf("%lld It's a prime\n",num);//longlong corresponds to% lld
		}	
	else{
		printf("%lld Not prime\n",num);
	}
    printf("i=%lld\n",i);//View cycle count
    return 0;
}
Please enter an integer: 100000000
100000000 Not prime
 It will be much faster than before (because now cpu Great, I can't see the difference)

continue Statement

When a certain condition is met, jump out of the current cycle and enter the next cycle

And break is to jump out of the whole cycle!

#include<stdio.h>
int main()
{
	int ch;
	while((ch=getchar())!='\n')//Judge the input until the loop ends when the input is wrapped
	{
		if(ch=='C')//Ignore characters with C entered by the user 
		{
			continue;
		}
		putchar(ch);//If there is a C, this operation will not be executed, and directly enter the next cycle to obtain the next character 
	}
	putchar('\n');

    return 0;
}
output
I LOVE CAT AND DOG
I LOVE AT AND DOG
#include<stdio.h>
int main()
{
	int i;
	for(i=0;i<100;i++)
	{
		if(i%2)//If it cannot be divided by 2 (non-zero), it will jump out of this cycle
		{
			continue;
		}
		printf("%d\n",i);//Finally, we get all the numbers that can be divided by 2 by 0 ~ 100
	 } 

    return 0;
}

The above example is changed to a while loop

#include<stdio.h>
int main()
{
	int i=-1;//Since the program starts with i plus 1, start with - 1
	while(i<100)
	{
		i++;//It must be placed in front of if. If 1% 2 is not 0, the + 1 operation will not be executed, and the program will fall into an endless loop
		if(i%2)
		{		
			continue;
		}
	printf("%d\n",i); 
	}				
    return 0;
}

You can see that for and while are different!

6. Knowledge point filling

Assignment operator '='

.....
int a;
....
a=5;//The left side of the assignment operator must be an lvalue, and the variable name is lvalue
.....

Lvalue (lvalue)

The name lvalue did originally come from E1 = E2 (E1 is the changeable lvalue). But a more reasonable explanation should be to understand lvalue as locator value, and rvalue should be value of an expression.

Therefore, it is not comprehensive to simply use left value and right value.

lvalue is an identifier used to identify or locate the storage location

#include <stdio.h>
int main()
{
        int a = 5;
        ++(a++);
        return 0;
}
Code error, bug!

(a + +) returns the value of variable a (5) as the value of the whole expression, and then increases a by 1 (similar to a = a + 1).

So here + + (a + +); Equivalent to + + (5), a = a + 1;

Of course, you should make a mistake. 5 is a constant. Of course, you can't get 5 = 5 + 1~

Compound operator

a += 1;     a=a+1
a -= 2;		a=a-2
a += 3;		a=a+3
a /= 4;		a=a/4
a %= 5;		a=a%5

Self increasing and self decreasing operator

When we need to add or subtract a variable and assign it to ourselves, we can write it in the form of i + +, i - or + + i, - i.

They are also called increment decrement operators, or + +, -- operators.

Their differences are:

  • i + + first uses the value saved in variable i, and then performs + + operation on itself;
  • ++i is to perform + + operation on itself first, and then use the value of variable i (at this time, the value of variable i has been increased by 1).

In addition, self increasing and self decreasing operators can only act on variables, not constants or representations.

#include<stdio.h>
int main()
{
	int i=5,j;
	j=i++;//First assign the value 5 of i to j, and then add 1 to i itself
	printf("i=%d,j=%d\n",i,j);
	
	i=5;
	j=++i;//First add 1 to the value of i to 6, and then add 1
	printf("i=%d,j=%d\n",i,j);				
    return 0;
}
output
i=6,j=5
i=6,j=6

Comma Operator

The syntax of comma expression is: expression 1, expression 2, expression 3,..., expression n

  • The operation process of comma expression is: calculate the expression one by one from left to right;
  • Comma expression as a whole, its value is the value of the last expression (that is, expression n).

However, the comma operator has the least status among all operators in C language.

Because even the assignment operator has higher priority than the comma operator, so

a = 3, 5 ; 
/*amount to*/
a=3;
5;

Example analysis

a=(b=3,(c=b+4)+5)
/*First assign variable b to 3;
Then, the variable c is assigned the sum of b+4, that is, 7;
Next, add the value of c + 5;
Finally assigned to a, so the value of a is 12*/

Note: commas seen in C language are not necessarily comma operators, because in some places, commas are only used as separators.

int a, b, c; 
scanf("%d%d%d", &a, &b, &c); 
/* Commas are used here as separators, not operators.  */

Conditional operator

An operator with one operand is called a unary operator, and two operands are called a binocular operator. However, C language also has a unique unary operator, which is used to provide a simplified way to represent if else statements.

Syntax: Exp1? exp2 : exp3;

exp1 is a conditional expression. If the result is true, exp2 is returned. If false, exp3 is returned

if (a > b)
{
    max = a;
}
else
{
    max = b;
}
/*amount to*/
max = a > b ? a : b;

goto statement**

Goto statement can be said to be a historical legacy, because the early programming languages have left many traces of assembly language. For example, goto statement is one of them.

The function of goto statement is to jump directly to the position of the specified label.

Syntax: goto tag;

The label needs to be positioned at the front of a statement, such as:

#include <stdio.h>
int main()
{
        int i = 5;
        while (i++)
        {
                if (i > 10)
                {
                        goto Label;//When I > 10, jump out of the loop and jump to the Label
                }
        }
Label:  printf("Here, i = %d\n", i);
        return 0;
}

Important: try to avoid using goto statements in development. In fact, even the authors of C language think that goto statement is very easy to be abused, and suggest that it must be used carefully, or even not at all.

But in one case, the use of goto statements is excusable, that is, when facing the need to jump out of multi-layer loops, the use of goto statements is better than multiple break statements.

notes

There are two ways to annotate C language. One is commonly used. Write the annotation after two consecutive slashes:

// This is a comment that the compiler will ignore

/*  This is a comment
	Applicable to multiple lines*/

, not necessarily all comma operators, because in some places, commas are just used as separators**

int a, b, c; 
scanf("%d%d%d", &a, &b, &c); 
/* Commas are used here as separators, not operators.  */

Conditional operator

An operator with one operand is called a unary operator, and two operands are called a binocular operator. However, C language also has a unique unary operator, which is used to provide a simplified way to represent if else statements.

Syntax: Exp1? exp2 : exp3;

exp1 is a conditional expression. If the result is true, exp2 is returned. If false, exp3 is returned

if (a > b)
{
    max = a;
}
else
{
    max = b;
}
/*amount to*/
max = a > b ? a : b;

goto statement**

Goto statement can be said to be a historical legacy, because the early programming languages have left many traces of assembly language. For example, goto statement is one of them.

The function of goto statement is to jump directly to the position of the specified label.

Syntax: goto tag;

The label needs to be positioned at the front of a statement, such as:

#include <stdio.h>
int main()
{
        int i = 5;
        while (i++)
        {
                if (i > 10)
                {
                        goto Label;//When I > 10, jump out of the loop and jump to the Label
                }
        }
Label:  printf("Here, i = %d\n", i);
        return 0;
}

Important: try to avoid using goto statements in development. In fact, even the authors of C language think that goto statement is very easy to be abused, and suggest that it must be used carefully, or even not at all.

But in one case, the use of goto statements is excusable, that is, when facing the need to jump out of multi-layer loops, the use of goto statements is better than multiple break statements.

notes

There are two ways to annotate C language. One is commonly used. Write the annotation after two consecutive slashes:

// This is a comment that the compiler will ignore

/*  This is a comment
	Applicable to multiple lines*/

Topics: C Programming