Menu
Topics Index
...
`

Sum of natural numbers


If you need explanation Read this topic

If you need Answer Take test on this topic

Sum of natural numbers
What will be the output of the following program?
public class SumOfNaturalNumbers
{
    public static void main(String args[])
    {
        int range = 20;
        System.out.print(sumOfNaturalNumbers(range));    
    }
    private static int sumOfNaturalNumbers(int range)
    {
        int sum = 0;
        if (range == 1)
            return 1;
        sum = range + sumOfNaturalNumbers(range - 1);
        return sum;
    }
}

A. 155
B. 312
C. 190
D. 210
E. Compilation Error or Runtime Error
Topic: Recursive In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans d it caluclates the sum of numbers upto its range and displays as 210

Posted by Manasa Jyothi Sree    2014-06-18 09:02:02


Ans is d..it wil add num upto 20..2 n last wen range becm 1 thn it is returning 1 so last 209+1=210 using the recursion concept

Posted by Uday Kumar    2014-06-18 09:08:11


ans is D as range is 20 in main and passed to function and in function based on if condition sum is changed and range is decreased and sum value is returned

Posted by Bharath Yelchuri    2014-06-18 15:55:45


Congratulations Manasa Jyothi Sree. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-06-19 06:35:42


© meritcampus 2019

All Rights Reserved.

Open In App