Find area of rectangle using Structure and Function in C++


The code defines a struct Rectangle with width and height as its member variables. It also defines a constructor that takes two parameters w and h and initializes the width and height variables of the struct with those values.

It also defines a function areaOfRectangle() that calculates and prints the area of the rectangle. In themain() function, an object of the Rectangle struct is created with width 4 and height 6. Then, the areaOfRectangle() function is called on that object to print the area of the rectangle, which is 24.

Source Code

#include<iostream>
using namespace std;
struct Rectangle
{
  int width,height;
  Rectangle(int w,int h)
  {
    width=w;
    height=h;
  }
  void areaOfRectangle()
  {
    cout<<"Area of Rectangle is: "<<(width*height);
  }
};
int main(void)
{
   struct Rectangle rec=Rectangle(4,6);
   rec.areaOfRectangle();
   return 0;
}
To download raw file Click Here

Output

Area of Rectangle is: 24

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples