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

C Program To Find If a Point Lies Inside Triangle or Not

Write a function to compute the distance between two points and use it to develop another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2, y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the point (x, y) lies inside the triangle ABC, otherwise returns a value 0.

3 triangles inside a triangle

Analyze Above Problem Statement

1. We need to define a function which calculates the distance between two points.

For Example: distance(x1, y1, x2, y2); This function takes values of 2 points (x1, y1) and (x2, y2) and returns the distance between these 2 points.

2. User will enter values for 3 points, which are 3 edges/points of the triangle: (x1, y1), (x2, y2) and (x3, y3). We need to make use of a function(check Step 1) to calculate the distance between them. Once we have the distances, which are nothing but 3 sides of the triangle, we can use it to find area of that triangle using Heron’s or Hero’s Formula.

We call the distance between points (x1, y1) and (x2, y2) as a.
We call the distance between points (x2, y2) and (x3, y3) as b.
We call the distance between points (x3, y3) and (x1, y1) as c.

Using 3 sides of the triangle and Heron’s formula we calculate the area of triangle and store it inside variable area.

Hint: Check the image above for all these points we’ve explained so far. It has all the markings, which will help you visualize the concept.

3. Next, user will enter values for a point(x, y) on the graph. We need to make use of distance function(see step 1) and area of triangle function(see step 2) to find the area of 3 triangles formed by connecting (x1, y1) and (x, y), (x2, y2) and (x, y), (x3, y3) and (x, y);

We store the area of these 3 triangles inside variables A, B and C.

4. Write a function which returns 1 if the point lies within the triangle and returns 0 if the point lies outside the triangle.

If area of triangle represented by points (x1, y1), (x2, y2) and (x3, y3) is equal to the sum of the 3 triangles formed by connecting these 3 points to (x, y), then the points lie inside the triangle else the point is outside the triangle.

i.e., area_of_main_triangle == A + B + C; then the point lies inside the main triangle else it lies outside the main triangle.

Hint: Check the image above once again and write it down on a piece of paper, so that you clearly understand all the markings.

Note: This C program is comparatively bigger, but most part of its logic is already covered in other videos. Nothing complicated here. Its very simple, easy and straightforward program. Just don’t get stressed by looking at the length of this program. Learn the code(and the logic) step by step. Consume this or understand this program bit by bit and in no time you’ll know the whole thing!

Related Read:
C Program To Calculate Distance Between Two Points
C Program To Calculate Area of a Triangle using Pointers

Video Tutorial: C Program To Find If a Point Lies Inside Triangle or Not


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

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


Source Code: C Program To Find If a Point Lies Inside Triangle or Not

#include<stdio.h>
#include<math.h>

void  calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *area);
int   position(float area, float A, float B, float C);
float distance(float x1, float y1, float x2, float y2);
float calc_area(float a, float b, float c);

int main()
{
    float x1, y1, x2, y2, x3, y3, x, y;
    int   flag = 0;
    float area = 0;

    printf("Enter value for(x1, y1)\n");
    scanf("%f%f", &x1, &y1);

    printf("Enter value for(x2, y2)\n");
    scanf("%f%f", &x2, &y2);

    printf("Enter value for(x3, y3)\n");
    scanf("%f%f", &x3, &y3);

    printf("Enter point(x, y) to check if it lies inside the Triangle\n");
    scanf("%f%f", &x, &y);

    calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &area);

    printf("\nArea of Triangle = %f\n", area);

    if(flag) printf("Point (%0.1f, %0.1f) lies within the Triangle\n", x, y);
    else     printf("Point (%0.1f, %0.1f) lies outside the Triangle\n", x, y);

    return 0;
}

void calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *area)
{
    float A, B, C, a, b, c, d, e, f;

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);
*area = calc_area(a, b, c);

    d = distance(x1, y1, x, y);
    e = distance(x2, y2, x, y);
    f = distance(x3, y3, x, y);

    A = calc_area(d, a, e);
    B = calc_area(e, b, f);
    C = calc_area(f, c, d);

*flag = position(*area, A, B, C);
}

float distance(float x1, float y1, float x2, float y2)
{
    return( sqrt( pow((x2 - x1), 2) + pow((y2 - y1), 2) ) );
}

float calc_area(float a, float b, float c)
{
    float S;

    S = (a + b + c) / 2.0;

    return( sqrt(S * (S - a) * (S - b) * (S - c) ) );
}

int position(float area, float A, float B, float C)
{
    float res = area - (A + B + C);

    if(res < 0)
    {
        res *= -1;
    }

    if(res == 0 || res < 0.001 )
    {
        return(1);
    }
    else
    {
        return(0);
    }
}

