Friday, March 21, 2014

Array_Ex_3 (Wk 8) Feb 24-28, 2014

Q1: Write code to add all the values in the array, display total.
 static void Main(string[] args)
        {
            int[] array = new int[12] { 2, -9, 8, 12, -6, -23, 33, 40, 19, -45, 18, -4 };

            int total = 0;
            for (int i = 0; i < array.Length; i++)
            {
                total += array[i];
                Console.WriteLine("Index: {0, 4}  Value: {1, 4}  Total: {2, 4}", i, array[i], total);
            }
            Console.ReadLine();
        }
*************************************************************************
Q2: Compute the total of positives only. Display positive total.
 static void Main(string[] args)
        {
            int[] array = new int[12] { 2, -9, 8, 12, -6, -23, 33, 40, 19, -45, 18, -4 };
            int total = 0;
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] > 0)
                {
                    total += array[i];
                }
                Console.WriteLine("Index: {0}  Value: {1}", i, array[i]);
            }
            Console.WriteLine("\nPositive Total: {0}", total);
            Console.ReadLine();
        }
*************************************************************************
Q3: Add only even values, Display even total.
  static void Main(string[] args)
        {
            int[] array = new int[12] { 2, -9, 8, 12, -6, -23, 33, 40, 19, -45, 18, -4 };
            int eventotal = 0;
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] % 2 == 0)
                {
                    eventotal += array[i];
                }
                Console.WriteLine("Index: {0}  Value: {1}", i, array[i]);
            }
            Console.WriteLine("\nPositive Total: {0}", eventotal);
            Console.ReadLine();
        } *************************************************************************

No comments:

Post a Comment