[C language] branch statement and loop statement

Posted by Yamakazi on Sat, 05 Feb 2022 12:53:45 +0100

catalogue

1, Branch statement

1. if statement

Grammar

Examples

2. switch statement

grammar

example

2, Circular statement

1. while loop

grammar

example

getchar(),putchar()

2. for loop

grammar

example

3. do... while() loop

grammar

example

1, Branch statement

1. if statement

  • 0 means false, non-0 means true
  • If the result of the expression is true, the statement is executed
  • Grammar

If (expression 1)

Statement 1;

Else if (expression 2)

Statement 2;

else

Statement 3;

  • Examples

//else suspended
#include <stdio.h>
int main()
{
    int a = 0;
    int b = 2;
    if (a == 1)
        if (b == 2)
            printf("hehe\n");
        else                        //else matches the latest if, and the print result is empty
            printf("haha\n");
    return 0;
}
//Exercise 1 judge whether a number is odd
#include <stdio.h>
int main()
{
    int num = 15;
    if (num % 2 == 1)
        printf("Odd number\n");
        
    return 0;
}
//Exercise 2 output odd numbers between 1-100
#include <stdio.h>
int main ()
{
    int i = 1;
    while (i <= 100)
    {
        printf("%d ",i);
        i += 2;
    }
    
    return 0;
}

2. switch statement

  • It is mostly used in the case of many branches
  • The break statement jumps out of the switch statement
  • If there is no break statement, it will be executed downward from the incoming case statement
  • The default statement is an exit to other options, regardless of order
  • grammar

Switch (expression)

{

case constant expression 1: statement sequence 1;

case constant expression 2: statement sequence 2;

default: statement sequence 3;

}

  • example

//Print the week corresponding to the input number
#include <stdio.h>
int main ()
{
    int day = 0;
    scanf("%d", &day);
    switch (day)            //Integer expression
    {
    case 1:                 //integral constant expression 
        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;                                            
    }
    
    return 0;
}
//Function of break statement
#include <stdio.h>
int main ()
{
    int day = 0;
    scanf("%d", &day);
    switch (day)            
    {
    case 1:                 //There are no break s, and they slide down in turn
    case 2:
    case 3:
    case 4:
    case 5:
        printf("weekdays\n");
        break;
    case 6:
    case 7:
        printf("Rest Day\n");   
        break;                                            
    }
    
    return 0;
}
//default clause
#include <stdio.h>
int main ()
{
    int day = 0;
    scanf("%d", &day);
    switch (day)            
    {
    case 1:                 //There are no break s, and they slide down in turn
    case 2:
    case 3:
    case 4:
    case 5:
        printf("weekdays\n");
        break;
    case 6:
    case 7:
        printf("Rest Day\n");   
        break;
    default:                        //Exits for other options, regardless of order
        printf("Input error\n");
        break;                                                        
    }
    
    return 0;
}
//practice
#include <stdio.h>
int main()
{
    int n = 1;
    int m = 2;
    switch (n)                        //n=1, enter from case 1
    {
        case 1:m++;                   //n=1,m=3 
        case 2:n++;                   //n=2,m=3 
        case 3:
            switch (n)                //n=2, enter from case 2
            {
                case 1:n++;
                case 2:n++;m++;       //n=3,m=4 
                    break;            //Jump out of the switch statement                    
            }
        case 4:m++;                   //Enter case 4, n=3, m=5;         
            break;                    //Jump out of the switch statement
        default:
            break;                                                                    
    }
    printf("m = %d, n = %d", m, n);
    
    return 0;
}

2, Circular statement

1. while loop

  • grammar

While (expression)

{

Circular statement;

}

  • example

//Print 1 ~ 10
#include <stdio.h>

int main()
{
    int i = 1;
    while (i <= 10)
    {
        printf("% d ", i);
        i++;
    }

    return 0;
}
  • break and continue statements
  • In a while loop, break permanently terminates the loop
  • In the while loop, continue skips the code behind this loop and directly judges the part to see whether to execute the next loop
