Write C# program to calculate power using while & for loop

Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability..

Calculating power of a number using while loop

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class csharpExercise
{
    static void Main(string[] args)
    {
 
        int basenumber, exponent,power, i;
 
        // Reading number
        Console.Write("Enter any number: ");
        basenumber = Convert.ToInt32(Console.ReadLine());
 
        Console.Write("Enter any number: ");
        exponent = Convert.ToInt32(Console.ReadLine());
 
        power = 1;
        i = 1;
        //caculatinh power of given number
        while (i <= exponent)
        {
            power = power * basenumber;
            i++;
        }
        Console.Write("Power : "+ power);
 
        Console.ReadLine();
    }
}

Calculating power of a number using for loop

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class csharpExercise
{
    static void Main(string[] args)
    {        
        int basenumber, exponent, i, power;
 
        // Reading number
        Console.Write("Enter any number: ");
        basenumber = Convert.ToInt32(Console.ReadLine());
 
        Console.Write("Enter any number: ");
        exponent = Convert.ToInt32(Console.ReadLine());
 
        power = 1;        
        //caculatinh power of given number
        for (i = 1; i <= exponent; i++)
            power = power * basenumber;            
 
 
        Console.Write("Power : "+ power);
 
        Console.ReadLine();
    }
}

Result

Write C# program to calculate power using while & for loop
Write C# program to calculate power using while & for loop

Leave a Comment