CODING JOY

The stunning potpourri of coding and mundane life

DISPLAYING AN ANIMATED CROSS PATTERN USING THREADS IN C LANGUAGE



AMRUHA AHMED
16th May,2023.



This article will help you to create an animated cross pattern using threads in C language. The cross pattern can be generated by using certain nested loops and the animation is achieved through the usage of threads.

blog1

DELVE DEEPER INTO THE PATTERN:


BREAK UP OF THE UPPER HALF OF THE PATTERN:

blog1

BREAK UP OF THE LOWER HALF OF THE PATTERN:

blog1

One thing to be kept in mind is that, all these instructions of pattern creation are present in the runner method of the program;these instructions are exceuted by a thread created in the main method.


FUNCTIONS REQUIRED:


PROGRAM:

The following is the code written in C to print the desired pattern on the screen and add animations to it by using the concept of threads:

                
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
void *runner();
void main()
{
    pthread_t tid;//thread id
    int ret;//to store a return value
    ret=pthread_create(&tid,NULL,runner,0);//creating a thread
    
    if(ret==-1)
    {
        printf("\n Thread has not been created");
        exit(1);
    }
    pthread_join(tid,0);
 
}

void *runner()
{
    int i,j,m,n;// i and j are loop counters 
    // m and n are used as counters for spacing
    m=0;
    n=7;
    for(i=1;i<=5;i++)
    {//to generate upper half of the pattern
       for(j=1;j<=m;j++)
       {
           printf("   ");
       }
       printf("* ");
    
       
       for(j=1;j<=n;j++)
       printf("   ");
       m+=1;
       n-=2;
       if(i==5)
        continue;
       printf("* ");
       sleep(2);
       printf("\n");
       
    }
    n=1;
    m=3;
    printf("\n");
    for(i=1;i<=4;i++)
    { //to generate lower half of the pattern
        for(j=1;j<=m;j++)
        printf("   ");
        printf("* ");
        for(j=1;j<=n;j++)
        printf("   ");
        printf("* ");
        sleep(2);
        m-=1;
        n+=2;
        printf("\n");
        
    }
    pthread_exit(0);
}

                   
             
         
CODE COPIED

OUTPUT: