ANIMATED PLUS SIGN IN C LANGUAGE
AMRUHA AHMED
22nd November, 2023.
This article will aid you in the creation of an animated plus sign in C language. This pattern is generated by a combination of nested loops and the animation is provided by the usage of threads.
DELVING DEEPER:
- 1.This pattern requires the usage of nested loops to print the asterisks in the appropriate manner
- 2.A separate variable needs to be reserved to keep track of the number of spaces printed before the asterisks are printed on the screen
- 3.The sleep method of threads needs to be inserted at appropriate intervals to impart an animated feel to the entire plus sign
BREAK-UP OF THE PATTERN:
- 1.A total of 11 rows need to be printed in the pattern
- 2.The dashes shown above are an indication of spaces required. A separate variable for space is initialized to 5 which remains constant for each iteration.
- 3.In case the middle of the pattern is not reached (row 6 is not reached) then, after the spaces are printed on the screen , then a single asterisk is now printed. This step ensures the creation of the vertical line of the plus sign.
- 4.In case the middle of the pattern( that is row 6) is reached then no space is printed. Instead, asterisks are printed in the entire row. This helps us to create the horizontal line of the plus sign.
- 5.Sleep method is introduced at this stage to ensure lag after each iteration
FUNCTIONS REQUIRED:
- 1.main( ) : used for thread creation
- 2.*runner( ) :contains instructions required to generate the plus sign. This method is executed only if the thread is successfully created in the main method.
PROGRAM:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
void *runner();
void main()
{
pthread_t tid;//thread id
int ret;//to store the return value
ret=pthread_create(&tid,NULL,runner,0);//thread creation
if(ret==-1)
{
printf("\n thread not created");
exit(1);
}
pthread_join(tid,0);
}
void *runner()
{
int m=5;//spaces before the *
int i,j;//loop counters
for(i=1;i<=11;i++)
{
if(i!=6)//when the iteration hasn't reached the middle of the pattern
{
for(j=1;j<=m;j++)
printf(" ");
printf("* ");
}
else//outer loop has reached the middle of the pattern
{
for(j=1;j<=11;j++)//printing the horizontal line
printf("* ");
}
sleep(1);
printf("\n");
}
}
OUTPUT: