Here, we will see that this problem can be solved more naturally using a for-statement.
|
|
|
|
input: n = some integer number |
Structure diagram of the algorithm:
Notice it is much easier to write the algorithm using a for-statement (than a while-statement - in this example)
import java.util.Scanner; public class Divisors01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int x; System.out.print("Enter a number n: "); n = in.nextInt(); // Read in number for ( x = 1; x <= n; x++ ) // Run x = 1, 2, ..., n { if ( n % x == 0 ) { // x is a divisor of n System.out.println(x); // Print x (because it's a divisor) } } } } |
How to run the program:
|
|
|
|
input: n = some integer number |
Sample execution (n = 5):
sum = 0; ---> sum = 0 for-statement: add 1 to sum; ---> sum = 1 add 2 to sum; ---> sum = 3 add 3 to sum; ---> sum = 6 add 4 to sum; ---> sum = 10 add 5 to sum; ---> sum = 15 Print sum; ---> Prints 15 |
sum = sum + x; |
Example:
Suppose the variable sum contains 6 and x = 4 Then: sum = sum + x; = 6 + 4; = 10; ---> Result, sum = 10 We have added 4 to sum ! |
Structure diagram of the algorithm:
import java.util.Scanner; public class Divisors01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int x, sum; System.out.print("Enter a number n: "); n = in.nextInt(); // Read in number sum = 0; // Clear running total for ( x = 1; x <= n; x++ ) // Run x = 1, 2, ..., n { sum = sum + x; // Add x to sum } System.out.println(sum); // Print final sum } } |
How to run the program:
|
|
|
|
input: n = some integer number |
Sample execution (n = 5):
product = 1; ---> product = 1 for-statement: multiply 1 into product; ---> product = 1 multiply 2 into product; ---> product = 2 multiply 3 into product; ---> product = 6 multiply 4 into product; ---> product = 24 multiply 5 into product; ---> product = 120 Print product; ---> Prints 120 |
product = product * x; |
Example:
Suppose the variable product contains 6 and x = 4 Then: product = product * x; = 6 * 4; = 24; ---> Result, product = 24 We have multiplied 4 into the product ! |
Structure diagram of the algorithm:
import java.util.Scanner; public class Factorial01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int x, product; System.out.print("Enter a number n: "); n = in.nextInt(); // Read in number product = 1; // Set init. product to 1 for ( x = 1; x <= n; x++ ) // Run x = 1, 2, ..., n { product = product * x; // Multiply x into product } System.out.println(product); // Print final product } } |
How to run the program:
|