一、条件语句 if … else
一个基于用户输入的条件处理的示例:
1、if … else语句的使用
代码示例:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter two integers: " << endl;
int num1 = 0, num2 = 0;
cin >> num1;
cin >> num2;
cout << "Enter \'m\' to multiply, anything else to add: ";
char userSelection = '\0';
cin >> userSelection;
int result = 0;
if (userSelection == 'm')
result = num1 * num2;
else
result = num1 + num2;
cout << "result is: " << result << endl;
return 0;
}
输出:
Enter two integers:
10
2
Enter ‘m’ to multiply, anything else to add: m
result is: 20
需要注意的是,如果第16行换成:
if (userSelection == 'm');
那么if结构是没有意义的,因为它已被空语句(分号)在同一行中终止。 需要小心并避免这种情况,因为在这种情况下不会发生编译错误。
2、if 嵌套语句
代码示例:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter two integers: " << endl;
float num1 = 0, num2 = 0;
cin >> num1;
cin >> num2;
cout << "Enter 'd' to divide, anything else to multiply: ";
char userSelection = '\0';
cin >> userSelection;
if (userSelection == 'd')
{
cout << "You wish to divide!" << endl;
if(num2 != 0)
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
else
cout << "Division by zero is not allowed" << endl;
}
else
{
cout << "You wish to multiply!" << endl;
cout << num1 << " x " << num2 << " = " << num1 * num2 << endl;
}
return 0;
}
输出:
Enter two integers:
10
2
Enter ‘d’ to divide, anything else to multiply: d
You wish to divide!
10 / 2 = 5
if…else结构也可以组合在一起,使用else if结构提供多个选项的选择:
#include <iostream>
using namespace std;
int main()
{
enum DaysOfWeek
{
Sunday = 0,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
cout << "Find what days of the week are named after!" << endl;
cout << "Enter a number for a day (Sunday = 0): ";
int dayInput = Sunday; // Initialize to Sunday
cin >> dayInput;
if (dayInput == Sunday)
cout << "Sunday was named after the Sun" << endl;
else if (dayInput == Monday)
cout << "Monday was named after the Moon" << endl;
else if (dayInput == Tuesday)
cout << "Tuesday was named after Mars" << endl;
else if (dayInput == Wednesday)
cout << "Wednesday was named after Mercury" << endl;
else if (dayInput == Thursday)
cout << "Thursday was named after Jupiter" << endl;
else if (dayInput == Friday)
cout << "Friday was named after Venus" << endl;
else if (dayInput == Saturday)
cout << "Saturday was named after Saturn" << endl;
else
cout << "Wrong input, execute again" << endl;
return 0;
}
输出:
Find what days of the week are named after!
Enter a number for a day (Sunday = 0): 3
Wednesday was named after Mercury
3、条件语句 switch-case
switch-case语句是我们能够针对一系列可能的常量检查特定表达式,并对这些不同的值执行不同的操作。
switch-case结构:
switch(expression) {
case LabelA:
DoSomething;
break;
case LabelB:
DoSomethingElse;
break;
// And so on...
default:
DoStuffWhenExpressionIsNotHandledAbove;
break;
}
该结构的执行方式是:代码对括号中的表达式求值,并检查后面的每个case标签是否与求得的值相等。每个cese的标签都是一个常量。如果相等,那么执行该标签后面的代码。当表达式未评估为LabelA时,它会检查LabelB。如果该检查的结果为true,则执行DoSomethingElse。这种检查一直持续到break为止。break导致执行退出代码块。default也是可选的,当表达式的值不等同于switch-case结构中的任何标签时执行该语句。
代码示例:
#include <iostream>
using namespace std;
int main()
{
enum DaysOfWeek
{
Sunday = 0,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
cout << "Find what days of the week are named after!" << endl;
cout << "Enter a number for a day (Sunday = 0): ";
int dayInput = Sunday; // Initialize to Sunday
cin >> dayInput;
switch (dayInput)
{
case Sunday:
cout << "Sunday was named after the Sun" << endl;
break;
case Monday:
cout << "Monday was named after the Moon" << endl;
break;
case Tuesday:
cout << "Tuesday was named after Mars" << endl;
break;
case Wednesday:
cout << "Wednesday was named after Mercury" << endl;
break;
case Thursday:
cout << "Thursday was named after Jupiter" << endl;
break;
case Friday:
cout << "Friday was named after Venus" << endl;
break;
case Saturday:
cout << "Saturday was named after Saturn" << endl;
break;
default:
cout << "Wrong input, execute again" << endl;
break;
}
return 0;
}
输出:
Find what days of the week are named after!
Enter a number for a day (Sunday = 0): 3
Wednesday was named after Mercury
4、条件运算符( ?: )
条件运算符类似于压缩的if…else结构,条件运算符也称为三元运算符,它需要三个操作数:
(conditional expression evaluated to bool) ? expression1 if true : expression2 if false;
这样的运算符可用于紧凑地评估两个给定数字中的较大者,如下所示:
int max = (num1 > num2)? num1 : num2; // max contains greater of num1 and num2
二、循环结构
1、使用goto的简单循环结构
顾名思义,goto指示从代码中的特定标记点继续执行,可以使用它来向后执行或重新执行某些语句。
SomeFunction()
{
Start: // Called a label
CodeThatRepeats;
goto Start;
}
上面声明了一个名为Start的标签,并使用goto从此时开始重复执行。
需要注意的是,在上面的情况中,除非在某些情况下调用goto给出一个可以求值为false的条件,或者重复的代码包含在某些条件下的return语句,否则goto命令和标签之间的代码段将无休止地重复并使程序不能结束。
代码示例:
#include <iostream>
using namespace std;
int main()
{
Start:
int num1 = 0, num2 = 0;
cout << "Enter two integers: " << endl;
cin >> num1;
cin >> num2;
cout << num1 << " x " << num2 << " = " << num1 * num2 << endl;
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
cout << "Do you wish to perform another operation (y/n)?" << endl;
char repeat = 'y';
cin >> repeat;
if (repeat == 'y')
goto Start;
cout << "Goodbye!" << endl;
return 0;
}
输出:
Enter two integers:
12
2
12 x 2 = 24
12 + 2 = 14
Do you wish to perform another operation (y/n)?
y
Enter two integers:
3
23
3 x 23 = 69
3 + 23 = 26
Do you wish to perform another operation (y/n)?
n
Goodbye!
上面代码重复执行乘法和加法操作,直到用户选择‘n’。
需要注意的是,goto不是编程循环的推荐形式,因为goto的大量使用会导致不可预测的代码流,代码的执行可以在没有特定顺序的情况下从一行跳到另一行,在某些情况下会使变量处于不可预测的状态。
2、while循环
while循环结构:
while(expression)
{
// Expression evaluates to true
StatementBlock;
}
只要括号中表达式的结果为true就会重复执行循环中的结构,直到表达式的值变为false。
3、do…while循环
do…while循环结构:
do
{
StatementBlock; // executed at least once
} while(condition); // ends loop if condition evaluates to false
与while语句不同的是,while语句是先判断,如果符合条件再执行,do…while循环是先执行再判断。
因此,当循环中的语句块需要至少执行一次时,使用do…while结构。
4、for循环
for语句是一个更复杂的循环,它允许执行一次初始化语句(通常用于初始化计数器),检查退出条件(通常使用此计数器),并在每个循环结束时执行操作( 通常递增或修改此计数器)。
for (initial expression executed only once;
exit condition executed at the beginning of every loop;
loop expression executed at the end of every loop)
{
DoSomething;
}
也可以在for循环第一个初始化表达式中一次初始化多个变量:
for (int counter1 = 0, counter2 = 5; // initialize
counter1 < ARRAY_LENGTH; // check
++counter1, --counter2) // increment, decrement
5、基于范围的for循环
基于范围的for循环基于一系列值来操作,判断语句中是一个范围,在变量的值为该范围中的值时符合循环条件:
for (VarType varName : sequence)
{
// Use varName that contains an element from sequence
}
一个例子:
int someNums[] = { 1, 101, -1, 40, 2040 };
for (int aNum : someNums) // range based for
cout << "The array elements are " << aNum << endl;
三、使用关键字 continue 和 break 修改循环结构
在一些情况中,特别是在处理许多条件的复杂循环中,有时候肯能无法有效地控制循环条件,甚至需要在循环内修改程序行为。这时候可以使用关键字continue 和 break。
continue关键字允许程序跳过代码块中continue后面的代码。 因此,continue关键字在while,do … while或for循环结构中的的效果是它跳过continue后面的语句,循环条件被重新评估,如果条件评估为真,则重新进入循环块。
break关键字的作用是退出循环块,从而结束循环。
1、无限循环
需要注意的是,while,do … while和for循环有一个条件表达式,当条件计算结果为false时,循环结束。如果编写一个始终求值为true的条件,则循环永远不会结束。
例如下面的情况:
while(true) // while expression fixed to true
{
DoSomethingRepeatedly;
}
for (;;) // no condition supplied = unending for
{
DoSomethingRepeatedly;
}
虽然看起来很奇怪,但是这样的循环有时候确实是有必要的。比如,操作系统需要不断检查是否已将USB等设备连接到USB端口。只要操作系统正在运行,这是一项不应该停止的活动。这种情况需要使用永不结束的循环,这种循环也称为无限循环。
2、控制无限循环
如果要结束无限循环,可以通过插入break关键字(通常在if(condition)块中使用)来实现。
例如:
while(true) // while condition fixed to true
{
DoSomethingRepeatedly;
if(expression)
break; // exit loop when expression evaluates to true
}
四、嵌套循环
在循环中嵌套一个或多个循环的情况也比较常见。代码示例如下:
#include <iostream>
using namespace std;
int main()
{
const int ARRAY1_LEN = 3;
const int ARRAY2_LEN = 2;
int myNums1[ARRAY1_LEN] = { 35, -3, 0 };
int myNums2[ARRAY2_LEN] = { 20, -1 };
cout << "Multiplying each int in myNums1 by each in myNums2:" << endl;
for (int index1 = 0; index1 < ARRAY1_LEN; ++index1)
for (int index2 = 0; index2 < ARRAY2_LEN; ++index2)
cout << myNums1[index1] << " x " << myNums2[index2] << " = " << myNums1[index1] * myNums2[index2] << endl;
return 0;
}
输出:
Multiplying each int in myNums1 by each in myNums2:
35 x 20 = 700
35 x -1 = -35
-3 x 20 = -60
-3 x -1 = 3
0 x 20 = 0
0 x -1 = 0
嵌套循环通常还有以下两个作用:
1、使用嵌套循环遍历多维数组
代码示例:
#include <iostream>
using namespace std;
int main()
{
const int NUM_ROWS = 3;
const int NUM_COLUMNS = 4;
// 2D array of integers
int MyInts[NUM_ROWS][NUM_COLUMNS] = { {34, -1, 879, 22},
{24, 365, -101, -1},
{-20, 40, 90, 97} };
// iterate rows, each array of int
for (int row = 0; row < NUM_ROWS; ++row)
{
// iterate integers in each row (columns)
for (int column = 0; column < NUM_COLUMNS; ++column)
{
cout << "Integer[" << row << "][" << column << "] = " << MyInts[row][column] << endl;
}
}
return 0;
}
输出:
Integer[0][0] = 34
Integer[0][1] = -1
Integer[0][2] = 879
Integer[0][3] = 22
Integer[1][0] = 24
Integer[1][1] = 365
Integer[1][2] = -101
Integer[1][3] = -1
Integer[2][0] = -20
Integer[2][1] = 40
Integer[2][2] = 90
Integer[2][3] = 97
2、使用嵌套循环计算斐波纳契数列
斐波那契数列是一组以0和1开始的数字,其中数列中的每个后续数字都是前两个数字的总和。Fibonacci数列前面部分内容如下所示:
0, 1, 1, 2, 3, 5, 8, … and so on
代码示例:
#include <iostream>
using namespace std;
int main()
{
const int numsToCalculate = 5;
cout << "This program will calculate " << numsToCalculate << " Fibonacci Numbers at a time" << endl;
int num1 = 0, num2 = 1;
char wantMore = '\0';
cout << num1 << " " << num2 << " ";
do
{
for (int counter = 0; counter < numsToCalculate; ++counter)
{
cout << num1 + num2 << " ";
int num2Temp = num2;
num2 = num1 + num2;
num1 = num2Temp;
}
cout << endl << "Do you want more numbers(y/n)? ";
cin >> wantMore;
} while (wantMore == 'y');
cout << "Goodbye!" << endl;
return 0;
}
输出:
This program will calculate 5 Fibonacci Numbers at a time
0 1 1 2 3 5 8
Do you want more numbers(y/n)? y
13 21 34 55 89
Do you want more numbers(y/n)? n
Goodbye!
总结
本章介绍了条件语句,学习了if … else结构,并介绍使用switch-case语句来处理包含不同值的变量时的不同情况。
介绍循环结构时介绍了goto语句的使用,但是由于它可能导致无法预料的错误,应该尽量避免使用。学习了使用while,do … while和for语句来实现循环结构,学习了使用无限循环,并使用continue和break来更好地控制它们。