Use a for
loop to compute the sum of all numbers from 14
to 73
.
Once computed, print this sum to the console.
In this lesson, we will learn how to use a for
loop to compute the sum of a range of numbers. This is a fundamental concept in programming that helps in understanding loops and iteration. Summing a range of numbers is a common task in various applications, such as calculating totals, averages, and other aggregate values.
A for
loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. Understanding how to use a for
loop is crucial before moving on to more complex programming tasks.
Example of a simple for
loop:
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This loop will print numbers from 0 to 9.
To solve the problem of summing numbers from 14 to 73, we need to:
for
loop to iterate through each number in the range.Let's look at the step-by-step implementation:
public class SumOfNumbers {
public static void main(String[] args) {
int sum = 0; // Initialize sum variable
for (int i = 14; i <= 73; i++) { // Loop from 14 to 73
sum += i; // Add each number to sum
}
System.out.println("The sum of numbers from 14 to 73 is: " + sum); // Print the result
}
}
In this example, the loop starts at 14 and ends at 73, inclusive. Each number in this range is added to the sum
variable, and the final sum is printed.
Common mistakes include:
Best practices:
For more advanced scenarios, consider using streams in Java 8+:
import java.util.stream.IntStream;
public class SumOfNumbers {
public static void main(String[] args) {
int sum = IntStream.rangeClosed(14, 73).sum();
System.out.println("The sum of numbers from 14 to 73 is: " + sum);
}
}
This approach uses the IntStream
class to create a stream of numbers from 14 to 73 and then sums them.
To debug, use print statements to check the values of variables at different stages. For testing, write test cases to verify the sum for different ranges.
public class SumOfNumbersTest {
public static void main(String[] args) {
assert sumOfRange(14, 73) == 2412 : "Test failed!";
System.out.println("All tests passed.");
}
public static int sumOfRange(int start, int end) {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
return sum;
}
}
Break down the problem into smaller parts: initialization, loop, and summation. Practice by solving similar problems, such as summing even or odd numbers in a range.
We have covered how to use a for
loop to sum a range of numbers, common pitfalls, best practices, and advanced techniques. Mastering these concepts is essential for efficient programming.