Tuesday, 16 August 2016

Powers with recursive function

This code takes two variables and then powers the second one to the first. For example...

Enter your variable or type end to break:
5
Enter your power:
3
125
Type any key to continue
..........................................................................................


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Powers
{
    class Program
    {
        static void Main(string[] args)
        {

            power();   
                }

        private static void power()
        {
            while (1 == 1)
            {

                Console.WriteLine("");

                Console.WriteLine("Enter your variable or type end to break: ");
                string b = Console.ReadLine();

                if (b == "end")
               
                    break;


                int x = int.Parse(b);


                Console.WriteLine("Enter your power: ");
                int y = int.Parse(Console.ReadLine());

                Console.WriteLine(Power(x, y));
                Console.WriteLine("Type any key to continue");
                Console.WriteLine("..................................................");
                string a = Console.ReadLine();
            }

        }
             public static int Power(int x, int y)
        {
            if (y == 0)
                return 1;
            else
                return x * Power(x, y - 1);
        }


    }
}




No comments:

Post a Comment