c language tutorial 1. branch and loop

Now is a detailed tutorial for each part of the C language. I have already explained some basic content in the C language summary. So I will start from the branch and loop to talk about the
C language structure:
1. Sequence structure
2. Select structure
3. Cyclic structure

Select structure:

Branch statement and loop statement:

In C language, separated by a semicolon is a statement
branch statement (select structure)

Structure of if statement:

1. if (expression)
statement; //expression is true, execute statement
2. if (expression)
statement 1;
else
statement 2; //expression is true, statement 1, false, statement 2
3. Multiple branches
.if (expression 1)
statement 1;
else if (expression 2)
statement 2;
else
statement 3; //1 true 1, 2 true 2, all false 3
examples:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
    
    
        int age;
               printf("please input your age\n");
               scanf("%d", &age);
        if (age < 18)
               printf("未成年\n");
        else if (age >= 18 && age < 28)//&&为“和”
               printf("青年\n");
        else if (age >= 28 && age < 50)
               printf("壮年\n");
        else if (age >= 50 && age < 90)
               printf("老年\n");
        else
               printf("老不死\n");
        return 0;
}

Here is a common dangling else problem.
There is such a problem here.
Insert picture description here
What will the code output?
In fact, else matches
the nearest if . The first if did not go in (determined as an error), so nothing will be printed. When
using the if statement, be sure to pay attention to this problem
when writing conditions at the same time: one = for assignment, two == To judge equal .
This is also a common mistake made by novices

switch statement

(Only an integer can be defined) For
multi-branch projects,
case decides the entry, break decides the exit. For
example:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
    
    
        int day;
               scanf("%d", &day);
               switch (day)     
               {
    
    
               case 1:
                       printf("星期1\n");
                       break;
               case 2:
                       printf("星期2\n");
                       break;
               case 3:
                       printf("星期3\n");
                       break;
               case 4:
                       printf("星期4\n");
                       break;
               case 5:
                       printf("星期5\n");
                       break;
               case 6:
                       printf("星期6\n");
                       break;
               case 7:
                       printf("星期日\n");
                       break;
               
               }
               return 0;
}

If there is no break in the middle, it will run down all the time.
Yes: case 1:
case 2:
case 3:
case 4:
case 5:
printf("working day\n");
break;
It is best to add break
and default to the last case to prevent The occurrence of events outside the case
Let’s look at an example:
Insert picture description here
You can think about m, what is the output of
n m=5 n=3

while loop

If the condition is true -> execute-return to the condition-the condition is true............ the condition is false-end You
can use if......break in while,
such as:

while(i<=10{
    
    
            if(i==5) ;
               break;
            printf("%d",1):
            i++;
}

Can only output 1234. If you encounter a break, you can jump out of continue to end the current loop and return to the condition

getchar-input a character and return (to be input)
putchar-output

Example:

int ch =0;
       while ((ch=getchar())!=EOF)
             {
    
    
                    putchar(ch);
              }

If you enter EOF, you can think about whether it will output EOF.
You may think that the while loop can’t enter, and nothing can be output.
In fact, the computer recognizes one by one. E, then O and then F. A single character is definitely not equal to EOF. The string
will therefore enter the loop and output EOF
(EOF–end of file).
Next,
Insert picture description here
let ’s talk about a very difficult example. Getchat and scanf are input functions.
Accept data and put it in the input buffer.
Getchar gets the rest of the buffer. Enter (\n) to go to the else output failed.
Please confirm the previous line and add a getchar() to take the carriage return,
but if the password is 12345 asdf, it will fail again.
Because the first getchar reads only spaces,
add a loop instead. The above getchar is fine

int ch
while((ch=getchar())!=‘\n’)//一直拿到回车
{
    
    
  ..........(上述题中的代码)
    } 

(This question is more difficult for beginners. It is put here to let everyone experience computer thinking. If you still don’t understand after reading the explanation carefully, you can ask your question in the comment area)

for loop

(The most used)
syntax:
for (expression 1; expression 2; expression 3)
loop statement;
*
expression 1-initialize loop variables (initialization part)
*
expression 2-determine when the loop ends (conditional judgment part) )
*
Expression 3-adjustment of loop conditions (adjustment part)

