Monday, September 30, 2013

P2C2: Write a program in C Sharp to calculate 2's power using recursion.

//Write a program in C Sharp to calculate 2's power using recursion
using System;

public class Program_Power_Recursion
{
   public static void Main()
    {
        int num;
        long ans;

        Console.Write("Enter any number: ");
        num = Convert.ToInt32(Console.ReadLine());

        ans = Power2(num);
        Console.WriteLine("\n :::::::: OUTPUT :::::::::\n");
        Console.WriteLine(" 2^" + num + " = " + ans);
     
        Console.WriteLine("\n\nPress any key to exit...");
        Console.ReadLine();
    }

   static long Power2(int n)
   {
       if (n == 0)
           return 1;
       else
           return (2 * Power2(n - 1));
   }
}

OUTPUT:

Enter any number: 10

 :::::::: OUTPUT :::::::::

 2^10 = 1024


Press any key to exit...

No comments:

Post a Comment