Sunday, September 29, 2013

P2C2: C Sharp Program - Sum of 10 consecutive numbers using while, do ... while and for loop

// Using while loop

using System;

public class Program_Sum
{
   public static void Main()
    {
        int n=0, sum=0;
     
        while (n < 10)
        {
            n = n + 1;
            sum = sum + n;
            Console.WriteLine("Number = {0} Sum = {1}", n, sum);
        }


        Console.WriteLine("\n\nSum of {0} numbers = {1}", n, sum);
     
        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();

    }
}

OUTPUT:

Number = 1 Sum = 1
Number = 2 Sum = 3
Number = 3 Sum = 6
Number = 4 Sum = 10
Number = 5 Sum = 15
Number = 6 Sum = 21
Number = 7 Sum = 28
Number = 8 Sum = 36
Number = 9 Sum = 45
Number = 10 Sum = 55


Sum of 10 numbers = 55

Press any key to exit...


//Using do ... while loop


using System;

public class Program_Sum
{
   public static void Main()
    {
        int n=0, sum=0;

        do
        {
            n = n + 1;
            sum = sum + n;
            Console.WriteLine("Number = {0} Sum = {1}", n, sum);
        } while (n < 10);


        Console.WriteLine("\n\nSum of {0} numbers = {1}", n, sum);
     
        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();

    }
}

OUTPUT:

Number = 1 Sum = 1
Number = 2 Sum = 3
Number = 3 Sum = 6
Number = 4 Sum = 10
Number = 5 Sum = 15
Number = 6 Sum = 21
Number = 7 Sum = 28
Number = 8 Sum = 36
Number = 9 Sum = 45
Number = 10 Sum = 55


Sum of 10 numbers = 55

Press any key to exit...


//Using for loop

using System;

public class Program_Sum
{
   public static void Main()
    {
        int sum=0;

        for(int n=1; n<=10; n++)
        {
            sum = sum + n;
            Console.WriteLine("N = {0} \t Sum = {1}", n, sum);
        }

                 
        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();

    }
}

OUTPUT:

N = 1    Sum = 1
N = 2    Sum = 3
N = 3    Sum = 6
N = 4    Sum = 10
N = 5    Sum = 15
N = 6    Sum = 21
N = 7    Sum = 28
N = 8    Sum = 36
N = 9    Sum = 45
N = 10   Sum = 55

Press any key to exit...

No comments:

Post a Comment