当前位置:网站首页>20210807 1 c language program structure
20210807 1 c language program structure
2022-07-26 10:44:00 【ZhuMou】
One .C Language program structure
C Three kinds of program structure of language : Sequential structure , Selection structure ( Branching structure ), Loop structure .
Several important concepts related to program structure : expression , sentence , Code block .
In short ,C Use semicolons in languages (;) Separated by a sentence , and C The statement between braces in language is Code block .
and expression The concept of is more complex : In terms of composition , For operators and operands ; In terms of function , To produce side effect( side effect ) And evaluation ( Every expression must have a value ,void It is also a type of value ).
See C Expressions of basic concepts of language _astrotycoon-CSDN Blog _c Language expressions
What needs to be emphasized is ,print() Such function calls are also expression,() Is a function call operator , and print It's the operands .
Two . Selection structure
1.if sentence
//if Three common uses of
if(expression1){
block1;
}
or
if(expression1)
statement1;
if(expression1){
block1;
}
else{
block2;
}
if(expression1){
block1;
}
else if(expression2){
block2;
}
else if(expression3){
block3;
}
else{
block4;
}About if……else…… In the use if and else Corresponding :
First ,if There can be no else With the corresponding ;
secondly ,else There must be corresponding if.
So we consider how to find and else Corresponding if. The principle is : find else On , same block The most recent if.
About if……else…… It is considered a sentence :
if,else,for,while,do If you don't add {}, You can only add a single statement, Instead of block. In the nested if……else…… In the sentence ,else There is no own {}, Then you can put if……else…… sentence . This explanation ,if……else…… It is considered as a sentence here . Use for It can also be proved that .
// prove if else Will be considered as a statement
#include <stdio.h>
int main() {
// utilize if prove
if (1)
if (0)
printf("if\n");
else
printf("else\n");
// utilize for prove
for (int i = 0; i < 10; ++i)
if (i > 5) printf("if\n");
else printf("else\n");
return 0;
}2.switch sentence
switch( Integer expression ){
case Integral constant expression 1:
block1;
case Integral constant expression 2:
block2;
case Integral constant expression 3:
block3;
......
//default Not required , But the suggestions are , To handle exceptional situations
default:
block4;
}switch Statement is used to handle multi branch logic ,case It's different block Entrance , and break It's the exit . That is, once you enter a certain case, The program will execute all the subsequent code , until break until . So in switch in ,break The role of is : Jump out of switch sentence .
default Location and case There are no strict regulations on the location of , however default It is suggested to put it at the end .default It's not necessary either , But the suggestions are , To deal with case Other than that .
switch If there is no loop in the statement , There can be no continue Of .
3、 ... and . Loop structure
1.while sentence
while(expr1){
block1;
}
or
while(expr1)
statement1;while The implementation logic of the statement is as follows .

break The function in a circular statement is : Exit the current cycle , Often used in conjunction with judgement sentences .
continue The role in the cycle is : Exit this cycle ( Skip the statement after this loop ), Re enter the current cycle .
while The structure of is quite loose , Only expr As a condition of cycle execution, it is hard to ask , Initialization statements are often in while front , Step increase statements are often in block1 in .
The following is a quite classic while The code of the loop :
#include <stdio.h>
int main(){
char ch='0';
while((ch=getchar())!=EOF){
putchar(ch);
}
return 0;
}
//getchar() The function fetches a character from the input buffer ( If not, I will wait ), And use it as the return value return.
//putchar(char ch) The return value is not concerned . The function is to print characters ch.
// By the way scanf() function , The function is to read data in a given format and store it in a specified address .
// Read data from the input buffer , To space or '\n' until ( Don't read both ).
//EOF.#define Defined identifier constant . Definition statement : #define EOF (-1)
// The way of keyboard typing is :ctrl+z. The function is to mark the end of the file , Be similar to '\0'.2.for sentence
for Circulation and while Loop execution loop The number of times >=0, There is no guarantee that the loop will execute 1 Time .
for Cycle compared to while loop , The initialization statement 、 Conditional interpretation statements and step increase statements are put together , It's more compact .
for( Initialization statement ; Conditional statements ; Step increase statement ){
block1;// The loop body
}
// Of course, these three statements can be omitted . But if the conditional judgment sentence is omitted, it is considered to be constant 1.
// This can lead to a dead cycle .
// You can define a loop control variable in the initialization statement , This makes the program more compact . It also makes circular variables reusable .
// But one for A loop can only be defined in its initialization statement 1/0 Loop variables .
for Circulation is not recommended in the circulation body block Change the value of the loop variable in , This often leads to logical errors .
Another practical suggestion is to control the range of cyclic variables as before 0 Rear opening . In this way, you can easily see the number of cycles , It is also very suitable for controlling arrays .
for Loop supports multi loop variable control loop . But it's not often . Examples are as follows , Corresponding to different cyclic variables ( Initialization and step increase only ) Use commas between statements , separate . The conditional interpretation statement should still be expression.
#include <stdio.h>
int main(){
int j=0;
int k-0;
for(int i=0, j=0, k=0;i+j+k<10;++i,++j,++k){
printf("Bamboo");
}
return 0;
}
// Once only in for Define a loop control variable in the initialization statement of the loop .
// It's written in for(int i=0, int j=0, int k=0;i+j+k<10;++i,++j,++k){} It can lead to error3.do……while…… loop
do……while…… Circulation and while Loops are structurally inferior to for The cycle is compact . Besides ,do……while…… The loop ensures that the loop body is executed 1 Time .
do{
statement;
}
while(expr);// The semicolon here cannot be dropped 
4. Loop control statement break and continue
break and continue Will make the program jump out of this cycle , Do not execute the subsequent code of this cycle . however break Is to quit completely loop; and continue Just exit this cycle , about while and do-while for , They go directly back to conditional statements ; about for loop , It goes back to the step increase statement .
5. Other suggestions
When using loop nesting , Note that some variables need to be initialized . The characteristics of these variables are , It often changes with the circulation of internal circulation , It needs to be initialized with the circulation of the outer loop .
Using loop nesting may lead to computational redundancy . Choosing the appropriate algorithm can improve the operation efficiency .
Example is :
// Calculation 1!+2!+3!+…………+10!
#include <stdio.h>
int main(){
int sum=0;// For storage and
int ret=1;// Used to store factorials
for(int i=1;i<11;++i){
ret=1;// This ret You need to initialize in each outer loop
for(int j=1;j<i+1;++j){
ret=ret*j;
}
sum+=ret;
}
printf("%d\n",sum);
return 0;
}
This code has obvious redundancy , That is, every factorial calculation starts from scratch , There is no use i! The result of calculation is (i+1)!.
The improved code is :
#include <stdio.h>
int main(){
int sum=0;
int ret=1;
for(int i=1;i<11;++i){
ret=ret*i;
sum+=ret;
}
printf("%d\n",sum);
return 0;
}6. Half search
Find elements in an ordered array in half , It is a good example of program structure .
First, consider how to find elements at the algorithm level . First, you need to specify the search range , The subscript of the array [left,right].
On this basis, take mid=(left+right)/2, Notice that this is integer division . take arr[mid] Compare with the given element , If the novel shows that the given element is mid On the right , take left=mid+1; If it is large, it means that the given element is mid On the left , take right=mid+1; If equal, it means that , Returns the element subscript , Otherwise, continue to search ( if ... be ... You can use a branch structure ). The above search process needs to be cycled , Until you find the element ( Use break control ) Or no search scope ( After thinking left>right There is no search scope ) Stop the cycle when . Because I don't know the number of execution cycles , So choose while Good circulation .
int binarySearch(int* arr, int left, int right, int element) {
int index = -1;// Find the return subscript , Otherwise return to -1
while (left <= right) {
int mid = (left + right) / 2;
// if ... be ...
if (arr[mid]>element) {
right = mid - 1;
}
else if (arr[mid] < element) {
left = mid + 1;
}
else {
index = mid;
break;// If found, exit the loop
}
}//end of while
return index;
}//end of function
// The basic structure is the cycle structure and its internal selection structure . choice while To achieve loop The reason is that I don't know the number of cycles , When the number of cycles is known , It is recommended to use for.Experience gained in writing the above program :
1.C Language is the language of communication with computers , The way to make the computer work correctly is that only the programmer clearly knows what the computer should do and clearly expresses it in high-level language . So spend time on algorithms .
2. We cannot give up deep thinking on Algorithm Design for the sake of speed , This is a waste of time . The impetuousness of the heart will be reflected in the pen , Reflected in the procedure .
3. When using the cycle, if you know the number of times to choose for, Otherwise select while. The conditions of the cycle can not only be placed in () In the expression in , You can also use if……break or if……continue To control .
7. Other simple code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
int main() {
char arr1[] = "welcome to bit";
char arr2[] = "##############";
int left = 0;
int right = strlen(arr1)-1;
while (left<=right) {
arr2[right] = arr1[right];
arr2[left] = arr1[left];
right--;
left++;
puts(arr2);
Sleep(1000); // Be similar to arduino Medium delay function , All units are ms.S Capitalization .
system("cls"); //s A lowercase letter .
}
printf("%s\n",arr2);
return 0;
}
// Use... In the front strlen Function to calculate the length of a string , The end is not counted '\0' Of . If you use sizeof(arr1)/sizeof(char) In terms of calculation , Accounting into the end '\0'
//char arr1[]="hello" The end of the string so defined has '\0', and char arr1[]={'h','e','l','l','o'}; The end of this definition does not '\0'.
// In addition, we need to pay attention to , When calculating the length of other types of arrays, you can use sizeof, And there's no problem . But be careful , There will be problems when calculating the array length inside the function .
// such as 边栏推荐
猜你喜欢
![Error[pe147]: declaration is incompatible with 'error problem](/img/4f/57145d78f4dc1fe84d2f271dd9d82f.png)
Error[pe147]: declaration is incompatible with 'error problem

sigmod 函数与softmax 函数对比

flutter 背景变灰效果,如何透明度,灰色蒙板遮罩

第6期:大学生应该选择哪种主流编程语言
![[leetcode daily question 2021/5/8]1723. The shortest time to complete all work](/img/e7/a48bb5b8a86cbc4cd5b37bb16661a8.png)
[leetcode daily question 2021/5/8]1723. The shortest time to complete all work

Flutter编译报错 version of NDK matched the requested version 21.0.6113669. Versions available locally: 2

解决:无法加载文件 C:\Users\user\AppData\Roaming\npm\npx.ps1,因为在此系统上禁止运行脚本 。

PLC与伺服电机连接

反射机制简述

Write to esp8266 burning brush firmware
随机推荐
回到顶部的几种方案(js)
flutter dart生成N个区间范围内不重复随机数List
使用float实现左中右布局,中间内容自适应
在神州IV开发板上为STemWin 5.22加入触屏驱动
剑指Offer(七):斐波那契数列
在altium designer中禁用USBJATG
PLC与伺服电机连接
MD5 encryption
[leetcode daily question 2021/8/31] 1109. Flight reservation statistics [medium] differential array
SQL Server 之Sql语句创建数据库
Flutter编译报错 version of NDK matched the requested version 21.0.6113669. Versions available locally: 2
[leetcode daily question 2021/5/8]1723. The shortest time to complete all work
Write to esp8266 burning brush firmware
字典与int矩阵
$router和$route的区别
剑指Offer(四十九):把字符串转换成整数
按二进制数中1的个数分类
Sql Server 数据库之初学体验
RT-Thread 学习笔记(三)---用SCons 构建编译环境
Issue 7: how do you choose between curling up and lying flat