Exercise: Sum Of Numbers


Use a for loop to compute the sum of all numbers from 14 to 73.

Once computed, print this sum to the console.

Introduction

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.

Understanding the Basics

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.

Main Concepts

To solve the problem of summing numbers from 14 to 73, we need to:

  • Initialize a variable to store the sum.
  • Use a for loop to iterate through each number in the range.
  • Add each number to the sum variable.
  • Print the final sum.

Examples and Use Cases

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 Pitfalls and Best Practices

Common mistakes include:

  • Incorrect loop boundaries (e.g., starting at 13 or ending at 74).
  • Forgetting to initialize the sum variable.
  • Not using the correct increment/decrement in the loop.

Best practices:

  • Always initialize your variables.
  • Double-check loop boundaries.
  • Use meaningful variable names.

Advanced Techniques

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.

Debugging and Testing

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;
    }
}

Thinking and Problem-Solving Tips

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.

Conclusion

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.

Additional Resources