info@meritcampus.com    +91-85006-22255
...
`

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 numbersCODE Try it Online`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        }}`OUTPUTSum after adding 1 is : 1Sum after adding 2 is : 3Sum after adding 3 is : 6Sum after adding 4 is : 10Sum after adding 5 is : 15Sum after adding 6 is : 21Sum of numbers till 6 is 21DESCRIPTIONThe 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 21THINGS TO TRYPlace 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