.NET Practical Slip 11 Q B

2. Slip-1 Problem Statement

Q. Write a C# program to make a class named Fruit with a data member to calculate the number of fruits in a basket. Create two other classes named Apples and Mangoes to calculate the number of apples and mangoes in the basket. Display the total number of fruits in the basket. 25 Marks

Answer:

using System;

namespace FruitBasket
{
    // Base class Fruit
    class Fruit
    {
        protected int count;

        public Fruit()
        {
            count = 0;
        }

        public void AddFruits(int number)
        {
            count += number;
        }

        public int GetCount()
        {
            return count;
        }
    }

    // Derived class Apples
    class Apples : Fruit
    {
        public Apples(int number)
        {
            AddFruits(number);
        }
    }

    // Derived class Mangoes
    class Mangoes : Fruit
    {
        public Mangoes(int number)
        {
            AddFruits(number);
        }
    }

    // Main program to calculate total number of fruits
    class Program
    {
        static void Main(string[] args)
        {
            // Create instances of Apples and Mangoes
            Apples apples = new Apples(10);  // 10 apples
            Mangoes mangoes = new Mangoes(5); // 5 mangoes

            // Calculate total number of fruits in the basket
            int totalFruits = apples.GetCount() + mangoes.GetCount();

            // Display total number of fruits
            Console.WriteLine("Total number of fruits in the basket: " + totalFruits);
            Console.ReadLine();
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top