Now since you have learnt about recursive methods, here is a recursive method to add natural numbers up to n.
int sumNNumbers(int n)
{
if (n < 1)
return 0;
else
return (n + sumNNumbers(n-1));
}
Write the main() method and checkout the function written above.
There is an alternative method of writing the same. Try out this also:
}
int sumNNumbers(int n)
{
return n<1 0="" :="" font="" nbsp="">n + sumNNumbers(n-1);1>}
No comments:
Post a Comment