当前位置:网站首页>[explain C language in detail] takes you to play with loop structure (for_while_do while)
[explain C language in detail] takes you to play with loop structure (for_while_do while)
2022-07-27 02:10:00 【Zoroxs】
Loop structure
executive summary
Life is not just about choices , Also often faced with doing something repeatedly , For example , We study day after day 、 Knock on the code 、
C The language provides —while loop —for loop —do-while Loop to express loop

Next , Introduce the three cycles respectively
while loop
while The flow chart of the cycle is roughly like this

Grammatical structure
while( expression ) // Determine if the expression holds , Execute the loop body when it is established , If it is not established, it will not enter
The loop body ;
Next let's use while loop , Print 1-10 The number of
#include <stdio.h>
int main(){
int i = 1;
while(i < 11)
printf("%d ",i++);
return 0;
}

This is while The simplest use , Let's take a look while Medium break and continue
while In circulation break and continue
break
notice break You must be familiar with , Select in structure switch-case Just match break Use
#include <stdio.h>
int main(){
int i = 1;
while(i < 11)
{
if( 5 == i)
break;
printf("%d ",i++);
}
return 0;
}

It can be seen that , When i=5 When , Directly jump out of the whole cycle and no longer execute
break It's about jumping out of the loop , Also jump out directly switch-case
continue
In English ,continue It means to continue , In circulation , It means to skip this cycle and proceed to the next cycle
#include <stdio.h>
int main() {
int i = 1;
while (i < 11)
{
if (5 == i)
continue; // hold break Switch to continue Have a try
printf("%d ", i++);
}
return 0;
}
You can guess , As one can imagine , You may think the result is 1 2 3 4 6 7 8 9 10 skip 5, Let's analyze


The cursor keeps flashing , Dead cycle , How can we skip 5 The effect of ,
The core problem is ** such i The value of cannot be changed , Then we put the i Put it in continue Let's try ahead **
#include <stdio.h>
int main() {
int i = 0;
while (i < 11)
{
i++;
if (5 == i)
continue;
printf("%d ", i);
}
return 0;
}
such continue You won't skip the cycle factor -i The change of , So there's no dead cycle , Look at the results

Successfully skipped 5, Everyone in while Use in loop continue We must pay attention to the problem of circulation factor
continue stay while The role of the loop is :
- In this cycle continue The following code will no longer be executed, but directly jump to while The judgment part of a sentence .
- Make the entry judgment of the next cycle .
for loop
Grammatical structure
for( expression 1 ; expression 2 ; expression 3)
The loop body ;
- expression 1 by ** Initialization part , be used for Initializes the of the loop variable **.
- expression 2 by _ Condition judgment part _, be used for ** Judge when the cycle ends **.
- expression 3 by _ Adjustment part _, be used for **_ Adjustment of cyclic conditions _**.

for In circulation break and continue
break
for In circulation break And while In circulation break Exactly the same , To jump out of a loop
#include <stdio.h>
int main() {
int i = 0;
for (i = 1; i < 10; i++) {
if (5 == i)
break;
printf("%d ", i);
}
return 0;
}

break Basically no difference , Just jump out of the loop
continue
for In circulation continue What jumps out is still this cycle , But it doesn't skip the expression 3
#include <stdio.h>
int main() {
int i = 0;
for (i = 1; i < 10; i++) {
if (5 == i)
continue;
printf("%d ", i);
}
return 0;
}

Still skip 5,continue Expressions will not be skipped 3, signify i++ It can be executed , It doesn't create a dead cycle
Of course , A man wants to write bug No one can stop him
such as :

for The problem of omitting expressions in loops
for There are in the loop 3 Expression , All can be omitted , But a semicolon cannot be less
int main(){
int i = 0;
// It can be written like this
for (i=0;i<10;)
;
// It can be like this
for(i = 0;;)
;
// Even so
for(;;); // There can't be less than one semicolon
}
for(;; This code , If there is no... In the loop break, Basically, it's a proper dead cycle , It is not recommended that you use
for A nested loop
When there are two for In the cycle , The problem of cycle control needs to be considered , The ranks of , What does internal and external circulation mean ? You need to think clearly
Write a multiplication table
#include <stdio.h>
int main() {
int i = 0;
int j = 0;
for (i = 1; i < 10; i++) {
// The control line
for (j = 1; j <= i; j++) {
printf("%d * %d = %d ", j, i, i * j); // Control the column
}
printf("\n");
}
return 0;
}
In general , The control conditions of the inner circulation factor are related to the outer circulation factor
Here are a few for Circular considerations
- Don't be in for Modify the loop variable in the loop body , prevent for The cycle is out of control .
- Suggest for The loop control variable value of the statement adopts “ Front closing back opening section ” How to write it
#include <stdio.h>
int main(){
int arr[10] = {
1,2,3,4,5,6,7,8,9,10};// Array index from 0 To 9
int i = 0;
for(;i <=9;i++) // Front closed and rear closed
printf("%d ",arr[i]);
for(;i < 10;i++)// Before closed after opening
printf("%d ",arr[i]);
return 0;
}
The writing method of front closed and back open interval , It may make the number have some meaning , For example, in the example 10, Just the number of print elements , Is also the length of the array
Give you a little knowledge
alert for Questions directly followed by semicolons after the cycle , Schools love this stuff , Understand everything
do-while loop
do-while The cycle is very different from the other two cycles , It is also the cycle with the lowest frequency
do
The loop body
while( Judge the condition );

do-while The biggest feature of the cycle is anyway , The loop body must be executed once
Only in the corresponding scenario , Should use do-while loop
do-while In circulation ,break as well as continue The usage and while The same in the loop , This article is not going to cover .
goto sentence
about goto sentence , It's a jump , In fact, there is no need to say , Because what can be solved with it can be solved with a cycle
A brief introduction , But it is not recommended that you use
#include <stdio.h>
int main()
{
printf("hehe\n");
goto flag;
printf("haha\n");
flag:
printf("heihei\n");
return 0;
}
goto Will jump directly to flag At the mark , Skip printing haha

This is just goto Sentence syntax
goto Statements are really used in multi-level loop nesting , Out of the loop , Use break To reach , You can only jump out once , We'll talk about it later
summary
- for Loop for initialization 、 Conditions 、 The control of circulation factors are all together
- do-while The body of the loop executes at least once
- goto It's not recommended
- Each cycle has its merits , According to the corresponding scenario , Select the corresponding cycle , Meet demand
- This article only introduces the circular grammar , For cycles , Everyone should practice hard , Think more
notes :
- All the insights in this article , My humble opinion , Misleading , I would appreciate your comments.
- If it helps you , Please support me
边栏推荐
- 21dns domain name resolution
- Hash索引和B+树相关知识
- 第五讲—按键控制LED
- 事务数据库及其四特性,原理,隔离级别,脏读,幻读,不可重复读?
- shell课程总结
- Talking about server virtualization & hyper convergence & Storage
- Text to image论文精读SSA-GAN:基于语义空间感知的文本图像生成 Text to Image Generation with Semantic-Spatial Aware GAN
- Introduction to network - Introduction to home networking & basic network knowledge
- Solution: various error reports and pit stepping and pit avoidance records encountered in the alchemist cultivation plan pytoch+deeplearning (I)
- Initial experience of cloud database management
猜你喜欢

Removal and addition of reference types in template and generic programming

超出隐藏显示省略号

DF-GAN实验复现——复现DFGAN详细步骤 及使用MobaXtem实现远程端口到本机端口的转发查看Tensorboard
![[详解C语言]一文带你玩转循环结构(for_while_do-while)](/img/d9/75053297873a5b5458514e7f557cdc.png)
[详解C语言]一文带你玩转循环结构(for_while_do-while)

MySQL backup recovery

【mysql】mysql启动关闭命令以及一些报错解决问题

FID index reproduction step on the pit to avoid the pit text generation image FID quantitative experiment whole process reproduction (FR é Chet inception distance) quantitative evaluation experiment s

STM32 HAL库串口(UART/USART)调试经验(一)——串口通信基础知识+HAL库代码理解

count(*)为什么很慢

Text to image paper intensive reading rat-gan: recursive affine transformation for text to image synthesis
随机推荐
B - Bomb HDU - 5934
js求最大值?
解决方案:炼丹师养成计划 Pytorch+DeepLearning遇见的各种报错与踩坑避坑记录(一)
通过对射式红外传感器计次实验讲解EXTI中断
[reprint] GPU compute capability table
STM32_HAL_SUMMARY_NOTE
When El table is selected, the jump page remains selected
FID指标复现踩坑避坑 文本生成图像FID定量实验全流程复现(Fréchet Inception Distance )定量评价实验踩坑避坑流程
测开基础 日常刷题 (持续更新ing...)
第五讲—按键控制LED
Solution: various error reports and pit stepping and pit avoidance records encountered in the alchemist cultivation plan pytoch+deeplearning (I)
Pseudo class of a element
JS max?
行,表,页,共享,排他,悲观,乐观,死锁
Text to image论文精读SSA-GAN:基于语义空间感知的文本图像生成 Text to Image Generation with Semantic-Spatial Aware GAN
Text to image论文精读GR-GAN:逐步细化文本到图像生成 GRADUAL REFINEMENT TEXT-TO-IMAGE GENERATION
JS——初识JS、变量的命名规则,数据类型
6.29 众安暑期测开实习一面
Realize data interaction between two apps through fileprovider
[详解C语言]一文带你玩转函数