Monday, March 24, 2014

Question No 38(For loop) & 39(Six random dice)

Ex 38.    Write a for loop to compute the sum of all the consecutive values between 10,000 and 20,000.Display the final result sum.
        static void Main(string[] args)
        {
            double sum = 0;
            for (int i = 10000; i < 20000; i++)
            {
                sum += i;
            }
            Console.WriteLine("Sum: {0}", sum);
            Console.ReadLine();
        }
//===================code for Q 39========================
Ex 39.    You are to throw a dice and gain points according to the outcome. The throw of the dice is simulated by generating a random number from 1 to 6.
You gain 2 points when you throw a 1
You gain 4 points when you throw a 2
You lose 3 points when you throw a 3
You gain a point when you throw a 4
You gain 2 points when you throw a 5
You lose 5 points when you throw a 6
Use a for loop to run 12 throws. Within the loop add up all the gains and losses according to the outcomes of the throws. Use a switch to set up the decision tree. Display the final accumulated points.
        static void Main(string[] args)
        {
             int[] dieRoller = { 1, 2, 3, 4, 5, 6 };
             Random rand = new Random();
             int points = 0;
            for (int i = 0; i < 12; i++)
            {
                int dieRoll = rand.Next(1, 7);
                switch (dieRoll)
                {
                    case 1:
                        dieRoller[0]++;
                        points += 2;
                        break;
                    case 2:
                        dieRoller[1]++;
                        points += 4;
                        break;
                    case 3:
                        dieRoller[2]++;
                        points -= 3;
                        break;
                    case 4:
                        dieRoller[3]++;
                        points += 1;
                        break;
                    case 5:
                        dieRoller[4]++;
                        points += 2;
                        break;
                    case 6:
                        dieRoller[5]++;
                        points -= 5;
                        break;
                }
                Console.WriteLine("Dice roll {0} Point {1}", dieRoll, points);
            }
            Console.WriteLine("\nYou have earned {0}", points);
            Console.ReadLine();
        }

No comments:

Post a Comment