1. 程式人生 > >《Beginning C++17》-學習筆記-Chapter 05-Arrays and Loops

《Beginning C++17》-學習筆記-Chapter 05-Arrays and Loops

The size of an array must always be specified using a constant integer expression. Any integer expression that the compiler can evaluate at compile time may be used, though mostly this will be either an integer literal or a const integer variable that itself was initialized using a literal.

The index of a particular array element is its offset from the first element. The first element has an offset of 0 and therefore an index of 0

; an index value of 3 refers to the fourth array element—three elements from the first.

The type of the array will determine the amount of memory required for each element. The elements of an array are stored in one contiguous block of memory.

To define an array of values that cannot be modified, you simply add the keyword const

to its type.

The values returned by the sizeof operator have type of size_t. It is an unsigned integer type that is generally used, for instance, for sizes and counts of things.

size_t is not the name of a built-in fundamental type such as int, long, or double; it is a type alias defined by the Standard Library. More specifically, it is an alias for one of the unsigned integer types, sufficiently large to contain the size of any type the compiler supports (including any array). The alias is defined in the cstddef

header, as well as in a number of other headers. In practice, however, you mostly do not need to include (with #include) any of these headers explicitly to use the size_t alias; the alias is often indirectly defined already by including other more high-level headers (such as the iostream header).

Array index values are not checked to verify that they are valid. It’s up to you to make sure that you don’t reference elements outside the bounds of the array. If you store data using an index value that’s outside the valid range for an array, you’ll either inadvertently overwrite something in memory or cause a socalled segmentation fault or access violation (both terms are synonymous and denote an error that is raised by the operating system if and when it detects unauthorized memory access). Either way, your program will almost certainly come to a sticky end.

It is legal to define variables within a for loop initialization expression.

Any automatic variables declared within the scope of a loop do not exist outside it.

 

//兩種計算array中element個數的方法
#include <iostream>
#include <array>          // for std::size();

int main()
{
	int values[]{ 10, 10, 10, 10};

	std::cout << "Number of elements in the array is: " << sizeof(values) / sizeof(values[0]) << std::endl;/*sizeof operator returns the number of bytes that a variable occupies. This works with an entire array as well as with a single array element.*/

	std::cout << "Number of elements in the array is: " << std::size(values) << std::endl;
}

The standard formula \pi r^{^{2}} is used to calculates the area of a circle.

Any number that is a fraction with an odd denominator cannot be represented exactly as a binary floating-point value. 0.2 cannot be represented exactly in binary floating point.

Comparing floating-point numbers can be tricky. You should always be cautious when comparing the result of floating-point computations directly using operators such as ==, <=, or >=. Rounding errors almost always prevent the floating-point value from ever becoming exactly equal to the mathematical precise value.
 


The factorial of an integer n, written n!, is the product of all the integers from 1 to n; for example, 5! = 1 × 2 × 3 × 4 × 5 = 120.


The comma is a binary operator. It combines two expressions into a single expression, where the value of the operation is the value of its right operand. This means that anywhere you can put an expression, you can also put a series of expressions separated by commas.

#include <iostream>

int main()
{
	std::cout << (1,2,3,4,5) << std::endl;//輸出最後一個數字5
}

 


What is a range? An array is a range of elements, and a string is a range of characters. The containers provided by the Standard Library are all ranges as well.

#include <iostream>

int main()
{
	int range_1[]{ 1, 1, 1, 1, 1};
	int total_1{};
	for (int x : range_1)
	{
		total_1 += x;
	}
	std::cout << total_1 << std::endl;//輸出5

	int total_2{};
	for (auto x : { 1, 1, 1, 1, 1 })//A braced initializer list itself is a valid range
	{
		total_2 += x;
	}
	std::cout << total_2 << std::endl;//輸出5

}

#include <iostream>

int main()
{
	int n{};
	int sum{};
	while (++n <= 3)// variable n is first incremented, then compared with integer literal 3.
	{
		sum += n; 
	}
	std::cout << sum<< std::endl;//輸出6

}

#include <iostream>
#include <cctype>    /* For tolower() function,也可以改為#include <locale>*/

int main()
{
	char reply{};                                      // Stores response to prompt for input
	int count{};                                       // Counts the number of input values
                               
	do
	{
		std::cout << "You ate " << ++count << ((count ==1)?" apple":" apples") << std::endl;     

		std::cout << "Do you want to eat another apple? (y/n): ";
		std::cin >> reply;                                // Get response

	} while (tolower(reply) == 'y');//此處必須加一個分號

	std::cout << "You ate " << count << ((count == 1) ? " apple" : " apples") << " in total." << std::endl;
}

//利用nested loops 輸出10x10乘法表
#include <iostream>
#include <iomanip>

int main()
{

	for (size_t i{ 1 }; i <= 10; ++i)
	{   
		std::cout << std::setw(3) << i << "|"; // Start the row
		
		for (size_t j{ 1 }; j <= 10; ++j)
		{
			std::cout << std::setw(3) << i * j << "|";  // Output the values in a row.
		}
		std::cout << std::endl; 
	}

}

/*This outputs all the printable characters with code values from 0 to the maximum unsigned char value so it displays a handy list of the codes for the printable ASCII characters.*/
#include <iostream>
#include <iomanip>
#include <cctype>
#include <limits>

int main()
{
	// Output the column headings
	std::cout << std::setw(11) << "Character " << std::setw(13) << "Hexadecimal "
		<< std::setw(9) << "Decimal " << std::endl;
	std::cout << std::uppercase;                                      // Uppercase hex digits

	// Output characters and corresponding codes
	unsigned char ch{};
	do
	{
		if (!std::isprint(ch))                                           // If it's not printable...the isprint() function only returns true for printable characters.
			continue;                                                      // ...skip this iteration
		std::cout << std::setw(6) << ch                                  // Character
			<< std::hex << std::setw(12) << static_cast<int>(ch)   // Hexadecimal
			<< std::dec << std::setw(10) << static_cast<int>(ch)   // Decimal
			<< std::endl;
	} while (ch++ < std::numeric_limits<unsigned char>::max()); /*numeric_limits<>::max() function returns the maximum value for the type you place between the angled brackets.*/
}

// Sorting an array in ascending sequence - using an indefinite while loop
#include <iostream>
#include <iomanip>

int main()
{
	const int array_size{ 10 };
	int x[array_size]{10,9,8,7,6,5,4,3,2,1};                    
		
	std::cout << "Starting sort..." << std::endl;
	//bubble sort algorithm
	while (true)
	{
		bool swapped{ false };          
		for (size_t i{}; i < array_size-1; ++i)
		{
			if (x[i] > x[i + 1])          
			{
				const auto temp = x[i];
				x[i] = x[i + 1];
				x[i + 1] = temp;
				swapped = true;
			}
		}

		if (!swapped)                   // If there were no swaps, data are in order; otherwise, go round again.

	std::cout << "Result:\n";
	for (size_t i{}; i < array_size -1; ++i)
	{
		std::cout << std::setw(3) << x[i];
	}

	std::cout << std::endl;
}

/*A character array that is terminated by '\0' is referred to as a C-style string. */
#include <iostream>
#include <iomanip>

int main()
{

	int int_array[]{ 1, 2, 3, 4,5 };
	char char_array1[]{ 'a','i','o','u' };
	char char_array2[]{ "aiou" };/*array initiated with a string literal; the null character will be stored in the element following the last string character,*/

	std::cout << int_array <<std::endl;//輸出亂碼
	std::cout << char_array1 << std::endl; //輸出aiou以及一些亂碼
	std::cout << char_array2 << std::endl;/*輸出aiou. You can output a string stored in an array just by using the array name. 
						There must be a '\0' at the end of the array. If there isn’t, the standard output stream 
						will continue to output characters from successive memory locations, which almost certainly 
						contain garbage, until either a null character happens to turn up or an illegal memory access occurs.*/

}

#include <iostream>
#include <cctype>

int main()
{
	const int max_length{ 100 };              // Array size
	char text[max_length]{};                // Array to hold input string

	std::cout << "Enter a line of text:" << std::endl;

	std::cin.getline(text, max_length);		// Read a line of characters including spaces
        /* The getline() function for cin reads a sequence of characters, including 
spaces. By default, the input ends when a newline character, '\n', is read, which will 
be when you press the Enter key. The getline() function expects two arguments between 
the parentheses. The first argument specifies where the input is to be stored, which in 
this case is the text array. The second argument specifies the maximum number of 
characters that you want to store. This includes the string termination character, '\0', 
which will be automatically appended to the end of the input.*/
	std::cout << "You entered:\n" << text << std::endl;//輸出之前輸入的所有字元

}

#include <iostream>
#include <array>   //this header defines  array<T,N> template

int main()
{
	std::array<double, 100> values; //This creates an object that has 100 elements of type double.
	values.fill(1);//set all elements to 1.
	std::cout << values.size() << std::endl;// return the number of elements of variable values.

	//using range-based for loop to sum up all elements in values.
	int total{};
	for (auto w : values)
	{
		total += w;
	}
	std::cout << total <<std::endl;

	std::array<double, 100> values2 =values; //copy all elements of values to values2;
	std::cout << values2.at(99) << std::endl;// return the number of elements of variable values.

	std::cout << values[2] << std::endl;// return the value of the third element, which is 1.
	std::cout << values.at(2) << std::endl;/*return the third element as well; at() function for an array<> object will detect attempts to use an index value outside the legitimate range*/
	std::cout << ( values.front() == values[0] )<< std::endl;
	std::cout << ( values.back() == values[values.size() - 1] ) << std::endl;

	//using for loop to sum up all the elements in an array.
	double total1{};
	for (size_t i{}; i < values.size(); ++i)
	{
		total1 += values[i];
	}
	std::cout << total1 << std::endl;//return the sum of all elements , which is 100
	//using range-based for loop to sum up all the elements in an array.
	double total2{};
	for (auto value : values)
	{
		total2 += value;
	}
	std::cout << total1 << std::endl;//return the sum of all elements , which is 100

}

#include <iostream>
#include <vector>   //including this header for using the vector<> container 

int main()
{
	std::vector<double> values(20); //creating a vector<> container that contains 20 values of type double, all initialized to 0
	values.push_back(3.1415); // Add an element to the end of the vector
	std::cout << values.size() << std::endl;//output 21

	std::vector<long> numbers(20, 99L); // Initialize a vector that contains 20 long values - all 99
	std::cout << numbers.size() << std::endl;//output 21
	std::vector<long> numbers2;
	numbers2.assign(99, 20L); //  Using assign() functions reinitialize the contents of a vector that contains 99 long values - all 20
	std::cout << numbers2.size() << std::endl;//output 99

	std::vector<int> data(100, 99); // Contains 100 elements initialized to 99
	data.clear(); // Remove all elements
	std::cout << data.size() << std::endl;//output 0

	std::vector<int> data2(100, 99); // Contains 100 elements initialized to 99
	data2.pop_back(); // Remove the last element
	std::cout << data2.size() << std::endl;//output 99

}

 


// using a vector<T> container to store numbers
#include <iostream>
#include <iomanip>
#include <vector>

int main()
{
	std::vector<double> x;               // Stores data to be sorted

	while (true)
	{
		double input{};                   // Temporary store for a value
		std::cout << "Enter numbers you want to store one after another; enter a non-zero value, or 0 to end: ";
		std::cin >> input;
		if (input == 0)
			break;

		x.push_back(input);
	}

	std::cout << "Your entered the following data.\n";

	for (size_t i{}; i < x.size(); ++i)
	{
		std::cout << std::setw(8) << x[i];

	}
	std::cout << std::endl;
}

 


The range-based for loop iterates over all elements within a range. An array is a range of elements, and a string is a range of characters. The array and vector containers define a range so you can use the range-based for loop to iterate over the elements they contain.


#include <iostream>
#include <iomanip>

int main()
{
	std::cout << "顯示4位小數: "  << std::setprecision(4) << std::fixed << (static_cast<double>(4)) << std::endl;
	//std::fixed Output floating-point data in fixed-point notation.
	/*std::setprecision(n) Sets the floating-point precision or the number of decimal places to n digits.
	If the default floating - point output presentation is in effect, n specifies the
		number of digits in the output value.If fixed or scientific format has
		been set, n is the number of digits following the decimal point.The default
		precision is 6*/
}

#include <iostream>

int main()
{
	unsigned count{};
	char ch{};

	std::cout << "Please enter a sequence of characters terminated by '#':" << std::endl;

	do {
		std::cin >> ch;//cin不讀取空格,回車
		++count;
	} while (ch != '#');

	std::cout << "You entered " << count << " characters (not counting spaces)." << std::endl;
}

#include <iostream>

int main()
{
	const size_t max_num_characters{ 1'000 };
	char string[max_num_characters];

	std::cout << "Please enter a string: ";
	std::cin.getline(string, max_num_characters);

	// Count the number of characters
	size_t count{};
	for (; count < max_num_characters && string[count] != '\0'; ++count) {}

	// Print out the characters in reverse order
	for (size_t i = 1; i <= count; ++i)
	{
		std::cout << string[count - i];
	}
	std::cout << std::endl;
}
#include <iostream>

int main()
{
	const size_t max_num_characters{ 1'000 };
	char string[max_num_characters];

	std::cout << "Please enter a string: ";
	std::cin.getline(string, max_num_characters);

	// Count the number of characters
	size_t count{};
	while (count < max_num_characters && string[count] != '\0')
		++count;

	// Reverse the characters of the string entered by the user
	for (size_t i = 0; i < count / 2; ++i)
	{
		char temp = string[i];
		string[i] = string[count - i - 1];
		string[count - i - 1] = temp;
	}

	// Print out all characters, one by one
	for (size_t i = 0; i < count; ++i)
	{
		std::cout << string[i];
	}
	std::cout << std::endl;
}
//輸出1到1000之間不能被7整除的所有整數,每列顯示10個數字
#include <iostream>
#include <iomanip>
#include <vector>

int main()
{
	std::vector<unsigned> values;
	// Add element values 1 to bound
	for (unsigned i{ 1 }; i <= 1000; ++i)
		values.push_back(i);

	size_t count{};                              // Number of output values
	size_t perline{ 10 };                          // Number output perline                 
	for (auto value : values)
	{
		if (value % 7 == 0) continue;
		std::cout << std::setw(6) << value;
		if (++count % perline == 0) std::cout << "\n";
	}
	std::cout << std::endl;
}

//  Generate 93 Fibonacci numbers stored in an array.
// 93 was not an arbitrary choice for the number  of Fibonacci numbers.
// Fibonacci number grow fairly rapidly.
// 93 is the most that are possible with type unsigned long long.

#include <iostream>
#include <array>

int main()
{
	const size_t n{ 93 };
	std::array<unsigned long long, n> fib;
	fib[0] = fib[1] = 1UL;
	for (size_t i{ 2 }; i < n; ++i)
		fib[i] = fib[i - 1] + fib[i - 2];

	std::cout << "The first " << n << " Fibonacci numbers are:\n";
	for (auto number : fib)
	{
		std::cout << number << std::endl;
	}
}