In this C++ program the area of geometric shapes (circle, rectangle, and triangle) is calculated easily through classes by asking the user a choice that which shape he wants to deal with, the code is:
//area of geometric shapes in C++ #include<iostream> #include<windows.h> using namespace std; #define pi 3.141592654 #define full 2.0 int square(int x) { return x*x; } // class declration class Area{ int X,Y; //taking two argumnet data members public: Area(int x,int y):X(x),Y(y){} //constructor with two argumnets //data functions float circle(int x,int y) //for area of the circle { cout<<"ntttArea of the Circle is :"; return pi*square(x); } float rectangle(int l,int w) //for area of the rectangle { cout<<"ntttArea of the Rectangle is :"; return l*w; } float triangle(int b,int h) //for area of the triangle { cout<<"ntttArea of the Triangle is :"; return (b*h)/full; } }; //class end void fun() // function for clear screen and Sleep { Sleep(2000);cout<<"nntttReturning to Menu"; for (int i=0;i<=5;i++) { cout<<" ."; Sleep(400); } system("cls"); } // fun end // main body int main(void) { int first,second,choice; cout<<"nEnter the first argument :";cin>>first; cout<<"nEnter the second argument :";cin>>second; system("cls"); Area instance(first,second);// set the value by pass to the constructor of the object called instance while (1) { // loop for infinite running expect when 4 is pressed which is terminating case cout << "nttt --------------MENU ------------ " << endl << "ttt Press 1. Area of Circle " << endl << "ttt Press 2. Area of Rectangle" << endl << "ttt Press 3. Area of Triangle" << endl << "ttt Press 4. To Exit " << endl << "nttt ------------------------------- " << endl << "tttYour Choice :"; cin>>choice; switch(choice){//switch case 1: cout<<instance.circle(first,second);fun();//passing by value the function for area of circle by the object break; case 2: cout<<instance.rectangle(first,second);fun();// same for the other functions break; case 3: cout<<instance.triangle(first,second);fun(); break; case 4: exit(1); // termninating case to escpae from while and terminate break; default: cout<<"Wrong Input ";// for other wrong inputs } } return 0; }
The functions with relative comments are mentioned in the above code, the user is first asked to enter the arguments and then a menu appears offering the area of shape the user needs to select.