Getting to understand C ++ Phase II Basics (5) - C ++ process structure

1. Sequence Structure

The implementation of the program from top to bottom

2. Select the structure (structure determination)

Analyzing structure requires the programmer to specify one or more conditions to be evaluated or tested, and the statement Statement (necessary) condition is false, and to execute (optional) condition is true be executed.

C ++ programming language provides the following types of judgment statement

Statement description
The if statement A if statement consists of a Boolean expression followed by one or more statements.
if-else statement A if statement later be followed by an optional else statement , else statement executes the Boolean expression is false.
Nested if statements You can a if or else if using another within the statement if or else if statement.
switch statement A switch case statement allows to test a plurality of values of the variable is equal.
Nested switch statement You can be a switch using another statement within a switch statement.

 The if statement

In C ++ if statement syntax:

if(boolean_expression)
{
   // If the Boolean expression is true statement to be executed
}

If the Boolean expression is to true , the code block if the statement will be executed. If the Boolean expression is to false , if the first set of codes after the end of the statement (after closing parenthesis) will be executed.

C language to any non-zero and non-null value is assumed to be to true , the zero or null is assumed to false .

int main() {
	int a=30;
	if (a<20)
	{
		cout << a;
	}
	cout << 20;
	return 0;
}

if-else statement

A if statement later be followed by an optional else statement , else statement executes the Boolean expression is false.

C ++, if ... else syntax statements:

if(boolean_expression)
{
   // If the Boolean expression is true statement to be executed
}
else
{
   // If the Boolean expression is false statement to be executed
}

If the Boolean expression is to true , then execution if the code within the block. If the Boolean expression is to false , execute else the code within the block.

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
 
   // 检查布尔条件
   if( a < 20 )
   {
       // 如果条件为真,则输出下面的语句
       cout << "a 小于 20" << endl;
   }
   else
   {
       // 如果条件为假,则输出下面的语句
       cout << "a 大于 20" << endl;
   }
   cout << "a 的值是 " << a << endl;
 
   return 0;
}

Nested if statements

In C ++, nested if-else statement is legal, which means you can in a if or else if using another within the statement if or else if statement.

C ++, nested if statements syntax:

if( boolean_expression 1)
{
   // Boolean expression 1 is true when executed
   if(boolean_expression 2)
   {
      // Boolean expression 2 is true when execution
   }
} 
You can nest the else if ... the else , way nested if similar statements.
#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
   int b = 200;
 
   // 检查布尔条件
   if( a == 100 )
   {
       // 如果条件为真,则检查下面的条件
       if( b == 200 )
       {
          // 如果条件为真,则输出下面的语句
          cout << "a 的值是 100,且 b 的值是 200" << endl;
       }
   }
   cout << "a 的准确值是 " << a << endl;
   cout << "b 的准确值是 " << b << endl;
 
   return 0;
}

switch statement

A switch case statement allows to test a plurality of values of the variable is equal. Each variable value is called a case, and will be tested for each switch case to be checked.

In C ++ switch statement syntax:

switch (expression) {case constant-expression: statement (s); break; // optional case constant-expression: statement (s); break; // // Alternatively you can have any number of default case statement : // optional statement (s);}

switch statement must follow the following rules:

  • switch statement expression must be an integer or enumerated type, a class or type, wherein there is a single class conversion function to convert it to an integral or enumeration type.
  • In a switch you can have any number of case statements. Each case is followed by a value to be compared and a colon.
  • case of the constant-expression must have the same data type variable in the switch, and must be a constant or literal.
  • When the constant case of the variable being tested is equal to, followed by the case of statements will be executed until the encounter break statement so far.
  • When faced break when the statement, the termination switch, control flow will jump to the next line after the switch statement.
  • Not every case needs to contain BREAK . If the case statement does not contain a break , control flow will continue to follow the case, until a break is encountered so far.
  • A switch statement can have an optional default Case, appears at the end of the switch. default case can be used in all of the above case is not true when performing a task. default case in the break statement is not required.

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   char grade = 'D';
 
   switch(grade)
   {
   case 'A' :
      cout << "很棒!" << endl; 
      break;
   case 'B' :
   case 'C' :
      cout << "做得好" << endl;
      break;
   case 'D' :
      cout << "您通过了" << endl;
      break;
   case 'F' :
      cout << "最好再试一下" << endl;
      break;
   default :
      cout << "无效的成绩" << endl;
   }
   cout << "您的成绩是 " << grade << endl;
 
   return 0;
}