Output 1:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
5 2

Area of Triangle = 100.000000
Point (5.0, 2.0) lies within the Triangle

Output 2:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
10 20.1

Area of Triangle = 100.000000
Point (10.0, 20.1) lies outside the Triangle

Output 3:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
20 0
Enter value for(x3, y3)
10 30
Enter point(x, y) to check if it lies inside the Triangle
10 15

Area of Triangle = 300.000000
Point (10.0, 15.0) lies within the Triangle

Logic To Find If a Point Lies Inside Triangle or Not

We ask the user to enter values for 3 edges or points of the triangle. We call it (x1, y1), (x2, y2) and (x3, y3). We also ask the user to enter a point, to check if it lies inside or outside the Triangle. We store the value of point inside (x, y).

We pass the values of (x1, y1), (x2, y2), (x3, y3), (x, y) and the address of variables flag and area to a function called calc().

calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &area);

Inside calc() function
Inside calc() function we call another function to find distance between user entered points (x1, y1), (x2, y2), (x3, y3) and (x, y). We pass values of 2 points to the function distance() to get back the value or the distance between these two points.

a = distance(x1, y1, x2, y2);

Similarly, we find the distance between points (x2, y2) and (x3, y3), (x3, y3) and (x1, y1). This gives us lengths of all 3 sides of the triangle.

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);

Inside distance() function
We use a simple formula to calculate distance between 2 points:

distance = sqrt( (x2 – x1)*(x2 – x1) + (y2 – y1)*(y2 – y1) );

C Program To Calculate Distance Between Two Points

Inside calc_area() function
When we know the values of all 3 sides of a triangle, we can easily calculate its area using Heron’s or Hero’s formula.

sqrt(S * (S – a) * (S – b) * (S – c) );

where a, b and c are sides of the triangle.
and S is semi-perimeter of the Triangle.

S is calculate using below formula:

S = (a + b + c) / 2.0;

C Program To Calculate Area of a Triangle using Pointers

Inside calc() function
Now we calculate the distance between the user entered point(x, y) and with all 3 points of the triangle (x1, y1), (x2, y2) and (x3, y3). And store the values inside variables d, e, f. We make use of the function distance() here to get the distance between the points.

Inside calc_area() function
Again we reuse the calc_area() function to calculate the area’s of 3 triangles formed by connecting (x1, y1), (x2, y2), (x3, y3) with (x, y).

Inside position() function
Now we have area of the entire triangle(with sides a, b, c). And area of 3 more triangles present inside the main triangle – according to our assumption, as per above image. It need not be like that. We store these 3 areas in variables A, B and C.

If area == A + B + C, then the point (x, y) lies inside the triangle orelse the point(x, y) lies outside the triangle.

Very Important Note:

Since variables *area, A, B, C and all the points on the graph are of type float. So the final result for *area == A + B + C will have a very small difference. i.e., up to 0.001

So whenever we check for if(*area == A + B + C) it returns false or 0. So we use different logic. If the point lies inside the triangle then A + B + C will be equal to the area of main triangle. So we subtract the value of main triangle with all the 3 triangles present inside, so the result should be either 0 or with a small difference less than 0.001.

So the difference can be positive or negative, so we multiple the result by -1 in case the result is less than 0. After that we check for the condition if res is equal to 0 or res is less than 0.001, then we return 1, indicating that the point lies inside the triangle. If there is a difference bigger than 0.001 then we return 0, indicating that the point (x, y) lies outside the triangle.

Source Code Which Matches Exactly To The Problem Statement

3 triangles inside a triangle
We’ve changed the variable names to match the problem statement. Rest everything is same – the logic and working etc. Only 4 variable names have been changed to match the problem statement.

Source Code: C Program To Find If a Point Lies Inside Triangle or Not

#include<stdio.h>
#include<math.h>

void  calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *ABC);
int   position(float ABC, float APB, float BPC, float CPA);
float distance(float x1, float y1, float x2, float y2);
float calc_area(float a, float b, float c);

int main()
{
    float x1, y1, x2, y2, x3, y3, x, y;
    int   flag = 0;
    float ABC = 0;

    printf("Enter value for(x1, y1)\n");
    scanf("%f%f", &x1, &y1);

    printf("Enter value for(x2, y2)\n");
    scanf("%f%f", &x2, &y2);

    printf("Enter value for(x3, y3)\n");
    scanf("%f%f", &x3, &y3);

    printf("Enter point(x, y) to check if it lies inside the Triangle\n");
    scanf("%f%f", &x, &y);

    calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &ABC);

    printf("\nArea of Triangle = %f\n", ABC);

    if(flag) printf("Point (%0.1f, %0.1f) lies within the Triangle\n", x, y);
    else     printf("Point (%0.1f, %0.1f) lies outside the Triangle\n", x, y);

    return 0;
}

void calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *ABC)
{
    float APB, BPC, CPA, a, b, c, d, e, f;

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);
 *ABC = calc_area(a, b, c);

    d = distance(x1, y1, x, y);
    e = distance(x2, y2, x, y);
    f = distance(x3, y3, x, y);

  APB = calc_area(d, a, e);
  BPC = calc_area(e, b, f);
  CPA = calc_area(f, c, d);

*flag = position(*ABC, APB, BPC, CPA);
}

int position(float ABC, float APB, float BPC, float CPA)
{
    float res = ABC - (APB + BPC + CPA);

    if(res < 0)
    {
        res *= -1;
    }

    if(res == 0 || res < 0.001 )
    {
        return(1);
    }
    else
    {
        return(0);
    }
}

float distance(float x1, float y1, float x2, float y2)
{
    return( sqrt( pow((x2 - x1), 2) + pow((y2 - y1), 2) ) );
}

float calc_area(float a, float b, float c)
{
    float S;

    S = (a + b + c) / 2.0;

    return( sqrt(S * (S - a) * (S - b) * (S - c) ) );
}

Output 1:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
5 2

Area of Triangle = 100.000000
Point (5.0, 2.0) lies within the Triangle

Output 2:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
10 20.1

Area of Triangle = 100.000000
Point (10.0, 20.1) lies outside the Triangle

Output 3:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
20 0
Enter value for(x3, y3)
10 30
Enter point(x, y) to check if it lies inside the Triangle
10 15

Area of Triangle = 300.000000
Point (10.0, 15.0) lies within the Triangle

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

C Program To Draw Pyramid of Numbers, using For Loop

Lets write a C program to draw / display / print a four row pyramid formed from numbers 1 to 10.

Related Read:
Nested For Loop In C Programming Language
C Program To Draw Pyramid of Numbers, using While Loop

Video Tutorial: C Program To Draw Pyramid of Numbers, using For Loop


