Pages

Simple C Language Program to Print Shapes


Printing shapes is a common task given to C Language students. It is a good way to capture the main concepts of looping. We'll discuss different methods to print shapes in C Language using looping. If you get these simple concepts well, then the rest becomes a smooth ride.
So, let's start with the show.

C Program: Print a Square


#include <stdio.h>
int main()
{
    int n, a, b;
    n = 6;
    for(a=1;a<=n;a++)
    {
                     for(b=1;b<=n;b++)
                     printf("*");
    printf("\n");}
    return 0;
}

Output



This is very a simple example. The program prints a square with a fixed height and length. It uses three variables n, a and b. 'n' specifies the length and height of the square (in number of stars) while a and b are loop counters. The program utilizes the concept of nested For Loops. The main For Loop starts on line 6 and ends on 10.

    for(a=1;a<=n;a++)
    {
                     for(b=1;b<=n;b++)
                     printf("*");
    printf("\n");}

In line 6, the first For Loop initializes loop counter 'a' to a value of 1. The condition (a <=  n) makes sure that the loop is executed 'n' number of times. The second For Loop starts at line 8 with the initialization of loop counter 'b' to a value of 1. This loop also executes 'n' number of times and each time prints an asterisk(*). Thus, printing a whole row. So, each time the first loop executes, the second loop executes 'n' number of times and prints an asterisk. The control then returns to the first loop which prints a new line character '\n'. In this way, a square gets printed.

C Program: Print a Right Triangle

This another simple C program that prints a right triangle, a triangle that contains a right angle. So, here's the code.

Code


#include <stdio.h>
int main()
{
    int a=12, b, c;
    
    for(b=1 ; b<=a ; b++)
    {
               for(c=1;c<=b;c++)
               printf("*");
               
    printf("\n");
}
return 0;
}

Output



This program works in quite similar fashion as the last one. It also contains nested For Loops. The inner For Loop prints the asterisks while the the outer one prints a newline character (\n) after each row. You can notice that the first row contains one asterisk, the second row two and the third row has three stars. In this way a triangle gets printed.

You can go through the code and in case of any confusion, you can feel free to ask me by using the contact form below.


Don't Forget to Share...