Nested switch statement

Can be a switch as an external switch portion of the sequence of statements, i.e., it can be a switch with another statement within the switch statement. Even if the case constants of internal and external switch contain common values, there is no contradiction.

C ++ switch statement allows at least 256 levels of nesting.

C ++, nesting switch statement syntax:

switch(ch1) {
   case 'A': 
      cout << "The external switch is part of the A";
      switch(ch2) {
         case 'A':
            cout << "The internal switch is part of the A";
            break;
         case 'B': // Internal Code B case
      }
      break;
   case 'B': // External Code B case
}

Note:?: Operator

We have explained in previous chapters of the conditional operator:? , Can be used instead if ... else statement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

Which, Exp1, Exp2 and Exp3 an expression. Please note that the use of the colon and location.

? Value of the expression is determined by the Exp1. If Exp1 true, Exp2 value is calculated, the result is the whole? Value of the expression. If Exp1 is false, Exp3 value is calculated, the result is the whole? Value of the expression.

3. loop structure

Sometimes, you may need to perform several times the same piece of code. In general, the statements are executed sequentially: first statement in the function performed first, followed by a second statement, and so on. Programming languages ​​are provided that allow more complex execution paths of various control structures. Loops allow us to repeatedly execute a statement or group of statements, the following is the general form in most programming languages ​​looping statement:


Cycle type.

Circulation type description
while loop When a given condition is true, repeat statement or group of statements. It will test the condition before executing the loop body.
for loop Repeatedly execute a sequence of statements, simplify code management loop variable.
do-while loop Except that it is the end of the outer body of the loop test conditions, similar to the while statement.
Nested loop You can use one or more cycles in while, for or do..while cycle.

 while loop

As long as the given condition is true, the while loop executes repeatedly a target statement.

In C ++ while loop syntax:

while(condition)
{
   statement(s);
}

Here, Statement (S) may be a single statement, may be several statements in the code block. condition can be any expression, when any non-zero value is true. When the execution loop condition is true. When the condition is false, program flow will continue to the next statement followed the loop.

int main() {
	int a=3;
	while (a<30)
	{
		cout << a;
		a++;
	}
	return 0;
}

for loop

for loop control structure allows you to write repeat a certain number of execution cycles.

In C ++ for loop syntax:

for ( init; condition; increment )
{
   statement(s);
}

下面是 for 循环的控制流:

  1. init 会首先被执行,且只会执行一次。这一步允许您声明并初始化任何循环控制变量。您也可以不在这里写任何语句,只要有一个分号出现即可。
  2. 接下来,会判断 condition。如果为真,则执行循环主体。如果为假,则不执行循环主体,且控制流会跳转到紧接着 for 循环的下一条语句。
  3. 在执行完 for 循环主体后,控制流会跳回上面的 increment 语句。该语句允许您更新循环控制变量。该语句可以留空,只要在条件后有一个分号出现即可。
  4. 条件再次被判断。如果为真,则执行循环,这个过程会不断重复(循环主体,然后增加步值,再然后重新判断条件)。在条件变为假时,for 循环终止。

#include <iostream>
using namespace std;
 
int main ()
{
   // for 循环执行
   for( int a = 10; a < 20; a = a + 1 )
   {
       cout << "a 的值:" << a << endl;
   }
 
   return 0;
}

基于范围的for循环(C++11)

for 语句允许简单的范围迭代:


int my_array[5] = {1, 2, 3, 4, 5};
// 每个数组元素乘于 2
for (int &x : my_array)
{
    x *= 2;
    cout << x << endl;  
}
// auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
for (auto &x : my_array) {
    x *= 2;
    cout << x << endl;  
}

上面for述句的第一部分定义被用来做范围迭代的变量,就像被声明在一般for循环的变量一样,其作用域仅只于循环的范围。而在":"之后的第二区块,代表将被迭代的范围。

实例


#include<iostream>  
#include<string>  
#include<cctype>  
using namespace std;  
  
int main()  
{  
    string str("some string");  
    // range for 语句  
    for(auto &c : str)  
    {  
        c = toupper(c);  
    }  
    cout << str << endl;  
    return 0;  
}

