Learning C Language: Part Four

1. Branch Control Statements

1.2 switch..case Statement

1.2.1 Format

switch(expression){    case constant_expression1:        code_block1;        break;    case constant_expression2:        code_block2;        break;    case constant_expressionn:        code_blockn;        break;    default:        other_branch;        break;}

1.2.2 Notes

1. The expression is generally a variable, which can also be a variable expression, and the constant expressions after case represent all possible values of this variable;

2. The constant expressions after case can be of character type or integer type, but cannot be floating-point type;

3. The default branch serves to enter the default branch if none of the previous cases are satisfied, similar to the else branch in an if..else statement; it can be omitted if not needed;

4. The role of break is to indicate that after executing a certain branch’s code block, it immediately exits the entire switch..case statement. If break is not added, the program will continue to execute the code blocks of the following cases until it encounters a break or the entire switch..case statement ends;

Example:

#include <stdio.h>
int main(int argc, const char *argv[]){
	printf("----proc start-----\n");
	int value = 0;
	scanf("%d", &value);
	/*
	if(10 == value){
		printf("------10-----\n");
	}else if(20 == value){
		printf("------20-----\n");
	}else if(30 == value){
		printf("------30-----\n");
	}else{
		printf("--------other-----\n");
	}
	*/
switch(value){
		case 10:
			printf("######  10  #####\n");
			break;
		case 20:
			printf("######  20  #####\n");
			break;
		case 30:
			printf("######  30  #####\n");
			break;
		default:
			printf("####### other ######\n");
			break;
	}
	printf("----proc end-----\n");
	return 0;
}

Exercise:

Write a program to implement a simple calculator function. Only integer + – * operations are required.

Terminal input: left operand operator right operand scanf(“%d %c %d”);

Output the calculated result.

#include <stdio.h>
int main(int argc, const char *argv[]){
	int lift=0, right=0, result=0;
	char operator;
	scanf("%d %c %d",&lift,&operator,&right);
switch(operator){
		case '+':
			result = lift + right;
			break;
		case '-':
			result = lift - right;
			break;
		case '*':
			result = lift * right;
			break;
		default:
			printf("Input error, only + - * operations are supported\n");
			return -1;
	}
	printf("%d  %c  %d  =  %d\n", lift, operator, right, result);
	return 0;
}

2. Implement the previous student grade management program using switch..case statement once;

#include <stdio.h>
int main(int argc, const char *argv[]){
	int score = 0;
	scanf("%d", &score);
switch(score/10){
		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("Fail\n");
			break;
	}
	return 0;
}

2. Loop Control Statements

2.1 Using goto to Implement Loops

The goto statement is originally used for code jumps and can only implement jumps within the same function.

Because the goto syntax has a certain impact on the readability and logic of the program, it should be used with caution.

Format:

code_block1;goto NEXT;code_block2;NEXT:code_block3;

Execution flow: First execute code_block1, then immediately jump to the corresponding label to execute code_block3 after goto,

the intermediate code_block2 will be skipped and not executed.

Note: Labels can have multiple names, and label names are identifiers that must comply with naming conventions (generally, label names are uppercase)

Example:

#include <stdio.h>
int main(int argc, const char *argv[]){
	printf("111111111111111111\n");
	goto NEXT;
	printf("222222222222222222\n");//not output
	printf("333333333333333333\n");//not output
	printf("444444444444444444\n");//not output
	printf("555555555555555555\n");//not output
NEXT:
	printf("666666666666666666\n");
	return 0;
}

Using goto to implement loops:

The loops we use generally have an end condition; otherwise, it is an infinite loop.

#include <stdio.h>
int main(int argc, const char *argv[]){
	int i = 0;
	printf("111111111111111111\n");
LOOP:
	i++; // The loop must have a statement that can change the end condition; otherwise, it will be an infinite loop.
	printf("222222222222222222\n");
	if(i<5){
		goto LOOP;
	}
	printf("333333333333333333\n");
	return 0;
}

