Answer to Question #188971 in C# for CHANDRASENA REDDY

Question #188971

Define a structure having one member variable as “Number”. Add functions to display the square and cube of the number in the same structure. In the main function, Initialize the structure variable, and display the square or the cube based on user’s choice.


1
Expert's answer
2021-05-08T07:59:50-0400
using System;

struct MyStruct
{
    public int number;


    public void displaySquare()
    {
        Console.WriteLine("The square of the number is: " + this.number * this.number);
    }
    public void displayCube()
    {
        Console.WriteLine("The cube of the number is: " + this.number * this.number * this.number);
    }
}


namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            bool loop = true;
            int option = 0;
            MyStruct myNumber = new MyStruct();


            Console.WriteLine("Enter your number: ");
            myNumber.number = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Choose an option:");
            Console.WriteLine("1. Display square of the number");
            Console.WriteLine("2. Display cube of the number");
            Console.WriteLine("3. Exit");


            while (loop)
            {
                Console.Write("\r\nSelect an option: ");
                option = Convert.ToInt32(Console.ReadLine());


                if (option < 1 || option > 3)
                {
                    Console.WriteLine("Error: You entered a wrong number, please try again!");
                }
                if (option == 1)
                {
                    myNumber.displaySquare();
                }
                else if (option == 2)
                {
                    myNumber.displayCube();
                }
                else if (option == 3)
                {
                    loop = false;
                }
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS