C++ Primer Fifth Edition: 1.12 1.13 1.14 1.16

Exercise 1.12: Sum of values ​​from -100 to 100

Exercise 1.13

#include<iostream>
using namespace std;

int main()
{
    
    //1.9
	int sum = 0;

	for (int val = 50; val <= 100; ++val)
		sum += val;
	cout << sum << endl;

	return 0;
}
#include<iostream>
using namespace std;

int main()
{
    
    //1.10
	for (int val = 10; val >= 0; --val)
		cout << val << ' ';
	cout << endl;

	return 0;
}
#include<iostream>
using namespace std;

int main()
{
    
    //1.11
	int val1, val2;

	cout << "Please input two integer:" << endl;
	cin >> val1 >> val2;

	for (; val1 <= val2; ++val1)
		cout << val1 << ' ';
	cout << endl;

	return 0;
}

Exercise 1.14: 1. The
for loop is suitable for the situation where the number of loops is known and the variable initialization and determination are in the head
2. The while loop is suitable for the situation where the number of loops is unknown

Exercise 1.16

#include<iostream>
using namespace std;

int main()
{
    
    
	int sum = 0;
	int val;

	while (cin >> val)
		sum += val;

	cout << sum << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/Xgggcalled/article/details/108521851