#include <stdio.h>
//In a while loop, break permanently terminates the loop
//In the while loop, continue skips the code behind this loop and directly judges the part to see whether to execute the next loop
int main()
{
    int i = 1;
    while (i <= 10)
    {
        if (i == 5)
            break;          

        printf("% d ", i);
        i++;
    }

    return 0;
}
  • getchar(),putchar()

  • int c = getchar() can read in an input character, and the integer variable will contain the ascii code value of the input character
  • putchar(c) can print the contents of integer variable C in the form of characters
  • Entering crtl+z is equivalent to no input, and getchar() returns a special value EOF(end of file to get characters)
  • Reason for not declaring c as a char type: c must be able to store not only any character, but also EOF
  • EOF is defined in. It is an integer number. The specific value is unimportant. It is only different from the values of all char types. The essence is - 1. The ascii value without characters is - 1
  • getchar() will take away the characters in the buffer regardless of the statement order. You should pay attention to clearing the buffer in advance
#include <stdio.h>
//getchar() gets the standard input character
//The ascii code value of the correct returned character is an integer int, and the error returns EOF(end of file flag)
int main()
{
     int ch = getchar();
     //printf("%c\n", ch);
     putchar(ch);//Output a character
     
     return 0;   
}
#include <stdio.h>
int main()
{
    int ch = 0;
    while ((ch = getchar()) != EOF)//The characters obtained are correct
//The essence of EOF is - 1. It is impossible to have this ascii code value
    {
        putchar(ch);    
    }
    //crtl+z -- getchar ends reading, which is equivalent to returning EOF without input
   
    reutrn 0;
}

#define #define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("Please input a password:");
	scanf("%s", password);        //Enter 123456\n,
        //scanf takes 123456, and the rest \ n is taken directly by getchar() without waiting
        getchar();                    //Therefore, a getchar() needs to be preceded to clear the buffer           
	printf("Please confirm the password(Y/N):");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}

	return 0;

}

 

#define #define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("Please input a password:");
	scanf("%s", password);        //Enter 123456 abcd
                                      //scanf() read in 123456  
        int temp = 0;                 //Clear all characters
        while((temp = getchar()) != '\n')
        {
            ;        
        }
                               
	printf("Please confirm the password(Y/N):");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}

	return 0;

}

2. for loop

proposal

  • The loop variable cannot be modified in the for loop body to prevent the for loop from losing control
  • It is suggested that the value of the loop control variable of the for statement should be written in the way of "close before open interval"
  • grammar

For (expression 1; expression 2; expression 3)

{

Circular statement;

}

  • Expression 1: initialization part, used to initialize loop variables
  • Expression 2: condition judgment part, which is used to judge whether the loop is terminated
  • Expression 3: adjustment part, which is used to adjust the loop condition

  • example

#include <stdio.h>
//Print 1 ~ 10
int main()
{
    int i = 0;
    for(i=1; i<=10; i++)
        printf("%d", i);
    
    return 0;
}
//Function of break statement
#include <stdio.h>
int main()
{
    int i = 0;
    for(i=1; i<=10; i++)
    {
        if(i == 5)
            break;
        printf("%d ", i);                    
    }

                                    //Results: 1 2 3 4 
   
    return 0;
}
//Function of continue statement
#include <stdio.h>
int main()
{
    int i = 0;
    for(i=1; i<=10; i++)
    {
        if(i == 5)
            continue;
        printf("%d ", i);                    
    }

                                    //Results: 1 2 3 4 6 7 8 9 10 
   
    return 0;
}
  • Variant 1
  • The judgment part is omitted, and the judgment part is always true
#include <stdio.h>
int main()
{
    //The judgment part is omitted, and the judgment part is always true
    for(;;)
    {
        printf("haha\n");    
    }
                                //haha dead cycle
    return 0;
}
#include <stdio.h>
int main()
{
    int i = 0;
    int j = 0;
    for(; i<3; i++)
    {
         for(; j<3; j++)           //When i=1, j is still = 3, so only 3 haha are printed
         {    
             printf("haha\t");
         }        
    }
                                //haha    haha    haha
    return 0;
}
  • Variant 2
  • There can be multiple judgment conditions
  • The result of judgment part y=0 is false, and the cycle is 0 times
#include <stdio.h>
int main()
{
    int x, y;
    for (x = 0, y = 0; y=0; ++x, y++)
    {
        printf("hehe\n");            //The result of judgment part y=0 is false, and the cycle is 0 times
    }
    
    return 0;
}

3. do... while() loop

  • The loop is executed at least once
  • grammar

do

{

Circular statement;

}While (expression);

  • example

#include <stdio.h>
//Print 1 2 3 4
int main ()
{
    int i = 1;
    do
    {
        if (i == 5)
            break;
        printf("%d ", i);
        i++;    
    } while (i<=10);
    
    return 0;
}

Topics: C