If the loop is too complicated, the initialization, judgment, and adjustment of the while loop are too far apart and inconvenient, so use the for loop
eg: Use the for loop to print 1-10

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

Schematic diagram of for loop:
Insert picture description here
Note: 1. Don't change the variable in the for loop, and put it in the for loop to lose control (pay special attention to the difference between judging equality and assignment)
2. It is recommended that the value of the for loop control variable adopts the writing method of "open before closed and open interval" (Wait before and after) ---- more meaningful
3. If the judgment condition part of the for loop is omitted, the condition is always true, and the loop will not stop! (It is recommended not to omit casually) After initialization is omitted, it will start from 0 by default

do...while loop

Example:

int i=1
do
{
    
    
printf("%d",1);
i++;
}

while(i<=10);//适用范围

retrun 0;

The process is as shown in the figure.
Insert picture description here
Next, there will be a few exercises using loops, and the answers will be released together. Novices are advised to write them by themselves and then see the difference with the answers.

Exercise

1. Calculate the factorial of n (without considering overflow)
2. Find a specific number n in the ordered array, write int binsearch (int x, int v[], int n); function: in v[0]< =v[1]<=v[2]<=…<=Find x in the array of v[n-1].
3. Write code to demonstrate that multiple characters converge from both sides to the middle
4. Simulate user login, enter the password, and enter up to three times

answer

1.Insert picture description here

  • Simple version:
#include<stdio.h>
int main()
{
    
    
        int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
        int k = 7;
        //写一个代码,在arr数组(有序的)中找到7
        int i = 0;
        int sz = sizeof(arr) / sizeof(arr[0]);
        for (i = 0; i < sz; i++)
        {
    
    
               if (k == arr[i])
               {
    
    
                       printf("找到了,下标是;%d\n", i);
                       break;
               }
        }
        if (i == sz)
               printf("找不到\n");
        return 0;
}
  • Half (two points) search algorithm

Find log2n times at most

#include<stdio.h>
int main()
{
    
    
        int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
        int k = 7;
        int sz = sizeof(arr) / sizeof(arr[0]);//计算元素个数
        int left = 0;//定义左下标
        int right = sz - 1;//定义右下标
        
        while (left<=right)
        {
    
    
               int mid = (left + right) / 2;
               if (arr[mid] > k)
               {
    
    
                       right = mid - 1;
               }
               else if (arr[mid] < k)
               {
    
    
                       left = mid + 1;
               }
               else
               {
    
    
                       printf("找到了,下标是:%d\n", mid);
                       break;
               }
        }
        if(left>right)
        {
    
    
               printf("找不到\n");
        }
        return 0;
}

3,

#include<stdio.h>
#include<string.h>
#include<CoreWindow.h>//sleep 的声明
#include<stdlib.h>//system的声明
int main()
{
    
    
        char arr1[] = "welcome to china!!!!!";
        char arr2[] = "#####################";
        int left = 0;
        //int right = sizeof(arr1) / sizeof(arr1[0]) - 2;//算上\0所以减2
        int right = strlen(arr1) - 1;//strlen为计算数组中元素个数的函数,更简便
        while (left <= right)
        {
    
    
               arr2[left] = arr1[left];
               arr2[right] = arr1[right];
               printf("%s\n", arr2);
               Sleep(1000);//间隔1000毫秒
               system("cls");//执行系统命令的一个函数-cls-清空屏幕"cls"
               left++;
               right--;
        }
        return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>//strcmp的库函数
int main()
{
    
    
        int i = 0;
        char password[20] = {
    
     0 };
        for (i = 0; i < 3; i++)
        {
    
    
               printf("请输入你的密码");
               scanf("%s", password);//输入字符串
               if (strcmp(password , "123456")==0)//等号不能用来判断两个字符串是否相等,应用“strcmp”函数来判断
               {
    
    
                       printf("登陆成功\n");
                       break;
               }
               else
               {
    
    
                       printf("密码错误\n");
               }
        }
        if (i == 3)
               printf("三次密码均错误,请退出");
        return 0;
}

Students who feel helpful can click a small like to support it~~

Guess you like

Origin blog.csdn.net/qq_54119007/article/details/115205779