C++ For 循环教程

476 阅读2分钟

For loop in C++ Program | C++ For Loop Example

循环有三种类型: for循环while循环do-while循环。在本教程中,我们将学习 for循环

要理解C++中的for循环,我们必须事先了解C++中的循环。 当我们想让某段代码运行多次时,就会用到循环。我们使用循环来重复执行代码的语句,直到一个特定的条件得到满足。它减轻了程序员的工作,也缩短了代码的长度。

C++中的for循环

C++中的for 循环是一种重复控制结构,通常用于更有效地编写代码,它应该被执行特定次数。

例如,如果我们想打印从1到1000的数字,那么如果我们不使用循环,我们必须写1000条不同的打印语句来打印从1到1000的数字。在循环的帮助下,我们可以在2行内写完这段代码。但是,首先,我们需要运行循环并给出迭代条件。

for 循环如何工作

  1. 一个初始化语句在开始时只执行一次。
  2. 然后,对测试表达式进行评估。
  3. 如果测试表达式是假的,那么for循环将被终止。但是如果测试表达式为真,for 循环内部的代码将被执行,并且更新表达式被更新。
  4. 一个测试表达式被评估,这个过程重复进行,直到测试表达式为假。

for 循环的语法

for(initialization; condition; increment/decrement)
{
	//statements
}

请看下面的例子。

for(int i=1;i<=100;i++)
{
	cout<<i<<endl;
}

解释一下。上面的代码将打印从1到100的数字。

for 循环的流程图

For loop in C++ Program

for 循环的参数

for(initialization; condition; increment/decrement)
{
	// Statements
}

执行初始化步骤是为了初始化程序计数器;它只做一次。程序计数器也被称为循环控制变量。

下一个参数是条件,用于检查循环应该运行的条件。

之后,有一个增量/减量计数器,一旦语句被执行,就会增加或减少该计数器。

C++中for循环的程序示例

Q1- 写一个程序来展示for循环的机制。

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print numbers from 1 to 20 using for loop"<<endl;
	for(int i=1;i<=20;i++)
	{
		cout<<"The number is:"<<i<<endl;
	}
	return 0;
	
}

请看输出。

Example program of for loop in C++

Q2-写一个程序,用for循环打印1到20的所有偶数。

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print even numbers from 1 to 100 using for loop"<<endl;
	for(int i=2;i<=100;i=i+2)
	{
		cout<<"The even number is:"<<i<<endl;
	}
	return 0;
	
}

请看输出。

C++ For Loop

Q3- 写一个程序,用for循环来打印1到100的所有奇数。

#include<iostream>
using namespace std;
int main()
{
	cout<<"We will print odd numbers from 1 to 100 using for loop"<<endl;
	for(int i=1;i<=100;i=i+2)
	{
		cout<<"The odd number is:"<<i<<endl;
	}
	return 0;
	
}

请看输出。

C++ For Loop Example

C++中的无限for循环

循环是无限的,当它重复执行并且从未停止。这通常是错误发生的。当你在for循环中设置一个条件,使其永远不返回false时,它就成为无限循环。

请看下面的例子。

#include <iostream>
using namespace std;
int main(){
   for(int i=1; i>=1; i++){
      cout<<"Value of variable i is: "<<i<<endl;
   }
   return 0;
}

这是一个无限循环,因为我们增加了一个i的值,所以它总是满足i>=1的条件;该条件永远不会返回错误。

下面是另一个无限循环的例子。

// infinite loop
for ( ; ; ) {
   // statement(s)
}

使用for循环显示一个数组的元素

请看下面的程序,它使用for循环显示一个数组的项目。

#include <iostream>
using namespace std;
int main(){
   int arr[]={21,9,56,99, 202};
   /* We have set the value of variable i
    * to 0 as the array index starts with 0
    * which means the first element of array 
    * starts with zero index.
    */
   for(int i=0; i<5; i++){
      cout<<arr[i]<<endl;
   }
   return 0;
}

请看下面的输出。

21
9
56
99
202

本教程到此为止。