`
linleizi
  • 浏览: 232358 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

C++控制结构学习笔记二

阅读更多
"条件结构(if and else);
例一:
if (x == 100) {
   cout << ""x is 100。\n"";
} else {
   cout << ""x is not 100。"";
}
例二:
if (x > 0)
cout << ""x is positive。\n"";
else if (x < 0)
cout << ""x is negative。\n"";
else
cout << ""x is 0.""; "

"循环结构;
while循环,例一:
#include <iostream.h>
int main() {
  int n;
  cout << ""Enter the starting number"";
  cin >> n;
  while (n > 0) {
    cout << n << "","";
    --n;
  }
  cout << ""FIRE!"";
  return 0;
}
do - while循环,例二:
#include <iostream.h>
int main() {
  ussigned long n;
  do {
    cout << ""Enter number (0 to end):"";
    cin >> n;
    cout << ""You entered:"" << n << ""\n"";
  } while (n != 0);
  return 0;
}
for 循环,例三:
#include <iostream.h>
int main() {
  for (int n=10; n>0; n--) {
    cout <<n << "","";
  }
  cout << ""FIRE!"";
  return 0;
}
"
"分支控制和跳转;
break语句,在满足条件下强制跳出循环,例四:
#include <iostream.h>
int main() {
  int n;
  for (n=10; n > 0;; n--) {
    cout << n << "","";
    if (n == 3) {
      cout << ""countdown aborter!"";
      break;
    }
  }
  return 0;
}
输出结果:10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
continue语句,跳出当前循环,直接进入下次循环,例五:
#include <iostream.h>
int main() {
  for (int n =10; n > 0; n--) {
    if (n == 5) continue;
    cout << n << "","";
  }
  cout << ""FIRE!"";
  return 0;
}
输出结果:10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
goto 语句,可以从程序一点跳到另外一点,goto语句参数是由表示名加冒号组成,例六:
#include <iostream.h>
int main() {
  int n = 10;
  loop:
    cout << n << "","";
    n--;
  if (n > 0) goto loop;
  cout << ""FIRE!"";
  return 0;
}
输出结果:10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! "
"选择结构;
switch (x) {
  case 1:
   cout << ""x is 1。"";
   break;
  case 2:
   cout << ""x is 2。"";
   break;
  default:
    cout << ""value of x unknown。"";
}
注意:每个分支后面必须包含break语句,只能用来比较表达式或不同常量的值,不能把变量或范围放在case之后。"
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics