Using Macros Find Area and Perimeter of Triangle, Square, Circle: C Program

Problem State: Write macro definitions with arguments for calculation of area and perimeter of a triangle, a square and a circle.

Store these macro definitions in a file called “areaperi.h”. Include this file in your program, and call the macro definitions for calculating area and perimeter for different squares, triangles and circles.

Related Read:
Switch Case Default In C Programming Language
Macros With Arguments: C Program
do-while Loop In C Programming Language

Problem Statement Analysis

1. We need to write macro definitions which accept arguments.
2. We need to write macro definitions to calculate area and perimeter of triangle, square and circle.
3. We need to write macro definition inside a separate file called areaperi.h and then include this header file into our source file and make use of the macro definitions to calculate area and perimeter of Triangle, Square and Circle for various user inputs.

Video Tutorial: Using Macros Find Area and Perimeter of Triangle, Square, Circle: C Program


[youtube https://www.youtube.com/watch?v=lR50ONlpDNw]

YouTube Link: https://www.youtube.com/watch?v=lR50ONlpDNw [Watch the Video In Full Screen.]

Source Code: Using Macros Find Area and Perimeter of Triangle, Square, Circle: C Program

areaperi.h

#include<math.h>

#define TRI_PERI(a, b, c) (a + b + c)
#define SP(a, b, c) ( (a + b + c) / 2.0 )
#define TRI_AREA(a, b, c) ( sqrt( SP(a,b,c) * \
                                 ( SP(a,b,c) - a ) *\
                                  (SP(a,b,c) - b) * \
                                  (SP(a,b,c) - c)) )

#define SQR_PERI(s) (4 * s)
#define SQR_AREA(s) (s * s)

#define C_PERI(r) (2 * M_PI * r)
#define C_AREA(r) (M_PI * r * r)

main.c

#include<stdio.h>
#include "areaperi.h"

int main()
{
    float a, b, c, side, radius;
    int choice, repeat;

    do
    {
        printf("1. Area of Triangle\n");
        printf("2. Perimeter of Triangle\n");
        printf("3. Area of Square\n");
        printf("4. Perimeter of Square\n");
        printf("5. Area of Circle\n");
        printf("6. Perimeter of Circle\n");

        printf("\nEnter your choice\n");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1: printf("Enter 3 sides of a Triangle\n");
                    scanf("%f%f%f", &a, &b, &c);
                    printf("Area of Trianlge is %0.2f\n", TRI_AREA(a,b,c));
                    break;
            case 2: printf("Enter 3 sides of a Triangle\n");
                    scanf("%f%f%f", &a, &b, &c);
                    printf("Perimeter of Trianlge is %0.2f\n", TRI_PERI(a,b,c));
                    break;
            case 3: printf("Enter length of side of Square\n");
                    scanf("%f", &side);
                    printf("Area of Square is %0.2f", SQR_AREA(side));
                    break;
            case 4: printf("Enter length of side of Square\n");
                    scanf("%f", &side);
                    printf("Perimeter of Square is %0.2f", SQR_PERI(side));
                    break;
            case 5: printf("Enter Radius of Circle\n");
                    scanf("%f", &radius);
                    printf("Area of Circle is %0.2f\n", C_AREA(radius));
                    break;
            case 6: printf("Enter Radius of Circle\n");
                    scanf("%f", &radius);
                    printf("Circumference of Circle is %0.2f\n", C_PERI(radius));
                    break;
            default: printf("\nPlease enter valid choice\n");
        }

        printf("\n\nDo you want to continue? Ans: 0 or 1\n");
        scanf("%d", &repeat);

        printf("\n");

    }while(repeat);

    return 0;
}

Output:
1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
1
Enter 3 sides of a Triangle
5
6
9
Area of Trianlge is 14.14

Do you want to continue? Ans: 0 or 1
1

1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
2
Enter 3 sides of a Triangle
5
6
9
Perimeter of Trianlge is 20.00

Do you want to continue? Ans: 0 or 1
1

1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
3
Enter length of side of Square
5
Area of Square is 25.00

Do you want to continue? Ans: 0 or 1
1

1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
4
Enter length of side of Square
5
Perimeter of Square is 20.00

Do you want to continue? Ans: 0 or 1
1

1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
5
Enter Radius of Circle
5.5
Area of Circle is 95.03

Do you want to continue? Ans: 0 or 1
1

1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Enter your choice
6
Enter Radius of Circle
5.5
Circumference of Circle is 34.56

Do you want to continue? Ans: 0 or 1
0

Formulas To Calculate Area and Perimeter

We’ve written the formula to calculate area and perimeter inside areaperi.h file, as macro expansion. Below we list all the formulas we’re using in our program:

Perimeter of a Triangle: ( a + b + c)
where: a, b, and c are lengths of sides of the triangle.

Semi-perimeter of a Triangle: ( (a + b + c) / 2 )
where: a, b, and c are lengths of sides of the triangle.

Area of a Triangle: sqrt( S x (S – a) x (S – b) x (S – c) )
where: a, b, and c are lengths of sides of the triangle.
S is the semi-perimeter.

Perimeter of Square: ( 4 x side )
where: side is the length of side of the square.

Area of Square: ( side x side)
where: side is the length of side of the square.

Perimeter or Circumference of Circle: ( 2 x PI x r )
Area of a Circle: ( PI x r x r )
where: r is radius of the circle.
PI is approximately equal to 3.14

Note: M_PI is a macro present inside math.h library file and has value of PI.

Related Read:
C Program To Find Area, Perimeter and Semi-perimeter: Valid Triangle
C Program To Calculate Perimeter, Diagonal of a Square using its Side
C Program To Find Area and Circumference of Circle using Pointer

Logic

We’ve included areaperi.h into main.c file. Now we can make use of all the macros we’ve defined inside areaperi.h

Users are provided with options to select the preferred operations like:
1. Area of Triangle
2. Perimeter of Triangle
3. Area of Square
4. Perimeter of Square
5. Area of Circle
6. Perimeter of Circle

Based on user selection appropriate block of code inside switch-case is executed, wherein we place the relevant macro template to get the desired result.

Note: We can continue writing macro expansion in next line by making use of macro continuation operator(\). You can see that we’ve broken the line and written the code in next line inside macro expansion of TRI_AREA.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

File Inclusion In C Programming Language

In today’s video tutorial lets learn more about include directive or preprocessor statement.

What We Learn?

1. Two ways of including/importing files.
2. Why write related code in separate file.
3. Example program to illustrate including and working with multiple files.

Related Read:
include directive in C Program

Video Tutorial: File Inclusion In C Programming Language