Exercise:

Write a program to sum the numbers from 1 to 100 using a loop.

// Idea
int sum = 0;
sum = sum + 1;
sum = sum + 2;
...
sum = sum + 100;
printf("%d\n", sum);
// Conversion
int sum = 0;
int i = 1;
sum = sum + i;
i++;
sum = sum + i;
i++;
...
sum = sum + i; // i == 100, add it in, sum stores the sum from 1 to 100.
i++;
printf("%d\n", sum);
// Further conversion
int sum = 0;
int i = 1;
LOOP:
sum = sum + i;
i++;
if(i<=100){   goto LOOP; }
printf("%d\n", sum);

As long as the syntax and brackets are correct, you can enter gg=G in command line mode to auto-indent.

2.2 while Loop

Format:

while(expression){    //code_block}

Execution logic:

First execute the expression; if the result of the expression is true, execute the code block, then execute the expression again

If it is still true, continue executing the code block,

Until the expression is false, the loop immediately ends, and the code after the loop continues to execute

The usage of the expression is the same as that in the if statement.

Note: The code block generally needs to have a statement that can change the result of the expression; otherwise, it may cause an infinite loop.

For example:

#include <stdio.h>
int main(int argc, const char *argv[]){
	printf("---start---\n");
	int i = 0; // Generally, loop variables are named i, j, k
	while(i<5){
		printf("hello world\n");
		i++;   // The loop body must have a statement that can change the loop end condition.
	}
	// Code not enclosed by {} is not affected by the loop.
	printf("---end---\n");
	return 0;
}

Exercise:

Use a while loop to sum the numbers from 1 to 100.

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

The monkey eating peach problem: Use a while loop to implement

The monkey picked some peaches on the first day,

immediately ate half of the peaches, and still wanted more, so he ate one more,

On the second day, he ate half of the remaining peaches and still wanted more, so he ate one more,

and so on every day,

Until on the tenth day, when he wanted to eat peaches, he found that there was only one peach left.

Question: How many peaches did the monkey pick on the first day?

Day 10:  1
Day 9:  4   (1+1)*2
Day 8:  10  (4+1)*2
Day 7:  22  (10+1)*2
...
num = (num+1)*2; // This is the statement we need to execute in a loop.
// Answer
#include <stdio.h>
int main(){
     int num = 1; // num stores the number of peaches
     int i = 0; // Control variable for days
     while(i<9){
         num = (num+1)*2;
         i++;
     }
     // When the loop ends, num stores the number of peaches picked on the first day.
     printf("num = %d\n", num);
    return 0;
}

Also output the number of remaining peaches each day:

On day 10, there are xx peaches;

….

On day 1, there are xx peaches;

#include <stdio.h>
int main(){
	int num = 1;
	int i = 0;
	while(i<9){
		printf("On day %2d, there are %4d peaches\n", 10-i, num);
		num = (num+1)*2;
		i++;
	}
	printf("On day %2d, there are %4d peaches\n", 10-i, num);
	return 0;
}

2.3 do..while Loop

Format:

do{    code_block;}while(expression);

Execution logic:

First execute the code block, then execute the expression; if the expression is true, continue executing the code block,

and so on, until the expression is false, the loop immediately ends.

The difference from while:

while checks first, then executes

do..while executes first, then checks

In other words, for do..while, regardless of whether the expression is true, its code block is executed at least once.

For example:

#include <stdio.h>
int main(int argc, const char *argv[]){
	int sum = 0;
	int i = 1;
do{
		sum+=i;
		i++;
}while(i<=100); // Note: Don't forget the semicolon here.
	printf("sum = %d\n", sum);
	return 0;
}

2.4 for Loop

Format:

for(expression1; expression2; expression3){    code_block}

Execution logic:

First execute expression1, then execute expression2; if expression2 is true, execute the code block, then execute

expression3, and then execute expression2 again; if still true, continue executing the code block and expression3,

until expression2 is false, the loop immediately ends.

Expression1: executed only once, generally used to assign an initial value to the loop variable;

Expression2: same as the expression in while, generally used to judge true or false;

Expression3: generally used to change the value of the loop variable, thus controlling the number of times the loop executes; e.g., i++

Example:

#include <stdio.h>
int main(int argc, const char *argv[]){
	printf("----start---\n");
	int i = 0;
	for(i = 0; i < 5; i++){
		printf("hello world\n");
	}
	printf("----end---\n");
	return 0;
}

Exercise:

Use a for loop to sum the numbers from 1 to 100.

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

2. Output all Armstrong numbers in the range (100, 1000).

Armstrong number: unit*unit*unit + ten*ten*ten + hundred*hundred*hundred == itself

For example: 153 == 1*1*1 + 5*5*5 + 3*3*3 == 1 + 125 + 27 == 153

#include <stdio.h>
int main(int argc, const char *argv[]){
	int g = 0;
	int s = 0;
	int b = 0;
	int num = 0;
	for(num = 101; num < 1000; num++){
		// In the loop, each time num changes,
		// so num can represent 101-999.
		g = num % 10;
		s = num / 10 % 10;
		b = num / 100;
		if(g*g*g + s*s*s + b*b*b == num){
			printf("Armstrong number: %d\n", num);
		}
	}
	return 0;
}

C Language Functions for Calculating Powers and Square Roots

When compiling, you need to add the compilation option -lm to link the math library

pow

#include <math.h>

double pow(double x, double y);

Function: Calculates x raised to the power of y

Return value: the result of the calculation

sqrt

#include <math.h>

double sqrt(double x);

Function: Calculates the non-negative square root of x

Return value: the result of the calculation

#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[]){
	double ret1 = pow(5, 3);
	printf("ret1 = %lf\n", ret1);//125
	double ret2 = sqrt(16);
	printf("ret2 = %lf\n", ret2);//4
	return 0;
}