[youtube https://www.youtube.com/watch?v=Z-uVxVnXqgE]

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

Source Code: C Program To Draw Pyramid of Numbers, using For Loop

#include<stdio.h>
int main()
{
    int num = 4, row, col, space, count = 1;
    float i = -7;


    for(row = 1; row <= num; row++)
    {
        for(space = i; space <= (num-row); space++)
        {
            printf(" ");
        }
        for(col = 1; col <= row; col++)
        {
            printf(" %d ", count++);
        }
        i += 0.8;

        printf("\n");
    }

    return 0;
}

Output

                    1
                  2  3
                 4  5  6
               7  8  9  10

Logic To Draw Pyramid of Numbers, using For Loop

Here we already know that the Pyramid we need to print has 4 rows and is formed of numbers 1 to 10.

Outer for loop selects the row number and the number of elements to be printed for that particular selected row. For example, 1st row has 1 element. 2nd row has 2 elements. 3rd row has 3 elements and so on. So the row number and the number of elements in that particular row are always the same.

First inner for loop prints the adequate spacing required for the pyramid. Second inner for loop prints the actual numbers.

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

C Program To Draw Pyramid of Stars, using For Loop

Lets write a C program to draw / print / display a pyramid / triangle formed from stars, using nested for loop.

Related Read:
Nested For Loop In C Programming Language
C Program To Draw Pyramid of Stars, using While Loop

Expected Output for the Input

User Input:
Enter no of rows of Pyramid
5

Output:

    
     *
    ***
   *****
  *******
 *********

Pyramid With 20 Rows
pyramid of stars

Video Tutorial: C Program To Draw Pyramid of Stars, using For Loop


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

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

Logic To Draw Pyramid of Stars, using For Loop

If num = 5;

First Iteration of outer for loop
row = 1;

1st inner for loop
condition:
num – row;
= 5 – 1
= 4
Four spaces gets printed.

2st inner for loop
condition:
2 * row – 1;
= 2 * 1 – 1;
= 2 – 1
= 1
One star gets printed.

Second Iteration of outer for loop
row = 2;

1st inner for loop
condition:
num – row;
= 5 – 2
= 3
Three spaces gets printed.

2st inner for loop
condition:
2 * row – 1;
= 2 * 2 – 1;
= 4 – 1
= 3
Three stars gets printed.

Third Iteration of outer for loop
row = 3;

1st inner for loop
condition:
num – row;
= 5 – 3
= 2
Two spaces gets printed.

2st inner for loop
condition:
2 * row – 1;
= 2 * 3 – 1;
= 6 – 1
= 5
Five stars gets printed.

Forth Iteration of outer for loop
row = 4;

1st inner for loop
condition:
num – row;
= 5 – 4
= 1
One space gets printed.

2st inner for loop
condition:
2 * row – 1;
= 2 * 4 – 1;
= 8 – 1
= 7
Seven stars gets printed.

Fifth Iteration of outer for loop
row = 5;

1st inner for loop
condition:
num – row;
= 5 – 5
= 0
Zero space gets printed.

2st inner for loop
condition:
2 * row – 1;
= 2 * 5 – 1;
= 10 – 1
= 9
Nine stars gets printed.

Source Code: C Program To Draw Pyramid of Stars, using For Loop

#include<stdio.h>

int main()
{
    int num, row, col, space;

    printf("Enter no of rows of Pyramid\n");
    scanf("%d", &num);

    for(row = 1; row <= num; row++)
    {
        for(space = 1; space <= (num-row); space++)
        {
            printf(" ");
        }
        for(col = 1; col <= (2*row-1); col++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

Output 1:
Enter no of rows of Pyramid
5

     *
    ***
   *****
  *******
 *********

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

C Program To Display Right Angled Triangle With Alphabets, using For Loop

Lets write a C program to display/print/output a right angled triangle pattern formed with Capital Letter English Alphabets, using nested for loop.

Related Read:
Nested For Loop In C Programming Language
C Program To Display Right Angled Triangle With Alphabets, using While Loop

Expected Output for the Input

If user enters number of rows as 5. Then our C program prints a Right angled Triangle with 5 rows of Capital Letter English Alphabets in it.

User Input:
num = 5;

Output:

A
B C
D E F
G H I J
K L M N O

Video Tutorial: C Program To Display Right Angled Triangle With Alphabets, using For Loop


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

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

Logic To Display Right Angled Triangle With Alphabets, using For Loop

If we take a closer look at the right angled triangle, we can see that the number of rows and the number of elements in that row are same. Example, row number 5 has 5 elements. Row number 6 has 6 elements etc. So we store this number in a variable called row. Since row starts from 1, we initialize the variable row to 1.

Outer For Loop

We ask the user to enter the maximum number of rows for the right angled triangle, and store it in address of variable num. Outer for loop selects the row. Outer for loop executes until row value is less than or equal to the user entered number.

Inner For Loop

Inner For loop prints the Alphabets. Printing starts from 1st position. So we initialize variable col to 1. And inner for loop iterates until col is less than or equal to the value present in variable row.

Inside inner for loop we check if the value of variable count is 91(ASCII Value of Z is 91). If true, we resent the value of count to 65(ASCII Value of A is 65).

Note: Row number is equal to the number of elements present in that row.

Source Code: C Program To Display Right Angled Triangle With Alphabets, using For Loop

#include<stdio.h>

int main()
{
    int num, row, col, count = 65;

    printf("Enter no of rows\n");
    scanf("%d", &num);

    printf("\n");
    for(row = 1; row <= num; row++)
    {
        for(col = 1; col <= row; col++)
        {
            if(count == 91)
                count = 65;

            printf("%c  ", count++);
        }
        printf("\n");
    }

    return 0;
}

Output 1:
Enter no of rows
5

A
B C
D E F
G H I J
K L M N O

Output 2:
Enter no of rows
10

A
B  C
D  E  F
G  H  I  J
K  L  M  N  O
P  Q  R  S  T  U
V  W  X  Y  Z  A  B
C  D  E  F  G  H  I  J
K  L  M  N  O  P  Q  R  S
T  U  V  W  X  Y  Z  A  B  C

Related Read:
C Program To Print All ASCII Characters and Value using For Loop

ASCII value of A is 65

ASCII value of B is 66

ASCII value of C is 67

ASCII value of D is 68

ASCII value of E is 69

ASCII value of F is 70

ASCII value of G is 71

ASCII value of H is 72

ASCII value of I is 73

ASCII value of J is 74

ASCII value of K is 75

ASCII value of L is 76

ASCII value of M is 77

ASCII value of N is 78

ASCII value of O is 79

ASCII value of P is 80

ASCII value of Q is 81

ASCII value of R is 82

ASCII value of S is 83

ASCII value of T is 84

ASCII value of U is 85

ASCII value of V is 86

ASCII value of W is 87

ASCII value of X is 88

ASCII value of Y is 89

ASCII value of Z is 90

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