// forloop.cpp -- introducing the for loop
#include <iostream>
int main()
{
using namespace std;
int i; // create a counter
// initialize; test ; update
for (i = 0; i < 5; i++)
cout << "C++ knows loops.\n";
cout << "C++ knows when to stop.\n";
// cin.get();
return 0;
}
该函数主要探究for的特性
i从零开始加到4,到5时退出循环,共循环5次
结果打印5次
5.2 num_test.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "Enter the starting countdown value: ";
int limit;
cin >> limit;
int i;
for (i = limit; i; i--) // quits when i is 0
cout << "i = " << i << "\n";
cout << "Done now that i = " << i << "\n";
// cin.get();
// cin.get();
return 0;
}
该函数更改了传统for循环中i累加的情况,使i累减
并且该函数还将输入值作为i的初始值
最后将i的值作为终止条件,当i减到0时终止循环
综上若输入i的值为5,则该循环循环5次,到0退出循环
5.3 express.cpp
#include <iostream>
int main()
{
using namespace std;
int x;
cout << "The expression x = 100 has the value ";
cout << (x = 100) << endl;
cout << "Now x = " << x << endl;
cout << "The expression x < 3 has the value ";
cout << (x < 3) << endl;
cout << "The expression x > 3 has the value ";
cout << (x > 3) << endl;
cout.setf(ios_base::boolalpha); //a newer C++ feature
cout << "The expression x < 3 has the value ";
cout << (x < 3) << endl;
cout << "The expression x > 3 has the value ";
cout << (x > 3) << endl;
/// cin.get();
return 0;
}
#include <iostream>
const int ArSize = 16; // example of external declaration
int main()
{
long long factorials[ArSize];
factorials[1] = factorials[0] = 1LL;
for (int i = 2; i < ArSize; i++)
factorials[i] = i * factorials[i - 1];
for (int i = 0; i < ArSize; i++)
std::cout << i << "! = " << factorials[i] << std::endl;
// std::cin.get();
return 0;
}
#include <iostream>
int main()
{
using std::cout; // a using declaration
using std::cin;
using std::endl;;
cout << "Enter an integer: ";
int by;
cin >> by;
cout << "Counting by " << by << "s:\n";
for (int i = 0; i < 100; i = i + by)
cout << i << endl;
// cin.get();
// cin.get();
return 0;
}