Exercise:

Write a program using loops to output the following pattern.

F_FE__FED___FEDC____FEDCB_____FEDCBA

Answer:

#include <stdio.h>
int main(int argc, const char *argv[]){
	int i = 0;
	int j = 0;
	char value = 'F';
	// Outer loop to control the number of lines printed
	for(i = 0; i < 6; i++){
		// Control the number of underscores printed on each line
		for(j = 0; j < i; j++){
			printf("_");
		}
		value = 'F'; // Start printing from F on each line
		// Control the characters printed on each line
		for(j = 0; j <= i; j++){
			printf("%c", value);
			value--;
		}
		putchar(10);
	}
	return 0;
}

2.5 Infinite Loops

while(1){

// Loop body

}

for(;;){ // Note: For for loops, if any expression is not needed, it can be omitted, but the semicolon must be written

// Loop body

}

2.6 Auxiliary Control Keywords

break

break can be used in switch..case statements to end the entire switch..case statement

break can also be used in loops to immediately end the current loop.

Using break elsewhere will result in an error.

continue

continue can only be used in loops to immediately end the current iteration of the loop.

return

return is originally used in functions to indicate the end of the function and return the result of the function’s execution.

If used in the main function, it indicates the end of the entire program.

#include <stdio.h>
int main(int argc, const char *argv[]){
	int i = 0;
	int j = 0;
	for(i = 1; i <= 5; i++){
		for(j = 1; j <= 5; j++){
			if(3 == j){
				//break;
				//continue;
				return 0;
			}
			printf("%d--%d\n", i, j);
		}
	}
	return 0;
}

3. Comprehensive Exercises on Control Statements

1. Input a number and output all factors of this number

For example: Input 12, output: 1 2 3 4 6 12

#include <stdio.h>
int main(int argc, const char *argv[]){
	int num = 0;
	scanf("%d", &num);
	int i = 0;
	for(i = 1; i <= num; i++){
		if(num%i == 0){
			printf("%d\n", i);
		}
	}
	return 0;
}

Leave a Comment