CPP A3
CPP A3
CPP A3
Step 1: Write the Source Code: Enter the following source codes using a programming text editor (such as NotePad++ for Windows or gedit for
UNIX/Linux/Mac) or an Interac�ve Development Environment (IDE) (such as CodeBlocks, Eclipse, NetBeans or Visual Studio - Read the respec�ve "How-To"
ar�cle on how to install and get started with these IDEs).
Do not enter the line numbers (on the le� panel), which were added to help in the explana�on. Save the source file as "hello.cpp". A C++ source file should
be saved with a file extension of ".cpp". You should choose a filename which reflects the purpose of the program.
1 /*
2 * First C++ program that says hello (hello.cpp)
3 */
4 #include <iostream> // Needed to perform IO operations
5 using namespace std;
6
7 int main() { // Program entry point
8 cout << "hello, world" << endl; // Say Hello
9 return 0; // Terminate main()
10 } // End of main function
Step 2: Build the Executable Code: Compile and Link (aka Build) the source code "hello.cpp" into executable code ("hello.exe" in Windows or
"hello" in UNIX/Linux/Mac).
On IDE (such as CodeBlocks), push the "Build" bu�on.
On Text editor with the GNU GCC compiler, start a CMD Shell (Windows) or Terminal (UNIX/Linux/Mac) and issue these commands:
where g++ is the name of GCC C++ compiler; -o op�on specifies the output filename ("hello.exe" for Windows or "hello" for UNIX/Linux/Mac);
"hello.cpp" is the input source file.
// UNIX/Linux/Mac (Bash shell) - Run "hello" (./ denotes the current directory)
$ ./hello
hello, world
1 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
These are called comments. Comments are NOT executable and are ignored by the compiler; but they provide useful explana�on and documenta�on to your
readers (and to yourself three days later). There are two kinds of comments:
1. Mul�-line Comment: begins with /* and ends with */. It may span more than one lines (as in Lines 1-3).
2. End-of-line Comment: begins with // and lasts un�l the end of the current line (as in Lines 4, 7, 8, 9 and 10).
#include <iostream>
using namespace std;
The "#include" is called a preprocessor direc�ve. Preprocessor direc�ves begin with a # sign. They are processed before compila�on. The direc�ve
"#include <iostream>" tells the preprocessor to include the "iostream" header file to support input/output opera�ons. The "using namespace
std;" statement declares std as the default namespace used in this program. The names cout and endl, which is used in this program, belong to the std
namespace. These two lines shall be present in all our programs. I will explain their meaning later.
return 0;
terminates the main() func�on and returns a value of 0 to the opera�ng system. Typically, return value of 0 signals normal termina�on; whereas value of non-
zero (usually 1) signals abnormal termina�on. This line is op�onal. C++ compiler will implicitly insert a "return 0;" to the end of the main() func�on.
Preprocessor Directive : The #include (Line 4) is a preprocessor direc�ve and NOT a programming statement. A preprocessor direc�ve begins with hash
sign (#). It is processed before compiling the program. A preprocessor direc�ve is NOT terminated by a semicolon - take note of this unusual rule.
Block : A block is a group of programming statements enclosed by braces { }. This group of statements is treated as one single unit. There is one block in this
program, which contains the body of the main() func�on. There is no need to put a semicolon a�er the closing brace.
Comments : A mul�-line comment begins with /* and ends with */, which may span more than one line. An end-of-line comment begins with // and lasts
�ll the end of the line. Comments are NOT executable statements and are ignored by the compiler; but they provide useful explana�on and documenta�on. Use
comments liberally.
Whitespaces : Blank, tab, and newline are collec�vely called whitespaces. Extra whitespaces are ignored, i.e., only one whitespace is needed to separate the
tokens. Nevertheless, extra white spaces and newlines could help you and your readers be�er understand your program. Use extra whitespaces and newlines
liberally.
Case Sensitivity : C++ is case sensi�ve - a ROSE is NOT a Rose, and is NOT a rose.
Step 6: Run the executable code, with the input to produce the desried output.
2 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
1 /*
2 * Comment to state the purpose of this program (filename.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 int main() {
8 // Your Programming statements HERE!
9
10 return 0;
11 }
cout << "hello" << " world, " << "again!" << endl;
cout << "hello," << endl << "one more time. " << endl << 5 << 4 << 3 << " " << 2.2 << " " << 1.1 << endl;
A special symbol called endl (END-of-Line) can be used to produce a newline. Whenever an endl is printed, there is no visible output, but the cursor advances
to the beginning (le�-margin) of the next line. A string, which is enclosed by a pair of double quotes, will be printed as it is, including the white spaces and
punctua�on marks within the double quotes. Integers (such as 1, 2, 3) and floa�ng-point numbers (such as 1.1, 2.2) can be printed too. The output for the
above two output statements is as follows where the underscore denotes the final cursor posi�on.
Beside the endl, you can also use '\n', which denotes a newline character, to advance the cursor to the next line. Similarly, you could use '\t', which
denote a tab character, to advance the cursor to the next tab posi�on. '\n' and '\t' are known as escape sequences represen�ng ASCII codes Hex 0A (line-
feed) and Hex 09 (tab), respec�vely. For example,
The output shall look like (the exact tab stop posi�ons depend on your system's se�ng - eight spaces is used here):
Notes : I strongly recommend that you use endl to print a newline, instead of '\n'. This is because line delimiter is system dependent: Windows use
"\r\n"; UNIX/Linux/Mac use '\n'. The endl produces system-specific newline. Furthermore, endl guarantees that the output is flushed; while '\n' does
not.
Exercises
1. Write programs called PrintPatternX.cpp (where X from A to D) to print EACH of the following pa�erns. Use one "cout <<" for each line of
outputs. End each line by prin�ng an "endl".
* * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
(a) (b) (c) (d)
1 /*
3 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
2 * Prompt user for two integers and print their sum, difference, product and quotient
3 * (IntegerArithmetic.cpp)
4 */
5 #include <iostream>
6 using namespace std;
7
8 int main() {
9 int firstInt; // Declare a variable named firstInt of the type int (integer)
10 int secondInt; // Declare a variable named secondInt of the type int
11 int sum, difference, product, quotient;
12 // Declare 4 variables of the type int to keep the results
13
14 cout << "Enter first integer: "; // Display a prompting message
15 cin >> firstInt; // Read input from keyboard (cin) into firstInt
16 cout << "Enter second integer: "; // Display a prompting message
17 cin >> secondInt; // Read input into secondInt
18
19 // Perform arithmetic operations
20 sum = firstInt + secondInt;
21 difference = firstInt - secondInt;
22 product = firstInt * secondInt;
23 quotient = firstInt / secondInt;
24
25 // Print the results
26 cout << "The sum is: " << sum << endl;
27 cout << "The difference is: " << difference << endl;
28 cout << "The product is: " << product << endl;
29 cout << "The quotient is: " << quotient << endl;
30
31 return 0;
32 }
Arithmetic Operators: +, =, *, /
We used arithme�c operators +, _, *, / to compute the sum, difference, product and quo�ent. Take note that integer division produces a truncated integer
quo�ent (e.g., 99/4 gives 24).
cout << "Enter two integers (separated by space): "; // Put out a prompting message
cin >> firstInt >> secondInt; // Read two values into respective variables
sum = firstInt + secondInt;
cout << "The sum is: " << sum << endl;
Take note that the two integer values that you entered must be separated by a space.
Exercises
1. Follow the above example, write a program called FiveIntegerArithmetic.cpp to prompt user for 5 integers, with 5 "cin >>" statements, and
4 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
print their sum and product. Use five int variables integer1 to integer5 to store the five integers.
2. Repeat the above using one "cin >>" statement to read 5 integers.
7. What is a Program?
A program is a sequence of instruc�ons (called programming statements), execu�ng one a�er another -
usually in a sequen�al manner, as illustrated in the previous example and the following flow chart.
Example (Sequential): The following program (CircleComputation.cpp) prompts user for the
radius of a circle, and prints its area and circumference. Take note that the programming statements are
executed sequen�ally - one a�er another in the order that they are wri�en.
1 /*
2 * Prompt user for the radius of a circle and compute its area and circumference
3 * (CircleComputation.cpp)
4 */
5 #include <iostream>
6 using namespace std;
7
8 int main() {
9 double radius, circumference, area; // Declare 3 floating-point variables
10 const double PI = 3.14159265; // Declare and define PI
11
12 cout << "Enter the radius: "; // Prompting message
13 cin >> radius; // Read input into variable radius
14
15 // Compute area and circumference
16 area = radius * radius * PI;
17 circumference = 2.0 * radius * PI;
18
19 // Print the results
20 cout << "The radius is: " << radius << endl;
21 cout << "The area is: " << area << endl;
22 cout << "The circumference is: " << circumference << endl;
23
24 return 0;
25 }
cout << "The radius is: " << radius << endl;
cout << "The area is: " << area << endl;
cout << "The circumference is: " << circumference << endl;
print the results.
5 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
Take note that the programming statements inside the main() are executed one a�er another, sequen�ally.
Exercises
1. Follow the above example, write a program called RetanguleComputation.cpp to print the area and perimeter of a rectangle. Your program shall
prompt the user for the length and width of the rectangle, in doubles.
2. Follow the above example, write a program called CylinderComputation.cpp to print the surface area and volume of a cylinder. Your program
shall prompt the user for the radius and height of the cylinder, in doubles.
8. What is a Variable?
Computer programs manipulate (or process) data. A variable is used to
store a piece of data for processing. It is called variable because you can
change the value stored.
The above diagram illustrates 2 types of variables: int and double. An int variable stores an integer (whole number). A double variable stores a real
number.
To use a variable, you need to first declare its name and type, in one of the following syntaxes:
// Syntax: Declare multiple variables of the same type with initial values
var-type var-name-1 = initial-value-1, var-name-2 = initial-value-2,... ;
// Example:
int firstNumber = 1, secondNumber = 2;
Once a variable is declared, you can assign and re-assign a value to a variable, via the assignment operator "=". For example,
int number; // Declare a variable named "number" of the type "int" (integer)
number = 99; // Assign an integer value of 99 to the variable "number"
number = 88; // Re-assign a value of 88 to "number"
number = number + 1; // Evaluate "number + 1", and assign the result back to "number"
int sum = 0; // Declare an int variable named sum and assign an initial value of 0
sum = sum + number; // Evaluate "sum + number", and assign the result back to "sum", i.e. add number into sum
int num1 = 5, num2 = 6; // Declare and initialize two int variables in one statement, separated by a comma
6 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
double radius = 1.5; // Declare a variable name radius, and initialize to 1.5
int number; // ERROR: A variable named "number" has already been declared
sum = 55.66; // WARNING: The variable "sum" is an int. It shall not be assigned a floating-point number
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a text string
x=x+1? x+y=1?
Assignment (=) in programming is different from equality in Mathema�cs. e.g., "x=x+1" is invalid in Mathema�cs. However, in programming, it means compute
the value of x plus 1, and assign the result back to variable x.
"x+y=1" is valid in Mathema�cs, but is invalid in programming. In programming, the RHS of "=" has to be evaluated to a value; while the LHS shall be a variable.
That is, evaluate the RHS first, then assign to LHS.
Some languages uses := as the assignment operator to avoid confusion with equality.
Addi�on, subtrac�on, mul�plica�on, division and remainder are binary operators that take two operands (e.g., x + y); while nega�on (e.g., -x), increment
and decrement (e.g., x++, --x) are unary operators that take only one operand.
Example
The following program (TestArithmetics.cpp) illustrates these arithme�c opera�ons:
1 /*
2 * Test arithmetic operations (TestArithmetics.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 int main() {
8
9 int number1, number2; // Declare 2 integer variable number1 and number2
10 int sum, difference, product, quotient, remainder; // declare 5 int variables
11
12 // Prompt user for the two numbers
13 cout << "Enter two integers (separated by space): ";
14 cin >> number1 >> number2;
15
16 // Do arithmetic Operations
17 sum = number1 + number2;
18 difference = number1 - number2;
19 product = number1 * number2;
20 quotient = number1 / number2;
21 remainder = number1 % number2;
22
23 cout << "The sum, difference, product, quotient and remainder of "
24 << number1 << " and " << number2 << " are "
25 << sum << ", "
26 << difference << ", "
27 << product << ", "
28 << quotient << ", and "
29 << remainder << endl;
7 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
30
31 // Increment and Decrement
32 ++number1; // Increment the value stored in variable number1 by 1
33 // same as "number1 = number1 + 1"
34 --number2; // Decrement the value stored in variable number2 by 1
35 // same as "number2 = number2 - 1"
36 cout << "number1 after increment is " << number1 << endl;
37 cout << "number2 after decrement is " << number2 << endl;
38
39 quotient = number1 / number2;
40 cout << "The new quotient of " << number1 << " and " << number2
41 << " is " << quotient << endl;
42
43 return 0;
44 }
cout << "The sum, difference, product, quotient and remainder of "
<< number1 << " and " << number2 << " are "
<< sum << ", "
<< difference << ", "
<< product << ", "
<< quotient << ", and "
<< remainder << endl;
prints the results of the arithme�c opera�ons, with the appropriate string descrip�ons in between. Take note that text strings are enclosed within double-
quotes, and will get printed as they are, including the white spaces (but without the double quotes). To print the value stored in a variable, no double quotes
should be used. For example,
++number1;
--number2;
illustrate the increment and decrement opera�ons. Unlike '+', '-', '*', '/' and '%', which work on two operands (binary operators), '++' and '--'
operate on only one operand (unary operators). ++x is equivalent to x = x + 1, i.e., increment x by 1. You may place the increment operator before or a�er
the operand, i.e., ++x (pre-increment) or x++ (post-increment). In this example, the effects of pre-increment and post-increment are the same. I shall point out
the differences in later sec�on.
Exercises
1. Introduce one more int variable called number3, and prompt user for its value. Print the sum and product of all the three integers.
2. In Mathema�cs, we could omit the mul�plica�on sign in an arithme�c expression, e.g., x = 5a + 4b. In programming, you need to explicitly provide
all the operators, i.e., x = 5*a + 4*b. Try prin�ng the sum of 31 �mes of number1 and 17 �mes of number2 and 87 �me of number3.
8 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
could use a loop in your program to perform a repe��ve task, that is what the dumb computers are good at.
Example
Try the following program SumNumbers.cpp, which sums all the integers from 1 to an upperbound provided by the user, using a so-called while-loop.
1 /*
2 * Sum from 1 to an upperbound using a while-loop (SumNumbers.cpp).
3 */
4 #include <iostream>
5 using namespace std;
6
7 int main() {
8 int sum = 0; // Declare an int variable sum to accumulate the numbers
9 // Set the initial sum to 0
10 int upperbound; // Sum from 1 to this upperbound
11
12 // Prompt user for an upperbound
13 cout << "Enter the upperbound: ";
14 cin >> upperbound;
15
16 // Use a loop to repeatedly add 1, 2, 3,..., up to upperbound
17 int number = 1;
18 while (number <= upperbound) {
19 sum = sum + number; // accumulate number into sum
20 ++number; // increment number by 1
21 }
22 // Print the result
23 cout << "The sum from 1 to " << upperbound << " is " << sum << endl;
24
25 return 0;
26 }
int number = 1;
while (number <= upperbound) {
sum = sum + number;
++number;
}
This is the so-called while-loop. A while-loop takes the following syntax:
initialization-statement;
while (test) {
loop-body;
}
next-statement;
As illustrated in the flow chart, the ini�aliza�on statement is first executed. The test is then
checked. If the test is true, the body is executed. The test is checked again and the process repeats
un�l the test is false. When the test is false, the loop completes and program execu�on con�nues
to the next statement a�er the loop.
In our program, the ini�aliza�on statement declares an int variable named number and
ini�alizes it to 1. The test checks if number is equal to or less than the upperbound. If it is true,
the current value of number is added into the sum, and the statement ++number increases the
value of number by 1. The test is then checked again and the process repeats un�l the test is
false (i.e., number increases to upperbound+1), which causes the loop to terminate.
Execu�on then con�nues to the next statement (in Line 23).
In this example, the loop repeats upperbound �mes. A�er the loop is completed, Line 23 prints the result with a proper descrip�on.
Exercises
1. Modify the above program to sum all the number between a lowerbound and an upperbound provided by the user.
2. Modify the above program to sum all the odd numbers between 1 to an upperbound. (Hint: Use "number = number + 2".)
9 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
3. Modify the above program to sum all the numbers between 1 to an upperbound that are divisible by 7. (Hint: Use "number = number + 7")
4. Modify the above program to find the sum of the square of all the numbers from 1 to an upperbound, i.e. 1*1 + 2*2 + 3*3 +...
5. Modify the above program to compute the product of all the numbers from 1 to 10. (Hint: Use a variable called product instead of sum and ini�alize
product to 1. Ans: 3628800.) Based on this code, write a program to display the factorial of n, where n is an integer between 1 to 12.
1 /*
2 * Sum the odd and even numbers from 1 to an upperbound (SumOddEven.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 int main() {
8 int sumOdd = 0; // For accumulating odd numbers, init to 0
9 int sumEven = 0; // For accumulating even numbers, init to 0
10 int upperbound; // Sum from 1 to this upperbound
11
12 // Prompt user for an upperbound
13 cout << "Enter the upperbound: ";
14 cin >> upperbound;
15
16 // Use a loop to repeatedly add 1, 2, 3,..., up to upperbound
17 int number = 1;
18 while (number <= upperbound) {
19 if (number % 2 == 0) { // even number
20 sumEven = sumEven + number;
21 } else { // odd number
22 sumOdd = sumOdd + number;
23 }
24 ++number; // increment number by 1
25 }
26
27 // Print the results
28 cout << "The sum of odd numbers is " << sumOdd << endl;
29 cout << "The sum of even numbers is " << sumEven << endl;
30 cout << "The difference is " << (sumOdd - sumEven) << endl;
31
32 return 0;
33 }
if (number % 2 == 0) {
sumEven = sumEven + number;
} else {
sumOdd = sumOdd + number;
}
This is a condi�onal statement. The condi�onal statement can take one these forms: if-then or if-then-else.
// if-then
if ( test ) {
true-body;
}
// if-then-else
if ( test ) {
true-body;
} else {
false-body;
}
10 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
In our program, we use the remainder operator (%) to compute the remainder of number divides by 2. We then compare the remainder with 0 to test for
even number.
Comparison Operators
There are six comparison (or rela�onal) operators:
Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-equal sign (=) is the assignment operator.
There are three so-called logical operators that operate on the boolean condi�ons:
For examples:
Exercises
1. Write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17, but not by 30.
2. Write a program to print all the leap years between AD1 and AD2010, and also print the number of leap years. (Hints: use a variable called count, which
is ini�alized to zero. Increment the count whenever a leap year is found.)
In programming, real numbers such as 3.1416 and -55.66 are called floa�ng-point numbers, and belong to a type called double. You can express floa�ng-
point numbers in fixed nota�on (e.g., 1.23, -4.5) or scien�fic nota�on (e.g., 1.2e3, -4E5.6) where e or E denote the exponent of base 10.
Example
1 /*
2 * Convert temperature between Celsius and Fahrenheit
3 * (ConvertTemperature.cpp)
11 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
4 */
5 #include <iostream>
6 using namespace std;
7
8 int main() {
9 double celsius, fahrenheit;
10
11 cout << "Enter the temperature in celsius: ";
12 cin >> celsius;
13 fahrenheit = celsius * 9.0 / 5.0 + 32.0;
14 cout << celsius << " degree C is " << fahrenheit << " degree F." << endl << endl;
15
16 cout << "Enter the temperature in fahrenheit: ";
17 cin >> fahrenheit;
18 celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
19 cout << fahrenheit << " degree F is " << celsius << " degree C." << endl;
20
21 return 0;
22 }
At �mes, you may need both int and double in your program. For example, keeping the sum from 1 to 100 (=5050) as an int, and their average 50.5 as
a double. You need to be extremely careful when different types are mixed.
You can assign an integer value to a double variable. The integer value will be converted to a double value automa�cally, e.g., 3 → 3.0. For example,
int i = 3;
double d;
d = i; // 3 → 3.0, d = 3.0
d = 88; // 88 → 88.0, d = 88.0
double nought = 0; // 0 → 0.0; there is a subtle difference between int of 0 and double of 0.0
However, if you assign a double value to an int variable, the frac�onal part will be lost. For example,
double d = 55.66;
int i;
i = d; // i = 55 (truncated)
Some C++ compilers (e.g., g++ version 3) signal a warning for trunca�on, while others (e.g., g++ version 4) do not:
You should study the "warning messages" carefully - which signals a poten�al problem in your program, and rewrite the program if necessary. C++ allows you to
ignore the warning and run the program. But, the frac�onal part will be lost during the execu�on.
For example,
double d = 5.5;
int i;
i = int(d); // int(d) -> int(5.5) -> 5 (assigned to i)
i = int(3.1416); // int(3.1416) -> 3 (assigned to i)
i = (int)3.1416; // same as above
Similarly, you can explicitly convert an int value to double by invoking type-cas�ng opera�on too.
12 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
Example
Try the following program and explain the outputs produced:
1 /*
2 * Testing type cast (TestCastingAverage.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 int main() {
8 int sum = 0; // Sum in "int"
9 double average; // average in "double"
10
11 // Compute the sum from 1 to 100 (in "int")
12 int number = 1;
13 while (number <= 100) {
14 sum = sum + number;
15 ++number;
16 }
17 cout << "The sum is " << sum << endl;
18
19 // Compute the average (in "double")
20 average = sum / 100;
21 cout << "Average 1 is " << average << endl;
22 average = double(sum) / 100;
23 cout << "Average 2 is " << average << endl;
24 average = sum / 100.0;
25 cout << "Average 3 is " << average << endl;
26 average = double(sum / 100);
27 cout << "Average 4 is " << average << endl;
28
29 return 0;
30 }
For the second average, the value of sum (of int) is first converted to double. Subsequently, double/int produces double.
For the fourth average, int/int produces an int (of 50), which is then casted to double (of 50.0) and assigned to average (of double).
Exercises
1. Write a program called HarmonicSeriesSum to compute the sum of a harmonic series 1 + 1/2 + 1/3 + 1/4 + .... + 1/n, where n =
1000. Your program shall prompt user for the value of n. Keep the sum in a double variable, and take note that 1/2 gives 0 but 1.0/2 gives 0.5.
Try compu�ng the sum for n=1000, 5000, 10000, 50000, 100000.
Hints:
/*
* Sum harmonics Series (HarmonicSeriesSum.cpp)
*/
#include <iostream>
using namespace std;
int main() {
int maxDenominator; // max denominator to sum to
double sum = 0.0; // For accumulating sum in double
int denominator = 1;
while (denominator <= maxDenominator) {
// Beware that int/int gives int
......
++denominator; // next
}
// Print the sum
......
}
2. Write a program called GeometricSeriesSum to compute the sum of a geometric series 1 + 1/2 + 1/4 + 1/8 + .... + 1/n. You
13 of 14 22/03/2020, 19:36
An Introduction to C++ Programming for First-time Programmers - C+... https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introducti...
program shall prompt for the value of n. (Hints: Use post-processing statement of denominator = denominator * 2.)
14. Summary
I have presented the basics for you to get start in programming. To learn programming, you need to understand the syntaxes and features involved in the
programming language that you chosen, and you have to prac�ce, prac�ce and prac�ce, on as many problems as you could.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
14 of 14 22/03/2020, 19:36