“Chapter 3. Flow Control of Statements” in “Introduction to Computer Programming with Python”
Chapter 3 Flow Control of Statements
If you praise computers for their diligence when they iterate operations tirelessly trillions of trillions of times, you must also appreciate their intelligence when they do certain things only if certain conditions are met, because decision making is important for all intelligent beings, including modern computers. All computer programming languages provide constructs for decision making—to run a statement or a block of statements only under certain conditions. Python does the same.
In Chapter 3, you will learn how to use the if, if-else, if-elif, and if-elif-else statements to instruct computers to do certain things only under certain conditions.
Learning Objectives
After completing this chapter, you should be able to
- • use an if statement to run a code block only under a set condition.
- • use if-else to run two code blocks under two different conditions.
- • use if-elif to make multiple selections.
- • use if-elif-else to make multiple selections.
- • use for statements to make loops to run code blocks repeatedly.
- • use while statements correctly and efficiently to put a code block in a loop.
- • use break and continue statements correctly to change the flow of program within the code block.
3.1 Selective with the if Statement
In Python, all selections are done with the if statement, which can take multiple forms. The following is a code sample showing how if is used to make a single selection.
Code sample in Python interactive mode | |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |
|
Note that a code block for if statements must begin on the next line after a colon : and be properly indented, as shown below:
n = int(input("n = ?"))
if n >= 0:
Code block
Note: Each code block must be properly indented to indicate what the code block belongs to.
The conditions for an if statement can be any Boolean expression, as discussed in 2.1.
3.2 Single-branch selective with if Statement
In the above example, the program specifies only what to do when n >= 0 but does not say what to do otherwise. With Python, you can further specify what can be done if n >= 0 is not true. The following is a revised code sample—it simply tells the user to input a positive number.
Code sample in Python interactive mode | |
---|---|
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
Note that no condition needs to be specified for an else clause because it implies that the condition is the negation of the condition for that if clause—that is, not n >= 0.
With the if and if-elif statements studied above, you can make single- or two-branch selections, which are depicted in Figures 3-1 and 3-2.
Figure 3-1: Flowchart of an if statement
Figure 3-2: Flowchart of an if-else statement
3.3 Multiple-branch selective with if-elif-… and if-elif-…-else Statements
In decision making, there can be multiple options, each of which requires different actions to be taken. In Python, multiple selections can be made with if-elif and if-elif-else statements. The logic flow of these two statements is depicted in the following diagrams.
The flowchart in Figure 3-3 shows the logic flow of an if-elif-elif…elif statement without else, which can be used to make multiple selections. The flowchart in Figure 3-4 illustrates the logic flow of an if-elif-elif…else statement for multiple selections.
Figure 3-3: Flowchart of an if-elif-elif-elif… statement
Figure 3-4: Flowchart of an if-elif-elif-else statement
Now, you are ready to tackle a real problem: to decide what letter grade should be assigned for a given numeric mark of a student in a course, according to Table 3-1.
Number of selections needed | Numeric grade (%) | Alpha/letter grade |
---|---|---|
1 | 90–100 | A+ |
2 | 85–89 | A |
3 | 80–84 | A− |
4 | 76–79 | B+ |
5 | 73–75 | B |
6 | 70–72 | B− |
7 | 67–69 | C+ |
8 | 64–66 | C |
9 | 60–63 | C− |
10 | 55–59 | D+ |
11 | 50–54 | D |
12 | 0–49 | F |
The table shows only integer numeric grades, but decimal inputs, automatically rounded to the nearest integer, are also allowed. The case study is shown in Table 3-2.
The problem | In this case study, design a program using an if-elif-else statement to convert numeric grades to alpha/letter grades. |
The analysis and design | As the above grade-conversion table shows, the program needs to make 12 selections. For each selection, a letter grade will be printed out when the numeric grade falls within the corresponding interval. |
The code |
|
The result | Please tell me a numeric grade between 0 and 100: 88 alpha/letter grade for 88 is A |
The code above didn’t explicitly specify the upper bounds of the intervals shown in the grade conversion table because it takes advantage of the if-elif-elif statement—that is, the upper bound of the current if condition has been implicitly satisfied when the previous if condition is not satisfied, and the program flow gets into the current elif selection. Taking the first elif statement as an example, since the previous if condition is number_grade >= 90, when the condition is not satisfied and the program flow goes to the elif, the number_grade must be less than 90, which is equal to number_grade <= 89, the upper bound of the first elif condition.
After you run the code on your computer, you may notice that for each conversion, you have to rerun the program to get another chance to input a numeric grade. How can you do as many conversions as you want until you tell the program to stop? You’ll be able to do that after learning how to put a code block in a loop in the next chapter.
3.4 Iterate with for Statement
Computers can do many amazing things. Many of these amazing things can only be done in thousands or even trillions of trillions of steps. Luckily, programmers don’t need to write trillions of trillions of statements in a computer program, because computers can be instructed to run a block of statements in a loop as many times as needed without complaint. As such, a programmer must be able to correctly put code blocks in loops when programming. In this and the next section of this chapter, you will learn how to use for statements and while statements correctly and effectively to put code blocks in loops.
In Python, the for statement is one of only two statements that can be used to make loops or iterations. In previous sections, you already saw some examples using the for statement. Formally, a for loop takes the following form:
for <iteration variable> in <sequence to be looped through>:
<Code Block>
in which for and in are keywords, and the iteration variable is used to take items one by one from the sequence, which can be a list, a tuple, a string, or an iterable object or generator, as you will see. The code block is a block of Python code to be executed in each iteration of the loop. The following example loops through a list of integers and calculates the cube of each.
Figure 3-5: Flowchart of the for loop
In [ ]: |
|
Out [ ]: | The cube of 1 is 1 The cube of 2 is 8 The cube of 3 is 27 The cube of 4 is 64 The cube of 5 is 125 The cube of 6 is 216 The cube of 7 is 343 The cube of 8 is 512 The cube of 9 is 729 The cube of 10 is 1000 |
A flowchart describing the for loop is shown in Figure 3-5.
Now we are ready to solve a more complex problem, shown in Table 3-3.
The task | Print a multiplication table from 1 * 1 to 9 * 9, and the result table should be a right triangle. |
Analysis and design | The resulting multiplication table should be a right triangle like this: 1 x 1 = 1 1 x 2 = 2 2 x 2 = 4 1 x 4 = 3 2 x 3 = 6 3 x 3 = 9 … so we will need two loops: the outer one is used to loop through the row, whereas the inner one loops through the column of each row. The algorithm is as follows: Step 1: Start a row I, I = 1, 2,…, 9 Step 2: Start a column j of row I, j = 1,…i Step 3: Print j × I = j * i on the same line until I * i Step 4: Go back to step 1 and finish all rows |
|
|
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
| |
Output in terminal | 1 x 1 = 1 1 x 2 = 2 2 x 2 = 4 1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16 1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25 1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36 1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49 1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 64 1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81 |
Our next problem, in Table 3-4, is to find all the Pythagorean triples of integers less than an integer given by the user.
The task | Three integers—A, B, and C—are called a Pythagorean triple when C * C = A * A + B * B. This program will take an integer input by the user and find all the Pythagorean triples of integers less than that integer. |
Analysis and design | Step 1: Get input from user Step 2: Find all the Pythagorean triples Step 3: Print all the triples Step 2.0: Make an empty list, say, plist =[] Step 2.1: One loop for A = 1…user input Step 2.2: One loop for B = 1…user input Step 2.3: One loop for C = 1…user input Step 2.4: If C * C = A * A + B * B, add the triple to the list plist |
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |
| |
Output in terminal | Give me a big integer:39 (3, 4, 5) (5, 12, 13) (6, 8, 10) (7, 24, 25) (8, 15, 17) (9, 12, 15) (10, 24, 26) (12, 16, 20) (12, 35, 37) (15, 20, 25) (15, 36, 39) |
A for statement can have multiple iteration variables if needed. In order to make it work, however, each item of the iteration sequence needs to have multiple values for the multiple iteration variables, as shown in the following example:
for i, j in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]:
print(f"{i} * {j} = {i * j}")
or
for i, j in zip(range(5), range(5)): # zip is a special function
print(f"{i + 1} * {j + 1} = {(i + 1) * (j + 1)}")
In the above, zip is a built-in function that takes an element from each iterable and forms a tuple, as shown below:
>>> list(zip(range(5), range(5), range(6)))
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4)]
The function zip will stop making tuples when the shortest iterable has reached the end.
Note that the following two statements are totally different:
for i in range(5):
for j in range(5):
print(f"{j + 1} * {i + 1} = {(i + 1)*(j + 1)}")z
versus
for i, j in zip(range(5), range(5)):
print(f"{i + 1} * {j + 1} = {(i + 1)*(j + 1)}")
The first statement is two loops nested, whereas the second is a single loop.
You may copy and paste the code into Jupyter Notebook to find out why and how.
Using break and continue Statements and an else Clause Within Loops
Chapter 2 discussed what the break statement and continue statement do. Within a for loop, if you want to get out of the iteration immediately when something has occurred, you can use a break statement; if you want to go to the next item in the iteration sequence right away, you can use a continue statement.
A for statement can also have an else clause whose code block will be executed when the iteration sequence is used up. The following code example taken from the Python documentation explains how the break statement and else clause can be used on a for loop.
In [ ]: |
|
Out [ ]: | 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 |
In the example above, pay particular attention to the indentation of else. The else block is treated as a clause of the inner for statement because it has the same indentation as the inner for. If it were indented the same as the if statement, the else block would become part of the if statement.
Common Coding Mistakes with the for Loop
Because Python made the for loop to run an iteration variable or variables through a sequence with a finite number of items, it has essentially avoided some mistakes common in other languages such as C, C++, and Java. You should, however, remember to not change the value of any iteration variable within the code block of a for loop because it needs to be changed automatically by Python interpreter to the next item in the sequence. The iteration might be unexpected if the value of the iteration variable is changed in the code block.
3.5 Iterate with the while Statement
The while statement is another statement you can use to make loops. As discussed in Chapter 2, while is best used if you know when the loop should stop but do not know how many times the code will iterate. For the problem solved in the previous section, even though you also know when each loop should stop, it can still be coded with the while statement, as shown below:
The code | |
---|---|
|
|
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
|
Figure 3-6: Flowchart illustrating the while loop
While a for loop can always be replaced with a while loop, a while loop cannot be replaced with a for loop in cases where the number of iterations is unknown.
Consider the problem of calculating the average of the student marks taken from user input. Either the total number of marks is unknown or you do not expect the user to count how many marks they input, so it is not possible to use a for loop to solve the problem. However, you do know there will be no negative marks, which can then be used to indicate the end of the input. Hence, you can use a while loop to take input from the user until you get a negative number from the user. The program is shown in Table 3-5.
Code sample in VS Code IDE | |
---|---|
The task | Get student marks from user input and calculate the average mark, using a negative number input by the user to indicate the end of marks. |
Analysis and design | You don’t know how many marks will be input from the user, but you do know there will be no negative marks. You can then use a negative number, input by the user, to end the application and use the while loop to iterate. To calculate the average, you need to know the sum of all the marks as well as the total number of marks. For the former, you need to add each mark to the total, whereas for the latter, you need to use a counter to count every mark. Use the variable total to keep the sum and use the variable count to keep the number of marks. Both need to be initialized to 0. The algorithm is below: Step 1: Initialize both count and total to 0 Step 2: Take an input from user and convert it to a float number Step 3: If the number is a mark (>= 0), then do the following: Step 3.1: Increase count by 1 Step 3.2: Add mark to total Step 3.3: Get another input from user and convert to float Step 3.4: Go back to Step 3 Step 4: Calculate the average using total/count and print out the result. Step 5: End the program |
|
|
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
Output in terminal | Please input a mark or a negative number to end: 78 Please input next mark or a negative number to end: 89 Please input next mark or a negative number to end: 98 Please input next mark or a negative number to end: 88 Please input next mark or a negative number to end: 85 Please input next mark or a negative number to end: -1 The average of the 5 marks is 87.6 |
Similarly, we can also write a program that takes a list of student marks and identify the lowest marks, the highest marks, and the mean, as shown in Table 3-6.
The problem | In this problem, you will get a list of student marks and find out the lowest, the highest, and the mean. |
The analysis and design | The steps involved are Step 1: Start with an empty list Step 2: Get marks in a loop and build a list Step 3: Sort the list Step 4: Get the lowest mark, the mean, and the highest mark from the sorted list |
The code |
|
The result | The lowest is 25, mean is 65, highest is 85 [25, 32, 36, 54, 55, 58, 65, 66, 74, 77, 85, 85] |
The next programming task for using a while loop is to write a program that can take an integer from a user and decide whether the integer is a prime number or not (see Table 3-7).
Code sample in VS Code IDE | |
---|---|
The task | Take an integer from a user and decide whether the integer is a prime number or not. |
Analysis and design | A prime number is an integer greater than 1 that cannot be divided by any of the integers between 1 and itself. The way to test this can be very simple: try to divide that number by all the numbers between 1 and that number. If it can be divided, and the answer is a whole number, then that number is prime. However, since i*j = j*i, we only need to test integers <= square root of m to speed up the test. We can assume the integer is a prime at the start of the test with a flag initialized to True; if a number in the range discussed above is found to be able to divide into the integer, the flag is changed to False and the test is complete. If no such number is found until the end of the range, the flag will remain True, and the number is a prime. The algorithm is as follows: Step 1: Get an integer from the user into variable n Step 2: Initialize flag to True Step 3: Initialize variable i to 2 Step 4: If i <= sqrt(n), do the following: Step 4.1: If n % m != 0, then m = m + 1; go to Step 4, else Step 4.2: If flag = False, break out and stop testing Step 5: If flag = True, then number n is a prime; print it out Step 6: End program |
|
|
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |
| |
Output in terminal | Give me an integer that is greater than 1, and I will tell you if it is a prime: 911 911 is a prime |
Please note the break statement in the example above. It is used to get out of the loop immediately by ignoring all the code before it without going back to test the looping condition. This is a way to get out of a loop in the middle of an iteration and is applicable to both the while loop and for loop.
Somewhat related to the break statement, the continue statement is used within a loop to go back directly to the beginning of the iteration—testing the looping condition in a while loop or taking the next item of the sequence in a for loop.
Common Coding Mistakes with a while Loop
As mentioned, the while loop is good for iterations in which the number of iterations is unknown but the condition of looping is known. To ensure that the loop will end as expected, the looping condition must be changed within the code block of the while statement. Otherwise, the loop will go on forever. To ensure that, there must be at least one variable within the code block of the loop whose value needs to be changed during iterations. Such a variable is called an iteration variable.
There are two common mistakes when using the while statement. The first one is not correctly writing the looping condition, which could be coded so that it is always true (hence, the iteration will keep going forever) or incorrectly coded to become false at the wrong time. For example, if x < 0 is written in place of x > 0 as the looping condition, the iteration would not finish as desired or wouldn’t run at all.
The other common mistake people often make when using the while statement is not coding the code block correctly to ensure that the following conditions hold:
- 1. There will be at least one iteration variable within the code block of the while loop.
- 2. The value(s) of iteration variable(s) must change within the code block.
- 3. The logical expression of the looping condition is not correctly written. This mistake may occur when inequal operators are involved in the logical expression of the looping condition. For example, using > in place of >=, or using < in place <=, will cause the program to miss one iteration of the loop.
In the example we just mentioned above, if x is never changed within the code block of the while loop, the value of the looping condition will remain the same, and the iteration will keep going forever as well.
3.6 Iterate with for Versus while
The for loop is controlled by a variable going through a sequence with a finite number of items. So essentially, the for loop is good for cases when the number of iterations is known. Let’s take a second look at the example about finding the average mark for a class. Assume now that we know the class has 30 students and we want the program to take the final marks of all students in the class and calculate the average mark. Because the number of students in the class is known, the for loop can be used to iterate, as shown below:
In [ ]: |
|
When the number of iterations is unknown, the while loop must be used, in which case the condition for exiting from the loop must be known. In this particular application, because no mark will be a negative number, we can use negative numbers to signify the end of input, to end the iteration, as shown in the following example:
In [ ]: |
|
Out [ ]: | Please input a mark: 89 Please input a mark: 96 Please input a mark: 78 Please input a mark: 97 Please input a mark: 88 Please input a mark: -7 The average course mark of 5 students is 89.6. |
In the example above, we use mark as an iteration variable to control the loop. Initializing it with 0 = ensures that the looping condition (logical expression mark >= 0) is satisfied to start the iteration.
Since we know the logical expression (mark >= 0) is true when 0 is assigned to mark, we can also simply use constant True in place of mark >= 0 and then use an if statement with the break statement to get out of the loop when a certain condition (condition to exit the loop) is met. The revised version of the program is shown below:
In [ ]: |
|
Out [ ]: | Please input a mark: 88 Please input a mark: 98 Please input a mark: 97 Please input a mark: 96 Please input a mark: 78 Please input a mark: -3 The average course mark of 5 students is 91.4. |
In the previous section we mentioned that the while loop is an entry-controlled iteration, which means that the code block of the loop statement may not be executed at all if the entry condition is not met at the beginning. In the example above, when we use True in place of the looping condition, it has guaranteed that the code block will always be run at least once, and the iteration could go on forever if a break statement is not used and executed when a certain condition (condition to exit) is met. This has made while statement an exit-controlled iteration. The flowchart of such iteration is shown in Figure 3-7.
Compared to the for statement, the while statement is more powerful and its uses are more versatile. In fact, all code written with a for statement can be rewritten with a while statement, though when looping through sequences, coding with for statements is more elegant and more readable.
Figure 3-7: Flowchart for a while loop
Since we know how to put a code block in a while loop, we can improve the grade conversion program written in the previous chapter so that we do not have to rerun the program for each conversion (see Tables 3-8 and 3-9).
Letter grade | Percentage |
---|---|
A+ | 90–100% |
A | 95–89% |
A− | 80–84% |
B+ | 77–79% |
B | 73–76% |
B− | 70–72% |
C+ | 67–69% |
C | 63–66% |
C− | 60–62% |
D | 55–59% |
D | 50–54% |
F | 0–49% |
The problem | In this case study, you are required to design a program using an if-elif-else statement to convert as many numeric grades to alpha/letter grades as needed until the user inputs -1 to stop. |
The analysis and design | In Canada, different provinces may use different conversion tables for numeric grade to letter grade conversion. In this case study, we take the one used in Alberta, as shown above. Based on the conversion table, our program needs to make 12 selections; for each selection, a letter grade will be printed out when the numeric grade falls within the corresponding interval. Since we allow a user to convert as many numeric grades as needed until the user explicitly tells the program to stop by inputting -1, we will put the above if-elif-elif multiple selection statements inside a while loop. Note that for this problem, the for loop will not work because we do not know how many times the loop will need to run. |
The code |
|
The result | Please input a numeric grade between 0 and 100 to convert; input -1 to exit:96 alpha/letter grade for 96% is A+ Please input a numeric grade between 0 and 100 to convert; input -1 to exit:79 alpha/letter grade for 79% is B+ Please input a numeric grade between 0 and 100 to convert; input -1 to exit:67 alpha/letter grade for 67% is C+ Please input a numeric grade between 0 and 100 to convert; input -1 to exit:-1 Thank you for using this grade converter! |
Chapter Summary
- • Knowing what to do at a given time and under certain conditions is important for any intelligent being.
- • Conditional statements are necessary and important constructs in all programming languages.
- • if, if-else, if-elif, if-elif-else are the constructs for conditional statements.
- • Each if, if-else, if-elif, if-elif-else statement represents a flow of program execution.
- • The if statement is for one selection. It will execute a code block if the condition is met.
- • The if-else statement is good for two selections.
- • The if-elif and if-elif-else statements are good for multiple selections.
- • The conditions behind if and elif are logical or Boolean expressions.
- • Python has two constructs for iteration, the for statement and the while statement.
- • The for statement can be used to repeat a code block through each member of an iterable, such as a list, tuple, or string, or an iterable object such as range(…).
- • When the iteration includes a for statement, the number of iterations can be determined most of the time, unless the break statement is used within the code block to break out from the loop.
- • The while statement is used to iterate under certain conditions.
- • The number of repetitions needed when using a while statement is often unknown. One can be used with or without a break statement within the code block.
- • The continue statement can be used within the code block of a for or while statement to directly go to the next iteration.
- • Any for statement can be rewritten as a while statement.
Exercises
- 1. Mentally run the following code blocks and write down the output of each code block.
a. |
|
b. |
|
c. |
|
- 2. Mentally run each of the code blocks below and write down the output of each code block:
a. |
|
b. |
|
c. |
|
d. |
|
Projects
- 1. Write a program that gets three numbers from the user and displays the biggest number among the three.
- 2. Write a program that gets a number from the user then says whether the number is an even number or odd number.
- 3. Write a program that takes three numbers from the user as the lengths of three lines, then determines if the three lines can make a triangle.
- 4. Write a program that takes three numbers from the user as the lengths of three lines, then determines if the three lines can make a triangle. If the three lines can make a triangle, the program should further determine if the triangle is an equilateral triangle or an isosceles triangle.
- 5. Write a program that takes three numbers from the user as the lengths of three lines, then determines if the three lines can make a triangle. If the three lines can make a triangle, the program should further determine if the triangle will be a right triangle.
- 6. Compound interest is a common practice in finance and banking, allowing you to earn interest on interest as well as on the principal. Assume that your bank offers a savings account with which you can earn compound interest. The amount you deposit into the account is p, and annual compound interest is r. By the end of n years after your initial deposit, the account balance will be a = p(1 + r)n. For this project, write a program that takes three numbers from the user as the initial deposit, the annual interest, and the number of years that the user wants the money to stay in the account. Calculate and display how much money the user will have by the end of the nth year.
- 7. In some countries like Canada, tax on taxable personal income for a year is calculated progressively according to a calculation table set for the year, such as the one shown below:
Income tax
15% on the first $48,534 or less
20.5% on the next $48,534
26% on the next $53,404
29% on the next $63,895
33% on taxable income over $214,368
Income
$0–$48,535
$48,536–$97,069
$96,070–$150,473
$150,474–$214,368
over $214,368
Write a program that takes taxable income from a user and calculates the total income tax payable according to the table above.
- 8. A mortgage is the money borrowed from a lender for the purchase of a property. Mortgages and mortgage payments are a big thing for almost everyone. For a mortgage with principal of P at a fixed monthly interest rate of r that needs to be paid off in Y years or 12 * Y = N months, the monthly payment would be:
Write a program that takes the principal, fixed annual interest rate, and years of amortization then calculates and displays the monthly payment amount. Hint: You will need to work out the number of months from number of years, and the monthly interest rate from the annual interest rate.
- 9. In the world of science and mathematics, the existence of some constants has attracted the attention of many scientists and mathematicians. Among those constants, pi π is the most well-known. Many great efforts have been made to get a more precise value for π. The following is a formula developed by Gottfried Leibniz for the calculation of π.
Write a program that takes an integer from the user to specify the number of terms used to calculate π. Calculate and display the approximate value.
- 10. Three integers—A, B and C—are called a Pythagorean when C * C = A * A + B * B. Write a program to take an input of integer from the user and find all the Pythagorean triples of integers, none of which are bigger than the integer taken from the user. For example, if the number from the user is 6, then 5, 4, and 3 are a Pythagorean triple because 52 = 42 + 32 = 25.
- 11. Compound interest is a common practice in finance and banking to earn interest on interest as well as on the principal. Assume that your bank offers you a deposit account through which you can earn compound interest, the amount you deposit into the account is p, and annual compound interest is r. By the end of n years after your initial deposit, the account balance will be a = p(1 + r)n. For this project, get p, r, and n from the user, then calculate and display a table showing the balance, the interest earned each year, and the total interest earned so far.
- 12. An integer is called a perfect number* if the sum of its factors, excluding itself, is equal to the integer itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3, and 1, 2, and 3 are all its factors. Write a program to get a number from a user, then determine if the number is a perfect number. If yes, display all its factors.
- 13. For a given integer n, if another integer m can divide n, then m is called a factor of n. In mathematics, finding all factors of a given integer is an important operation, especially for cryptography. Write a program that takes an integer from the user and determine and display all the factors of the number given by the user.
- 14. Read a series of float numbers from the user and calculate and display the average of all the numbers given by the user. Assume that the number of float numbers is unknown but that a negative number is used to indicate the end of the input.
- 15. For a mortgage with a principal of P at a fixed monthly interest rate of r that needs to be paid off in Y years or 12 * Y = N months, the monthly payment would be:
Continuing the project you did above for project 8, calculate a table showing the interest and principal paid each month and the principal balance at each month’s end.
* By definition, a perfect number is a positive integer that is equal to the sum of all its divisors, excluding itself but including 1. The smallest perfect number is 6, which is equal to the sum of 1, 2, and 3.
We use cookies to analyze our traffic. Please decide if you are willing to accept cookies from our website. You can change this setting anytime in Privacy Settings.