[youtube https://www.youtube.com/watch?v=E9zYMqf3qHk]

YouTube Link: https://www.youtube.com/watch?v=E9zYMqf3qHk [Watch the Video In Full Screen.]

Source Code: File Inclusion In C Programming Language

Main.c

#include<stdio.h>
#include "Circle.h"

int main()
{
    float r;

    printf("Enter radius of Circle\n");
    scanf("%f", &r);

    printf("Area of Circle is %f\n", circle_area(r, PI));

    return 0;
}

Output:
Enter radius of Circle
5
Area of Circle is 78.539819

In your Code::Blocks editor, go to File -> New -> Empty File.

Circle.c

double circle_area(float r, float PI)
{
    return( PI * r * r );
}

Circle.h

#define PI 3.14159265358979323846

double circle_area(float, float);

Note: Make sure Main.c, Circle.c and Circle.h are all in the same directory/folder.

Circle.c
This file has definition of the function/methods.

Circle.h
This file has all the macro definitions and function prototypes.

Main.c
This is our main C program where we include Circle.h file. By including this file we also include macro definition for PI and also the function to calculate area of circle.

Preprocessor includes all the content of Circle.h into Main.c source code before passing the code to the compiler.

Since all the code in Circle.h is included, we can directly use PI value as well as we can call circle_area() method from within Main.c file.

Advantages of Separating Related Files

1. If we’re using certain functions and macros repeatedly in our program, its best practice to write it in a separate file and include it at the top of our program and use the functions and macros wherever necessary.

Example: We keep using printf() and scanf() methods in all our programs, so it has been written in a separate library file called stdio.

2. In big projects, if we separate related files, we can handover related tasks to separate teams. This way we can maintain modularity of the project effectively.

Example: Math.h file has macro definition and prototype of all the functions related to Mathematics.

3. It’s easy to find bugs, debug and unit test our project.

4. Our source code looks less clumsy and more readable.

Two Ways To Include Files

There are 2 ways to include files in C.

1. Using angular brackets: Angular Brackets are used to import or include standard library files. In this case the linker looks for the included file in the standard library file storage directory / folder.

2. Using Double Quotes: When filename is wrapped with double quotes, the linker looks for the file inside current working directory. It also means that the included file is written by the user and is not a part of standard library file.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

include directive in C Program

Usually you can see these “include” directive at the very top of your source code. It’s called a preprocessor directive.

All preprocessor statements in C start with a hash(#) symbol. include directive is similar to imports statement in Java.

 
#include < stdio.h >
int main()
{
    printf("Microsoft\n Apple\n Oracle\n Google\n Yahoo\n");
    return 0;
}

Output:
Microsoft
Apple
Oracle
Google
Yahoo

include Preprocessor Directive In C Program


[youtube https://www.youtube.com/watch?v=4BBml3T8WK4]

YouTube Link: https://www.youtube.com/watch?v=4BBml3T8WK4 [Watch the Video In Full Screen.]


This “include” directive causes one file to be included in another. For example, when we include stdio.h (header file) in our above program, all the content(code) gets imported or included in our program source code. This way we can make use of any function present inside stdio.h library file in our c program.

Car Program

We are writing Car simulation program in C – we write all the related code in different files by group them together and then include it in our main Car program. For example, we can separate wheels, color and display related things and then include all those things in our main Car program. This way our main Car program source code looks less clumsy and more over we need not worry about the implementation details present in those files.

Ex: When we include stdio.h file, we do not worry about the implementation details of printf() method. We simply use it for displaying content to the console. All the implementation details are present in stdio.h header file.

There are 2 ways of including header files

 
#include < stdio.h >

#include "Mylib.h"

When we use < and > to wrap around the file name, the linker looks for the files in standard library storage folder. When we wrap the file name in double quotes it looks for the file in current directory.

Usually user written, custom header files are wrapped in double quotes.

We’ll be writing our own library files in this video series. But for now it’ll get too complicated if we go any further.

Note: There are many preprocessor statements other than include directive. We’ll discuss them as and when we use it in our C programs.

Structure of a basic C Program

Lets write our first C program – the typical “Hello World!” program.

In this video tutorial lets learn the structure of a basic C program:
1. Preprocessors – include directive.
2. Main method/function.
3. printf method/function.
4. Semicolon syntax.
5. Indentation for readability of code.

Source Code: A Simple C Program

#include<stdio.h>

int main()
{
    printf("Microsoft\n Apple\n Oracle\n Google\n Yahoo\n");
    return 0;
}

Output:
Microsoft
Apple
Oracle
Google
Yahoo

Structure of a basic C Program


[youtube https://www.youtube.com/watch?v=3Yu6u3tmBS4]

YouTube Link: https://www.youtube.com/watch?v=3Yu6u3tmBS4 [Watch the Video In Full Screen.]


Preprocessor statement

The “include” directive which we see in the first line is a preprocessor directive. Here we are including a standard library file which has some set of useful functions in it, which we are using in our “Hello World” C Program.

stdio stands for “Standard Input Output”. As the name suggests this library file has functions to read and write data to console window, along with other many useful functions. For example, printf() is a function present in stdio.h library file. We simply use it in our program to print data on to the console window. We need not know the implementation details of printf method/function.

main() method

Main method or function is part of all ‘C’ programs. It’s entry point of any C program execution. Function is a way of grouping some code together. We can write any logic/statements inside a function.

It’s a standard that main always returns a integer value. Thus main is preceded by a keyword called int, which means integer. It’s a keyword or reserve word. We’ll know more about keywords(or reserve words) in a separate video tutorial. Since main method needs to return a integer value, we explicitly return 0 at the end.

Readability of code

It’s very important that we write code which is readable. It helps in maintaining the code. Large programs get too clumsy very easily and reading and understanding code often becomes difficult. So we need to indent the code and make sure its readable as far as possible.

Note:
Main method/function doesn’t take any argument.