1) print the natural numbers 1 to n:
i/p:
20
o/p:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Solution:
using System;
public class GFG{
public static int naturalNumbers(int a,int b){
//main logic- this condition should fail till reach our output values
if(a>b) return a;
Console.Write("{0} ",a);
//Acting as iterator
return naturalNumbers(a+1,b);
}
static public void Main (){
naturalNumbers(1,20);
}
}
2) print the natural number from n to 1(reverse order):
i/p:
20
o/p:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Solution:
using System;
public class GFG{
public static int naturalNumbers(int a) {
if(a<1) return a;
Console.Write("{0} ",a);
return naturalNumbers(a-1);
}
static public void Main (){
naturalNumbers(20);
}
}
3) print the sum of the natural number from 1 to n:
i/p:
3
o/p:
6
sample: 1+2+3
Solution:
using System;
public class GFG{
public static int naturalNumbers(int a,int k){
//main logic- this condition should fail till reach our output values
if(a<1)
return k;
//Acting as iterator
return naturalNumbers(a-1,k+=a);
}
static public void Main (){
Console.WriteLine(naturalNumbers(3,0));
}
}
4) print the natural number as separated:
i/p: (int)
31234
o/p:
3 1 2 3 4
Solution:
using System;
public class Program{
public static void naturalNumbers(int a)
{
if(a<=0) return ;
naturalNumbers(a/10);
Console.WriteLine(a%10);
return;
}
static public void Main (){
int a=1234;
naturalNumbers(a);
}
}
5) Count & print the number of the natural number :
i/p: (int)
12345
o/p:
5
Solution:
using System;
class Program {
public static int naturalNumbers(int a,int count)
{
//condition used to break the statement
if(a<=0)
return count;
//method call used which will do the number reduction & count
return naturalNumbers(a/10,count+=1);
}
static void Main() {
Console.WriteLine(naturalNumbers(123465,0));
}
}