上面的程序使用Range for语句遍历一个字符串,并将所有字符全部变为大写,然后输出结果为:

SOME STRING

do-while循环

不像 forwhile 循环,它们是在循环头部测试循环条件。do...while 循环是在循环的尾部检查它的条件。

do...while 循环与 while 循环类似,但是 do...while 循环会确保至少执行一次循环。

C++ 中 do...while 循环的语法:

do
{
   statement(s);

}while( condition );

请注意,条件表达式出现在循环的尾部,所以循环中的 statement(s) 会在条件被测试之前至少执行一次。

如果条件为真,控制流会跳转回上面的 do,然后重新执行循环中的 statement(s)。这个过程会不断重复,直到给定条件变为假为止。

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 10;

   // do 循环执行
   do
   {
       cout << "a 的值:" << a << endl;
       a = a + 1;
   }while( a < 20 );
 
   return 0;
}
a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

嵌套循环

一个循环内可以嵌套另一个循环。C++ 允许至少 256 个嵌套层次。

C++ 中 嵌套 for 循环 语句的语法:

for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // 可以放置更多的语句 }

C++ 中 嵌套 while 循环 语句的语法:

while(condition) { while(condition) { statement(s); } statement(s); // 可以放置更多的语句 }

C++ 中 嵌套 do...while 循环 语句的语法:

do { statement(s); // 可以放置更多的语句 do { statement(s); }while( condition ); }while( condition );

关于嵌套循环有一点值得注意,可以在任何类型的循环内嵌套其他任何类型的循环。比如,一个 for 循环可以嵌套在一个 while 循环内,反之亦然。

循环控制语句

循环控制语句更改执行的正常序列。当执行离开一个范围时,所有在该范围中创建的自动对象都会被销毁。

C++ 提供了下列的控制语句。点击链接查看每个语句的细节。

控制语句 描述
break语句 终止 loopswitch 语句,程序流将继续执行紧接着 loop 或 switch 的下一条语句。
continue语句 引起循环跳过主体的剩余部分,立即重新开始测试条件。
goto语句 将控制转移到被标记的语句。但是不建议在程序中使用 goto 语句。

break语句 

C++ 中 break 语句有以下两种用法:

  1. break 语句出现在一个循环内时,循环会立即终止,且程序流将继续执行紧接着循环的下一条语句。
  2. 它可用于终止 switch 语句中的一个 case。

如果您使用的是嵌套循环(即一个循环内嵌套另一个循环),break 语句会停止执行最内层的循环,然后开始执行该块之后的下一行代码。

continue语句

C++ 中的 continue 语句有点像 break 语句。但它不是强迫终止,continue 会跳过当前循环中的代码,强迫开始下一次循环。

对于 for 循环,continue 语句会导致执行条件测试和循环增量部分。对于 whiledo...while 循环,continue 语句会导致程序控制回到条件测试上。

语法

C++ 中 continue 语句的语法:

goto语句

goto 语句允许把控制无条件转移到同一函数内的被标记的语句。

注意:在任何编程语言中,都不建议使用 goto 语句。因为它使得程序的控制流难以跟踪,使程序难以理解和难以修改。任何使用 goto 语句的程序可以改写成不需要使用 goto 语句的写法。

语法

C++ 中 goto 语句的语法:

goto label;
..
.
label: statement;

在这里,label 是识别被标记语句的标识符,可以是任何除 C++ 关键字以外的纯文本。标记语句可以是任何语句,放置在标识符和冒号(:)后边。

无限循环

如果条件永远不为假,则循环将变成无限循环。for 循环在传统意义上可用于实现无限循环。由于构成循环的三个表达式中任何一个都不是必需的,您可以将某些条件表达式留空来构成一个无限循环。


#include <iostream>
using namespace std;
 
int main ()
{
 
   for( ; ; )
   {
      printf("This loop will run forever.\n");
   }
 
   return 0;
}

当条件表达式不存在时,它被假设为真。您也可以设置一个初始值和增量表达式,但是一般情况下,C++ 程序员偏向于使用 for(;;) 结构来表示一个无限循环。

Note: Press Ctrl + C key to terminate an infinite loop.

                        One public interest is scanned No. java. More importantly, the little ape is willing to be a friend you programmed the road!

Articles starting address: www.javayihao.top

No public debut: java One

Guess you like

Origin www.cnblogs.com/javayihao/p/11906234.html