6、流程控制

分支语句

if-else

#include<stdio.h>

int main(){
   int age = 19;
   if(age >= 18){
      printf("已经成年");
   }else if(age >= 15){
      printf("青少年");
   }else{
      printf("青年");
   }

   return 0;
}

switch-case

#include<stdio.h>

int main(){
   int mon = 1;
   switch(mon){
      case 1:
         printf("春天");
         break;
      case 2:
         printf("夏天");
         break;
      case 3:
         printf("秋天");
         break;
      default:
         printf("冬天");
         break;
   }

   return 0;
}

循环语句

while

#include<stdio.h>

int main(){
   int i = 0;
   while (i < 10){
      printf("循环第%d次,此时i为:%d\n",i + 1,i);
      i++;
   }
   return 0;
}

do-while

#include<stdio.h>

int main(){
   int i = 0;
   do{
      printf("循环第%d次,此时i为:%d\n",i + 1,i);
      i++;
   } while (i < 10);
   return 0;
}

for

#include<stdio.h>

int main(){
   for(int i = 0;i < 10;i++){
      printf("循环第%d次,此时i为:%d\n",i + 1,i);
   }
   return 0;
}

循环控制关键字

break

#include<stdio.h>

int main(){
   int count = 0;
   while(1){
      printf("此时的count为%d\n",count);
      if(count == 9){
         break;
      }
      count++;
   }
   return 0;
}

continue

#include<stdio.h>

int main(){
   for(int i = 0;i < 100;i++){
      if(i % 2 == 0){
         continue;
      }
      printf("偶数:%d\n",i);
   }
   return 0;
}