Compute integer powers of 2 with while loop in CSharp

Description

The following code shows how to compute integer powers of 2 with while loop.

Example


/* ww  w  .  j a v  a2  s.  co m*/
using System; 
 
public class MainClass {   
  public static void Main() { 
    int e; 
    int result; 
 
    for(int i=0; i < 10; i++) { 
      result = 1; 
      e = i; 
 
      while(e > 0) { 
        result *= 2; 
        e--; 
      } 
 
      Console.WriteLine("2 to the " + i + " power is " + result);        
    } 
  }   
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception