C program to print hollow square star pattern

  • Write a program in C to print hollow square star (*) pattern of n rows using for loop.
  • Write a C program to print outline or boundary of a square pattern by star (*) character using loop.

For a hollow square star pattern of side 5 stars. Program’s output should be:

Hollow_Square_Star_Pattern

Required Knowledge

Algorithm to print hollow square star pattern using loop
The algorithm of this pattern is similar to square star pattern except here we have to print stars of first and last rows and columns. At non-boundary position, we will only print a space character.

  • Take the number of stars in each side of square as input from user using scanf function. Let it be N.
  • We will use two for loops to print square star pattern.
    • Outer for loop will iterate N times. In one iteration, it will print one row of pattern.
    • Inside inner for loop, we will add a if statement check to find the boundary positions of the pattern and print star (*) accordingly.

Here is the matrix representation of the hollow square star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Hollow_Square_Star_Pattern

C program to print hollow square star pattern

C program to print hollow square star pattern

#include<stdio.h>
 
int main(){
    int side, i, j;
     
    printf("Enter side of square\n");
    scanf("%d", &side);
     
    /* Row iterator for loop */
    for(i = 0; i < side; i++){
     /* Column iterator for loop */
        for(j = 0; j < side; j++){
            /* Check if currely position is a boundary position */
            if(i==0 || i==side-1 || j==0 || j==side-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

Output

Enter side of square
5
*****
*   *
*   *
*   *
*****

C program to print rectangular star pattern

C program to print rectangular star pattern
  • Write a program in C to print rectangular star (*) pattern of n rows and m columns using for loop.
  • Write a C program to print a rectangle pattern of star (*) character using loops.

For a rectangular star pattern of 5 rows and 9 columns. Program’s output should be:

Rectangle_Star_Pattern_Program

Required Knowledge

Algorithm to print rectangular star pattern using loop

  • Take the number of rows(N) and columns(M) of rectangle as input from user using scanf function.
  • We will use two for loops to print rectangular star pattern.
  • Outer for loop will iterate N times. In each iteration, it will print one row of pattern.
  • Inner for loop will iterate M times.In one iteration, it will print one star (*) characters in a row.

Here is the matrix representation of the rectangle star pattern. The row numbers are represented by i whereas column numbers are represented by j.

Rectangle_Star_Pattern_Matrix

C program to print rectangular star pattern

C program to print rectangular star pattern

#include<stdio.h>
 
int main(){
    int rows, cols , i, j;
     
    printf("Enter rows and columns of rectangle\n");
    scanf("%d %d", &rows, &cols);
     
    /* Row iterator for loop */
    for(i = 0; i < rows; i++){
     /* Column iterator for loop */
        for(j = 0; j < cols; j++){
           printf("*");
        }
        printf("\n");
    }
    return 0;
}

Output

Enter rows and columns of rectangle
3 9
*********
*********
*********

C program to print inverted right triangle star pattern

C program to print inverted right triangle star pattern
  • Write a program in C to print inverted right triangle star (*) pattern of n rows using for loop.
  • Write a C program to print a inverted right angles triangle pattern of star (*) character using loops.

For a inverted right triangle star pattern of 7 rows. Program’s output should be:

Inverted_Right_Triangle_Star_Pattern

Required Knowledge

Algorithm to print inverted right triangle star pattern using loop

If you look closely, this pattern is the vertically inverted pattern of right triangle star pattern. As the row number increases from top to bottom, number of stars in a row decreases.
NOTE: The index of rows and columns starts from 0.

  • Take the number of rows(N) of inverted right triangle as input from user using scanf function.
  • Number of stars in Kth row is equal to (N – K + 1). In the pattern given above, N = 7. Hence, 1st row contains 7 star, 2nd row contains 6 stars, 3rd row contains 5 stars.
  • We will use two for loops to print inverted right triangle star pattern.
    • For a inverted right triangle star pattern of N rows, outer for loop will iterate N time(from i = 0 to N-1). Each iteration of outer loop will print one row of the pattern.
    • For jth row of inverted right triangle pattern, inner loop will iterate N-j times(from j = 0 to N-j). Each iteration of inner loop will print one star character.

Here is the matrix representation of the inverted right triangle star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Inverted_Right_Triangle_Star_Pattern_Matrix

C program to print inverted right triangle star pattern

C program to print inverted right triangle star pattern

#include<stdio.h>
 
int main() {
    int i,j,rows;
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
 
    for(i = 0; i < rows; i++) {
        /* Prints one row of triangle */
        for(j = 0; j < rows - i; j++) {
            printf("* ");
        }
        /* move to next row */
        printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
7
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

C program to print mirrored right triangle star pattern

C program to print mirrored right triangle star pattern
  • Write a program in C to print mirrored right angled triangle star (*) pattern using for loop.
  • Write a C program to print a mirrored right angles triangle pattern of star (*) character of n rows.

For a mirrored right triangle star pattern of 7 rows. Program’s output should be:

Mirrored_Triangle_Star_Pattern

Required Knowledge

Algorithm to print mirrired right triangle star pattern using loop

C program to print mirrored right triangle star pattern is similar to the right triangle star pattern program. Once you understand how to print right triangle pattern then printing it’s mirrored pattern will be an easy task.

  • Take the number of rows(N) of mirrored right triangle as input from user using scanf function.
  • In any row, the sum of spaces and stars are equal to N. Number of stars increases by one and number of spaces before stars decreases by 1 in consecutive rows.
  • In any row R, we will first print N-R-1 space characters then R+1 star characters.

Here is the matrix representation of the inverted triangle star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Inverted_triangle_Star_Pattern

C program to print mirrored right triangle star pattern

C program to print mirrored right triangle star pattern

#include <stdio.h>
 
int main() {
    int i, j, rows;
 
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
 
    for(i = 0; i < rows; i++){
        /* for j th row, first print rows-r spaces then stars */
        for(j = 0; j < rows; j++){
            if(j < rows-i-1){
                printf(" ");
            } else {
                printf("*");
            }
        }
        /* move to next row */
        printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
6
     *
    **
   ***
  ****
 *****
******

Here is the C program to print inverted right triangle star pattern using one for loop

Here is the C program to print inverted right triangle star pattern using one for loop

#include<stdio.h>
  
int main(){
    char *str="*******************";
    int i,j, rows;
     
    printf("Enter the number of rows\n");
    scanf("%d", &rows); 
     
    for(i = 0; i < rows; i++){
       printf("%*.*s\n", rows, i+1, str);
    }
     
    return 0;
}
</stdio.h>

Output

Enter the number of rows
5
    *
   **
  ***
 ****
*****

C program to print reversed mirrored right triangle star pattern

C program to print reversed mirrored right triangle star pattern
  • Write a program in C to print reversed inverted right triangle star (*) pattern of n rows using for loop.

For a reversed mirrored right triangle star pattern of 7 rows. Program’s output should be:

Inverted_Star_Triangle_Pattern_2

Required Knowledge

Algorithm to print reversed mirrored right triangle star pattern using loop
If you look closely, this pattern is similar to inverted right triangle star pattern. For Rth row, we have to print R space characters before stars.

  • Take the number of rows(N) of reversed inverted right triangle as input from user using scanf function.
  • Each row(R) contains N characters, R space characters followed by N-R star (*) character.
  • We will use two for loops. Outer for loop will print one row in one iteration.
  • One iteration of inner loop will first print R space characters followed by N-R star (*) character

Here is the matrix representation of the mirrored triangle star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Inverted_triangle_star_pattern2

C program to print reversed mirrired right triangle star pattern

C program to print reversed mirrored right triangle star pattern

#include <stdio.h>
 
int main() {
    int i, j, rows;
 
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
 
    for (i = 0; i < rows; i++) {
        for (j = 0; j < rows; j++) {
            if (j < i) {
                printf(" ");
            } else {
                printf("*");
            }
        }
        printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
6
******
 *****
  ****
   ***
    **
     *

C program to print pyramid star pattern or equilateral triangle star pattern

C program to print pyramid star pattern or equilateral triangle star pattern
  • Write a program in C to print pyramid star pattern using for loop.
  • Write a C program to print an equilateral triangle star pattern of n rows using loops.

For an equilateral triangle pyramid star pattern of 5 rows. Program’s output should be:

Pyramid_Star_Pattern

Required Knowledge

Algorithm to print pyramid star pattern using loop
In this program, we are printing a pyramid star pattern in which ith row contains (2*i + 1) space separated stars. The index of rows and columns starts from 0.

  • We first take the number of rows(R) in the pattern as input from user using scanf function.
  • One iteration of outer for loop will print a row of pyramid(from i = 0 to R – 1).
  • For jth row of pyramid, the inner for loop first prints (R – i – 1) spaces for every line and then nested while loop prints (2*j + 1) stars.

Here is the matrix representation of the pyramid star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Pyramid_Star_Pattern

C program to print pyramid star pattern

C program to print pyramid star pattern or equilateral triangle star pattern

#include<stdio.h>
 
int main() {
    int i, j, rows, star = 0;
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
 
    /* printing one row in every iteration */
    for (i = 0; i < rows; i++) {
        /* Printing spaces */
        for (j = 0; j <= (rows - i - 1); j++) {
            printf(" ");
        }
        /* Printing stars */
        while (star != (2 * i + 1)) {
            printf("*");
            star++;;
        }
        star = 0;
        /* move to next row */
        printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
6
     *
    ***
   *****
  *******
 *********
***********

C program to print rhombus star pattern

C program to print rhombus star pattern
  • Write a C program to print rhombus star pattern using for loop.

For a rhombus star pattern of 6 rows. Program’s output should be:

Rhombus_Star_Pattern

Required Knowledge

Algorithm to print rhombus star pattern using loop

  • We first take the number of rows(N) as input from user using scanf function.
  • The index of rows and columns will start from 0.
  • Each row of rhombus star pattern contains N star characters.
  • Each iteration of outer for loop(from i = 0 to N-1) will print one row of pattern at a time.
  • Each jth row, contains j space characters followed by N star characters.
  • First inner for loop prints space characters whereas second inner for loop prints star characters.

Here is the matrix representation of the rhombus star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Rhombus_Star_Pattern_Program

 program to print rhombus star pattern

C program to print rhombus star pattern

#include <stdio.h>
 
int main() {
    int i, j, rows;
 
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
 
    for (i = 0; i < rows; i++) {
        /* Print spaces before stars in a row */
        for (j = 0; j < i; j++) {
            printf(" ");
        }
        /* Print rows stars after spaces in a row */
        for (j = 0; j < rows; j++) {
            printf("*");
        }
        /* jump to next row */
        printf("\n");
    }
    return 0;
}

Output

Enter the number of rows
6
******
 ******
  ******
   ******
    ******
     ******

Storage Classes in C Programming

  • In this tutorial, we will learn about various storage classes in C like static, auto, register and extern. We will also study the effect of storage classes on storage and visibility of variables.

A Storage class defines the scope, life-time and where to store a variable in C program. There are four storage classes defined in C programming language

  • static
  • auto
  • register
  • extern

Static Variable

A local static variable is visible only inside their own function but unlike local variables, they retain their values between function calls. We can declare static variable by adding static keyword before data type in variable declaration statement.

static data_type variable_name;

For Example:

static int sum;
  • Static keyword has different effect on local and global variables.
  • For local static variables, compiler allocates a permanent storage in heap like global variable, so that they can retain their values between function calls. Unlike global variables, local static variables are visible only within their function of declaration.
  • For global static variables, compiler creates a global variable which is only visible within the file of declaration.
  • Variables declared static are initialized to zero(or for pointers, NULL) by default.

In the following program, we declared a local and a static variable inside getVal function. Output of this programs shows that static variable retains it’s value between successive function call whereas local variable vanishes when control exits function block.

Storage Classes in C Programming

#include <stdio.h>
 
int printVal(){
    /* Declaring a static variable */    
    static int staticVariable = 0; 
    /* Declaring a local variable */
    int localVariable = 0;
     
    /*Incrementing both variables */
    staticVariable++;
    localVariable++;
     
    printf("StaticVariable = %d, LocalVariable = %d\n", staticVariable, localVariable);
}
 
int main(){
   printVal();
   printVal();
   printVal();
   printVal();
    
   return 0;
}

Output

StaticVariable = 1, LocalVariable = 1
StaticVariable = 2, LocalVariable = 1
StaticVariable = 3, LocalVariable = 1
StaticVariable = 4, LocalVariable = 1

Automatic variable

A variable which is declared inside a function or block is automatic variable by default. We can declare automatic variables using auto keyword, but it is rarely used because by default every variable is automatic variable.

Storage Classes in C Programming 1

#include <stdio.h>
 
int main(){
    /* Automatic variable by default */
    int a = 5;
    /* Declaration of automatic variables using auto keyword */
    auto int b = 10;
 
    printf("Sum = %d", a+b);
 
    return 0;
}

Output

Sum = 15

Register Variable

Declaring a variable with register keyword is a hint to the compiler to store this variable in a register of the computer’s CPU instead of storing it in memory. Storing any variable in CPU register, will reduce the time of performing any operation on register variable. We can declare register variables using register keyword.

  • The scope of register variables are same as automatic variables, visible only within their function.
  • You a only declare local variables and formal parameters of a function as register variables, global register variables are not allowed.
  • Declaring a variable as register is a request to the compiler to store this variable in CPU register, compiler may or may not store this variable in CPU register(there is no guarantee).
  • Frequently accessed variables like loop counters are good candidates for register variable.

Register Variable

#include <stdio.h>
 
int main(){
    /* Declaration of register variables using register keyword */
    register int counter;
    int sum=0;
    /* Variable counter is used frequently within for loop */
    for(counter = 1; counter <= 500; counter++){
        sum+= counter;
    }
    printf("Sum = %d", sum);
    
    return 0;
}

Output

Sum = 125250

External Variable

External variables in C are variables which can be used across multiple files. We you can declare an external variable by preceding a variable name with extern specifier. The extern specifier only tells the compiler about the name and data type of variable without allocating any storage for it. However, if you initialize that variable, then it also allocates storage for the extern variable.

  • Variables declared extern are initialized to zero by default.
  • The scope of the extern variable is global.
  • The value of the external variable exists till program termination.

Arrays in C Programming

Array in C programming language is a collection of fixed size data belongings to the same data type. An array is a data structure which can store a number of variables of same data type in sequence. These similar elements could be of type int, float, double, char etc.

For Example

int age[100]; /* Integer array of size 100 */
float salary[10]; /* floating point array of size 10 */

Suppose, you want to store salary of 100 employees. You can store salaries of all employees by creating 100 variable of int data type individually like employeeSalary1, employeeSalary2, employeeSalary3 …. employeeSalary100. This is very tedious, time consuming and difficult to maintain method of storing 100 salaries.

C programming language provides support for array data structure, which solves the problem of storing N similar data. We can declare an integer array of length 100 to store salaries of 100 employees

    int employeeSalary[100];
In the above array declaration, we declared an array of name “employeeSalary” which can store maximum of 100 integer data in contiguous memory locations. We can access the individual elements of an array using their index.

  • employeeSalary[0] refers to the first element of array.
  • employeeSalary[1] refers to the second element of array.
  • employeeSalary[99] refers to the last element of array which is 100th element.

All elements of array are stored in the contiguous memory locations.

Suppose, we have an integer array of size 7 whose name is score. The base address or starting address of array score is 1000(base address is same as address of first element score[0]) and the size of int be 2 bytes. Then, the address of second element(score[1]) will be 1002, address of third element(score[2]) will be 1004 and so on.

C-Array

Arrays in Details

  • Initialization of Array in C
  • Accessing Array Elements in C
  • Multi Dimensional Arrays in C
  • Passing Array to a Function in C
  • Returning Array to a Function in C

Important Facts about Arrays in C

  • An array is a collection of variables of same data types.
  • All elements of array are stored in the contiguous memory locations.
  • The size of array must be a constant integral value.
  • Individual elements in an array can be accessed by the name of the array and an integer enclosed in square bracket called subscript/index variable like employeeSalary[5].
  • Array is a random access data structure. you can access any element of array in just one statement.
  • The first element in an array is at index 0, whereas the last element is at index (size_of_array – 1).

Advantage of Array in C

  • Less amount of code : Using array we can aggregate N variables of same data type in a single data structure. Otherwise we have to declare N individual variables.
  • Easy access of elements : We can access any element of array using array name and index. We can access all elements serially by iterating from index 0 to size-1 using a loop.
  • Easy to implement algorithms : Certain algorithms can be easily implemented using array like searching and sorting, finding maximum and minimum elements.
  • Random Access : We can access any elements of array in O(1) time complexity.

Declaration of Array in C

Like any other variable in C, we must declare an array first before using it. Below is the syntax of declaring a one-dimensional array.

data_type array_name[array_size];

  • array_name : It is a valid C identifier representing the name of the array.
  • array_size : It is the maximum number of elements which can be stored in array. It must be an integer constant greater than zero.
  • data_type : It represents the data type of the elements to be stored in array.

Examples of Array Declaration in C

  • An Array of 10 Integers
    int marks[10];
  • An Array of 50 Characters.
    char name[50];
  • Two Dimensional Array of Integers.
    int matrix[10][10];

Types of Array in C

There are two types of Arrays in C

  • One Dimensional Array
  • Multi Dimensional Array

One Dimensional Array in C

  • Single dimensional array is used to store data in sequential order.
  • Single dimensional array contains only one subscript/index in their declaration, like
    int marks[100];
  • In one dimensional array, we can access any element using one index reference, like marks[5].

Multi Dimensional Array in C

  • Array having more than one subscript variable/index is called multi dimensional array.
  • Multi dimensional array is array of array.
  • Multi dimensional array contains multiple subscript/index in their declaration, like
    int matrix[10][20];
  • In multi dimensional array, we can access any element using multiple index reference, like matrix[4][8].

Pointer to a Pointer in C Programming

Pointer to a Pointer in C Programming

A pointer to a pointer in C programming is a pointer variable which is used to store the address of another variable. A pointer can store the address of another pointer variable also like any other data type pointer.

A pointer to a pointer means, first pointer will contains the address of second pointer and second pointer can will contain the add of actual value stored in memory.

We use double * operator to define a pointer to a pointer.

<data_type> **<identifier>;

For Example

int count = 10;
int *ptr = &count; /* Pointer to an integer variable */
int **ptrToPtr = &ptr; /* Pointer to a pointer */ 

To access the value of count variable using pointer variable ‘ptr’, we need one asterisk operator(*) like

*ptr;

and to access the value of count variable using pointer to a pointer variable ‘ptrToPtr’, we need two asterisk operator(*) like

**ptrToPtr;

first asterisk returns the memory address stored inside pointer ‘ptr’ and second asterisk retrieves the value stored at memory location pointer by ‘ptr’.

C program to show the use of pointer to a pointer

Pointer to a Pointer in C Programming

#include <stdio.h>
#include <conio.h>
 
int main () {
   int count = 10;
   /* pointer to an integer variable */
   int *ptr = &count;
   /* pointer to a pointer*/
   int **ptrToPtr = &ptr;
    
   printf("Value of count variable = %d\n", count);
   printf("Value of count variable retreived uisng ptr %d\n", *ptr);
   printf("Value of count variable retreived uisng ptrToPtr = %d\n", **ptrToPtr);
 
   getch();
   return 0;
}

Output

Value of count variable = 10
Value of count variable retreived uisng ptr 10
Value of count variable retreived uisng ptrToPtr = 10