Menu
Topics Index
...
`


Control Statements > Iteration statements (Loops) >
Siva Nookala - 06 Oct 2016
This example finds the sum of all numbers till a given input number using for Loop In Java. e.g., if the input is 6, then the sum is 1 + 2 + 3 + 4 + 5 + 6 = 21;

Sum of numbers
class SumOfNumbers
{
    public static void main(String arg[])
    {
        int input = 6;
        int sum = 0;
        
        for(int i = 1; i <= input; i++)
        {
            sum = sum + i;    // LINE A
            System.out.println("Sum after adding " + i + " is : " + sum);
        }
        
        System.out.println();
        System.out.println("Sum of numbers till " + input + " is " + sum); // LINE B
    
    }
}
OUTPUT

Sum after adding 1 is : 1
Sum after adding 2 is : 3
Sum after adding 3 is : 6
Sum after adding 4 is : 10
Sum after adding 5 is : 15
Sum after adding 6 is : 21

Sum of numbers till 6 is 21

DESCRIPTION

The program calculates the sum of numbers till the given input. input this case is 6. The variable sum is also initialized to 0. The for loop control variable i is initialized to 1 and is incremented until it is less than or equal to input.
When the first iteration of the for loop is run with i = 1, sum changes from 0 to 1 at LINE A. When the second iteration is run with i = 2, sum changes from 1 to 3, since 2 is added. When i is 3, sum changes from 3 to 6. When i is 4, it changes from 6 to 10. When i is 5, it changes from 10 to 15. And finally when i is 6, it changes from 15 to 21. So after the for loop, it prints Sum of numbers till 6 is 21

THINGS TO TRY
  • Place the below line of code after LINE B to print the average of numbers.
    int average = sum/input;
    System.out.println("Average of numbers: " + average);
  • Change LINE A to replace the code with the below code so that it prints the sum of squares.
    sum = sum + (i*i);

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App