-->




c++ program to find area of circle using functions

Leave a Comment
Cpp tutorial to calculate area of circle
  •  User enter radius or diameter of circle.
  •  Program should have two functions one which takes radius as parameter and second takes diameter as parameter.
  •  If user enters wrong option then tell users its valid selection and chose again the right option.
This Cpp Tutorial covers the concept of
  • if else if statement
  • for loop
  • function with parameter and return value
Cpp code compiler used: Codeblocks C++ Compiler

#include <iostream>
#define PI 3.14159
using namespace std;

float AreaOfCircle(float radius);
float AreaWithDiameter(float diameter);

int main()
{
    float radius,diameter,circleArea;
    char choice='0';
    cout<<"\n\t\t\tFind Area Of Circle:"<<endl;


    for(;choice!='1'&&choice!='2';)
        {
         cout<<"\nEnter 1 to Enter Radius OR
                 2 to Enter Diameter: ";
         cin>>choice;
         if(choice!='1'&&choice!='2')
         cout<<"\n\t\tEnter a VALID Option ";

        }

    if(choice=='1')
    {
    cout <<"\n\t\tEnter Radius To Find Area: ";
    cin>>radius;
    circleArea=AreaOfCircle(radius);
    }
    else if(choice=='2')
    {
    cout <<"\n\t\tEnter Diameter To Find Area: ";
    cin>>diameter;
    circleArea=AreaWithDiameter(diameter);

    }
    cout<<"\n\n\t\tArea of Circle is:->> "<<circleArea<<endl;
    return 0;
}

float AreaOfCircle(float radius)
{
    return (PI*(radius*radius));

}

float AreaWithDiameter(float diameter)
{

    return (AreaOfCircle(diameter/2));
}


output of program
calculate area of circle cpp tutorial

Program explanation
  • Program has two functions one for radius and one for diameter both called upon user choice
  • Both calculates the radius and diameter according to formula and return result value from where they have called
  • A for loop is used to prevent the wrong choice selection it will break only if user enters valid option 1 or 2 else it will continue to ask user to enter valid option

0 comments:

Post a Comment