C++ Flow of control

这里只是对Control structures 简要说明。

一般的, 我们的程序执行的顺序都是一个语句一个语句按照顺序执行。 但是有的时候, 我们常常需要改变程序语句执行的顺序, 好处自不必说。 这就是the control flow。

control flow 需要两种control structures, 一种是条件语句(conditionals), 一种是循环loops。

1.control structure 1: contionals:

   1.1 if 条件句

#include <iostream>
using namespace std;
int main() {
   int x = 6;
   int y = 2;
   if (x > y) 
      cout << "x is greater than y\n";
   else if (y > x)
      cout << "y is greater than x\n";
   else
      cout << "x and y are equal\n";
    return 0; 
}


    1.2 switch case 语句 

#include <iostream>

using namespace std;
int main() {
   int x = 6;
   
   switch (x) {
          case 1:
                        cout<< "x is 1\n";
                break;
           case 2:
           case 3:  
               cout << "x is 2 or 3";
              break;
            default:
              cout << "x is not 1, 2, or 3";    
   }
   return 0;
}


2.control structure 2: Loops

C++ 有三种loops: while, do while, and for

2.1  while 和do-while

#include <iostream>
using namespace std;
int main() {
   int i = 0;
  
   while(i < 10)
      i = i + 1;
   cout << "i is" << endl; //this program will print: i is 10
   return 0;
}


 注意: 

do {

   statement1

   statement2

   ...

} while (conmdition)

能够保证{ }中的语句至少执行一次。

2.2for循环

#include <iostream>
using namespace std;
int main() {
   for(int i = 0; i < 10; i++) {
      cout << i << "\n";
   }
   return 0;
} 


 This program will print values 0 through 9, each on its own line 

如果计数的变量已经提前定义了, 在for 循环语句的初始化区域就不需要重新定义一个。

<pre name="code" class="cpp">#include <iostream>
using namespace std;

int main() {
   int i = 0;
   for( ; i < 10; i++) {
      cout << i << "\n";
   }
   return 0;
}


 for循环语句可以转换为while 语句 

#include <iostream>
using namespace std;

int main() {
   int i = 0;
   while(i < 10) {
      cout << i << "\n";
      i++
   }
   return 0;
}


 2.3 Nesed Control structures 

如下例子:

#include <iostream>
using namespace std;
int main() {
   int x;
   int y;
   if (x > y) {
      cout << "x is greater than y \n";
      if(x == 6)
         cout << "x is equal to 6 \n";
      else
         cout << "x is not equal to 6 \n";    
   }
   else 
      cout << "x is not greater than y\n";
   return 0;
}


 

例如下面的nesed loop:

#include <iostream>
using namespace std;
int main() {
   for (int i = 0; i < 4; i++) {
      
      for (j = 0; j < 4; j++) 
          cout << j;
      cout << "\n";
   }   
   return 0;
}

This program will print four lines of 0123







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值