string.h C Library Functions

The string.h header file includes C standard library functions for string manipulation like copy, search, append, compare, splitting a string etc.

List of string.h Library Functions

Click on function names below to see detailed description of functions.

Function Description
memchr It searches for first occurence of a character in memory location.
memcmp It compares the first n bytes of two memory blocks.
memcpy It copies the first n bytes from one memory block to another.
memmove It moves the first n bytes from one memory block to another considering overlap.
memset It copies the character c to the first n bytes of the block of memory.
strcat It appends one string at the end of another string.
strchr It searches for the first occurrence of a character in the string.
strcmp It compares two strings character by character.
strncmp It compares first n characters of two strings.
strcpy It copies characters from one string into another string.
strncpy It copies first n characters from one string into another string.
strcspn It calculates the length of prefix of a string which doesn’t contain any character of another string.
strlen It returns the length of a string.
strncat It appends first n characters of one string at the end of another string.
strpbrk It searches for the first occurrence of any character of a string in another string.
strrchr It searches for the last occurrence of a character in the string.
strspn It returns the length of the initial segment of a string which consists entirely of characters in another string.
strstr It searches for the first occurrence of a string in another string.
strtok It breaks a string into smaller tokens.

Variable type in string.h Library

Type Description
size_t This is unsigned integral type

Macros in string.h Library

Macro Description
NULL Null pointer constant

strcat C Library Function

strcat C Library Function

he function char *strcat(char *destination, const char *source); appends string pointed by source at the end of string pointed by destination. It will overwrite null character of destination and append a null character at the end of combined string. Destination string should be large enough to contain the concatenated string.

Function prototype of strcat

char *strcat(char *destination, const char *source);
  • destination : This is pointer to destination array(containing a null terminated string) where we want to append another string.
  • source : It is a pointer to a string to be appended. This should not overlap destination.

Return value of strcat

It returns a pointer to destination string.

C program using strcat function

The following program shows the use of strcat function to append one string at the end of another string.

strcat C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char stringOne[100], stringTwo[100];
 
   printf("Enter first string\n");
   gets(stringOne);
   printf("Enter second string\n");
   gets(stringTwo);
    
   strcat(stringTwo, stringOne);
   printf("Second string after strcat\n%s", stringTwo);
 
   getch();
   return(0);
}

Output

Enter first string
CrashCourse
Enter second string
Tech
Second string after strcat
TechCrashCourse

strcmp C Library Function

strcmp C Library Function

The function int strcmp(const char *str1, const char *str2); compares string pointed by str1 with string pointed by str2. This function compares both string character by character. It will continue comparison until the characters mismatch or until a terminating null-character is reached.

Function prototype of strcmp

int strcmp(const char *str1, const char *str2);
  • str1 : A pointer to a C string to be compared.
  • str2 : A pointer to a C string to be compared.

Return value of strcmp

Return Value Description
Positive (>0) str2 is less than str1
Zero (==0) str1 is equal to str2
Negative (<0) str1 is less than str2

C program using strcmp function

The following program shows the use of strcmp function to compare two strings.

strcmp C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char firstString[100], secondString[100];
   int response;
   printf("Enter first string\n");
   scanf("%s", &firstString);
   printf("Enter second string\n");
   scanf("%s", &secondString);
    
   response = strcmp(firstString, secondString, 5);
 
   if(response > 0){
      printf("second String is less than first String");
   } 
   else if(response < 0) {
      printf("first String is less than second String");
   }
   else {
      printf("first String is equal to second String");
   }
    
   getch();
   return(0);
}

Output

Enter first string
asdfg
Enter second string
ASDFG
second String is less than first String
Enter first string
testString
Enter second string
testString
first String is equal to second String

C Program to Draw Stars in Night Sky Using C Graphics

Write a program in C to draw stars in night sky using graphics.h header file

In this program, we will randomly select 500 pixels on screen and color them in while. We will use putpixel functions of graphics.h header file to color a pixel at (x, y).

C program to draw stars in night sky using graphics

In this program, we first initialize graphics mode, by passing graphics driver(DETECT), default graphics mode and specifies the directory path where initgraph looks for graphics drivers (*.BGI). Then we will randomly select any (x, y) coordinate using rand, getmaxx and getmaxy function and color it using putpixel function. After 500 milliseconds we will clear screen and again paint the screen with stars until presses any key.

C Program to Draw Stars in Night Sky Using C Graphics

#include <conio.h>
#include <graphics.h>
#include <dos.h>
#include <stdlib.h>
 
int main() {
    int gd = DETECT, gm;
    int i, x, y;
    initgraph(&gd, &gm, "C:\\TC\\BGI");
        
 
 while (!kbhit()) {
      /* color 500 random pixels on screen */
   for(i=0; i<=500; i++) {
       x=rand()%getmaxx();
          y=rand()%getmaxy();
          putpixel(x,y,15);
      }
      delay(500);
 
      /* clears screen */
      cleardevice();
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screen shot of twinkling night sky animation.

STARS

C Program to Draw Pie Chart Using C Graphics

Write a program in C to draw pie chart using graphics.h header file

In this program, we will draw a pie chart on screen having centre at mid of the screen and radius of 120 pixels. We will use outtextxy and pieslice functions of graphics.h header file. Below is the detailed descriptions of graphics functions used in this program.

Function Description
initgraph It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode.
getmaxx It returns the maximum X coordinate in current graphics mode and driver.
getmaxy It returns the maximum Y coordinate in current graphics mode and driver.
outtextxy It displays a string at a particular point (x,y) on screen.
pieslice It draws only a sector of circle having radius r and centre at (x, y), it takes two additional arguments start-angle and end-angle. It also fills the slice with pattern and color set using setfillstyle function.
setfillstyle It sets the current fill pattern and fill color.
closegraph It unloads the graphics drivers and sets the screen back to text mode.
void pieslice(int xCenter, int yCenter, int startAngle, int endAngle, int radius);

C program to draw pie chart using graphics

In this program we first initialize graphics mode, by passing graphics driver(DETECT), default graphics mode and specifies the directory path where initgraph looks for graphics drivers (*.BGI). Then we will draw multiple pie slices having same center coordinates and radius but varying the start angle and end angle. Before drawing a pie slice we change the fill color using setfillstyle function.

C Program to Draw Pie Chart Using C Graphics

#include<graphics.h>
#include<conio.h>
 
int main() {
   int gd = DETECT, gm, x, y;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
 
   settextstyle(BOLD_FONT,HORIZ_DIR,2);
   outtextxy(220,10,"PIE CHART");
   /* Setting cordinate of center of circle */
   x = getmaxx()/2;
   y = getmaxy()/2;
 
   settextstyle(SANS_SERIF_FONT,HORIZ_DIR,1);
   setfillstyle(SOLID_FILL, RED);
   pieslice(x, y, 0, 60, 120);
   outtextxy(x + 140, y - 70, "FOOD");
 
   setfillstyle(SOLID_FILL, YELLOW);
   pieslice(x, y, 60, 160, 120);
   outtextxy(x - 30, y - 170, "RENT");
 
   setfillstyle(SOLID_FILL, GREEN);
   pieslice(x, y, 160, 220, 120);
   outtextxy(x - 250, y, "ELECTRICITY");
 
   setfillstyle(SOLID_FILL, BROWN);
   pieslice(x, y, 220, 360, 120);
   outtextxy(x, y + 150, "SAVINGS");
 
   getch();
   closegraph();
   return 0;
}

Program Output

PIECHART

strncmp C Library Function

strncmp C Library Function

The function int strncmp(const char *str1, const char *str2, size_t n); compares first n characters string pointed by str1 with first n characters of string pointed by str2. This function compares both string character by character. It will compare till n characters until the characters mismatch or a terminating null-character is reached.

Function prototype of strncmp

int strncmp(const char *str1, const char *str2, size_t n);

  • str1 : A pointer to a C string to be compared.
  • str2 : A pointer to a C string to be compared.
  • n : Maximum number of characters to compare.

Return value of strncmp

Return Value Description
Positive (>0) str2 is less than str1
Zero (==0) str1 is equal to str2
Negative (<0) str1 is less than str2

C program using strncmp function

The following program shows the use of strncmp function to compare first n characters of two strings.

strncmp C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char firstString[100], secondString[100];
   int response, n;
   printf("Enter first string\n");
   scanf("%s", &firstString);
   printf("Enter second string\n");
   scanf("%s", &secondString);
   printf("Enter number of characters to compare\n");
   scanf("%d", &n);
    
   response = strncmp(firstString, secondString, n);
 
   if(response > 0){
      printf("second String is less than first String");
   } 
   else if(response < 0) {
      printf("first String is less than second String");
   }
   else {
      printf("first String is equal to second String");
   }
    
   getch();
   return(0);
}

Output

Enter first string
ASDFGiuyiu
Enter second string
ASDFGiuhkjshfk
Enter number of characters to compare
5
first String is equal to second String

strrchr C Library Function

strrchr C Library Function

The function char *strrchr(const char *str, int c); searches for the last occurrence of character c(an unsigned char) in the string pointed by str.

Function prototype of strrchr

char *strrchr(const char *str, int c);
  • str : This is the string to be scanned.
  • c : Character to be searched.

Return value of strrchr

This function returns a pointer to the last occurrence of the character c in the string str. If character c is not found in str, it returns NULL.

C program using strrchr function

The following program shows the use of strrchr function to search last occurrence of a character in a string.

strrchr C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char string[100], ch;
   char *ptr;
 
   printf("Enter a string\n");
   scanf("%s", string);
   printf("Enter a character to search\n");
   scanf(" %c", &ch);
    
   ptr = strrchr(string, ch);
 
   if(NULL == ptr){
      printf("'%c' not found", ch);
   } else {
      printf("Last Occurance of '%c' is at index %d\n", ch, ptr-string);
   }
    
   getch();
   return(0);
}

Output

Enter a string
TechCrashCourse
Enter a character to search
C
Last Occurance of 'C' is at index 9
Enter a string
TechCrashCourse
Enter a character to search
C
C not found

C Program to Make a Digital Clock Using C Graphics

Write a program in C to make a digital clock using graphics.h header file

In this program, we will make a digital clock that print current Day, Month, Year and Date on screen inside a rectangular box. We will use below mentioned graphics functions in this program. Here, we are using time function of time.h header file to get the current epoch time(epoch time is number of seconds since 1 January 1970, UTC). We convert epoch time to string representing the localtime in “www mmm dd hh:mm:ss yyyy” format, where www is the weekday, mmm is the month in letters, dd is the day of the month, hh:mm:ss is the time, and yyyy is the year. After printing current date and time on screen, it waits for 1000 milliseconds(1 second) before printing it again on screen.

C program to make a digital clock using graphics

C Program to Make a Digital Clock Using C Graphics

#include <conio.h>
#include <graphics.h>
#include <time.h>
#include <dos.h>
#include <string.h>
 
int main() {
    int gd = DETECT, gm;
    int midx, midy;
    long current_time;
    char timeStr[256];
 
    initgraph(&gd, &gm, "C:\\TC\\BGI");
 
    /* mid pixel in horizontal and vertical axis */
    midx = getmaxx() / 2;
    midy = getmaxy() / 2;
 
    while (!kbhit()) {
        cleardevice();
        setcolor(WHITE);
        setfillstyle(SOLID_FILL, WHITE);
        rectangle(midx - 250, midy - 40, midx + 250, midy + 40);
        floodfill(midx, midy, WHITE);
        /* Get Current epoch time in seconds */
        current_time = time(NULL);
        /* store the date and time in string */
        strcpy(timeStr, ctime(&current_time));
        setcolor(RED);
        settextjustify(CENTER_TEXT, CENTER_TEXT);
        settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4);
 
        moveto(midx, midy);
        /* print current time */
        outtext(timeStr);
        /* Add delay of 1000 milliseconds(1 second) */
        delay(1000);
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screen shot of digital clock that shows current date and time on screen.

DIGITAL_CLOCK

C Program for Moving Car Animation Using C Graphics

Write a program in C for moving car animation using graphics.h header file
In this program, we will first draw a car and color it. In every iteration of for loop we keep on increasing the x coordinates of every point of car to make it look like this car is moving from left to right. We will use below mentioned graphics functions in this program.

Function Description
initgraph It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode.
getmaxx It returns the maximum X coordinate in current graphics mode and driver.
getmaxy It returns the maximum X coordinate in current graphics mode and driver.
setcolor It changes the current drawing colour. Default colour is white. Each color is assigned a number, like BLACK is 0 and RED is 4. Here we are using colour constants defined inside graphics.h header file.
setfillstyle It sets the current fill pattern and fill color.
circle It draws a circle with radius r and centre at (x, y).
line It draws a straight line between two points on screen.
arc It draws a circular arc from start angle till end angle.
floodfill It is used to fill a closed area with current fill pattern and fill color. It takes any point inside closed area and color of the boundary as input.
cleardevice It clears the screen, and sets current position to (0, 0).
delay It is used to suspend execution of a program for a M milliseconds.
closegraph It unloads the graphics drivers and sets the screen back to text mode.

C program for moving car graphics animation

In this program, we first draw a red color car on left side of the screen (x,y) and then erases it using cleardevice function. We again draw this car at(x + 5, y). This will look like a moving car from left to right direction. We will repeat above steps until car reaches the right side of screen.

C Program for Moving Car Animation Using C Graphics

#include <stdio.h>
#include <graphics.h>
#include <conio.h>
#include <dos.h>
 
int main() {
    int gd = DETECT, gm;
    int i, maxx, midy;
 
    /* initialize graphic mode */
    initgraph(&gd, &gm, "X:\\TC\\BGI");
    /* maximum pixel in horizontal axis */
    maxx = getmaxx();
    /* mid pixel in vertical axis */
    midy = getmaxy()/2;
 
    for (i=0; i < maxx-150; i=i+5) {
        /* clears screen */
        cleardevice();
 
        /* draw a white road */
        setcolor(WHITE);
        line(0, midy + 37, maxx, midy + 37);
 
        /* Draw Car */
        setcolor(YELLOW);
        setfillstyle(SOLID_FILL, RED);
 
        line(i, midy + 23, i, midy);
        line(i, midy, 40 + i, midy - 20);
        line(40 + i, midy - 20, 80 + i, midy - 20);
        line(80 + i, midy - 20, 100 + i, midy);
        line(100 + i, midy, 120 + i, midy);
        line(120 + i, midy, 120 + i, midy + 23);
        line(0 + i, midy + 23, 18 + i, midy + 23);
        arc(30 + i, midy + 23, 0, 180, 12);
        line(42 + i, midy + 23, 78 + i, midy + 23);
        arc(90 + i, midy + 23, 0, 180, 12);
        line(102 + i, midy + 23, 120 + i, midy + 23);
        line(28 + i, midy, 43 + i, midy - 15);
        line(43 + i, midy - 15, 57 + i, midy - 15);
        line(57 + i, midy - 15, 57 + i, midy);
        line(57 + i, midy, 28 + i, midy);
        line(62 + i, midy - 15, 77 + i, midy - 15);
        line(77 + i, midy - 15, 92 + i, midy);
        line(92 + i, midy, 62 + i, midy);
        line(62 + i, midy, 62 + i, midy - 15);
        floodfill(5 + i, midy + 22, YELLOW);
        setcolor(BLUE);
        setfillstyle(SOLID_FILL, DARKGRAY);
        /*  Draw Wheels */
        circle(30 + i, midy + 25, 9);
        circle(90 + i, midy + 25, 9);
        floodfill(30 + i, midy + 25, BLUE);
        floodfill(90 + i, midy + 25, BLUE);
        /* Add delay of 0.1 milli seconds */
        delay(100);
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screenshot of moving car.

MOVING_CAR

C Graphics Programming Tutorial

C Graphics Programming Tutorial

This C Graphics tutorials is for those who want to learn fundamentals of Graphics programming, without any prior knowledge of graphics. This tutorials contains lots of fundamental graphics program like drawing of various geometrical shapes(rectangle, circle eclipse etc), use of mathematical function in drawing curves, coloring an object with different colors and patterns and simple animation programs like jumping ball and moving cars. This tutorial will provide you an overview of computer graphics and it’s fundamentals.

The first step in any graphics program is to initialize the graphics drivers on the computer using initgraph method of graphics.h library.

void initgraph(int *graphicsDriver, int *graphicsMode, char *driverDirectoryPath);

It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode. It also resets or initializes all graphics settings like color, palette, current position etc, to their default values. Below is the description of input parameters of initgraph function.

  • graphicsDriver : It is a pointer to an integer specifying the graphics driver to be used. It tells the compiler that what graphics driver to use or to automatically detect the drive. In all our programs we will use DETECT macro of graphics.h library that instruct compiler for auto detection of graphics driver.
  • graphicsMode : It is a pointer to an integer that specifies the graphics mode to be used. If *graphdriver is set to DETECT, then initgraph sets *graphmode to the highest resolution available for the detected driver.
  • driverDirectoryPath : It specifies the directory path where graphics driver files (BGI files) are located. If directory path is not provided, then it will seach for driver files in current working directory directory. In all our sample graphics programs, you have to change path of BGI directory accordingly where you turbo C compiler is installed.

Colors in C Graphics Programming

There are 16 colors declared in C Graphics. We use colors to set the current drawing color, change the color of background, change the color of text, to color a closed shape etc. To specify a color, we can either use color constants like setcolor(RED), or their corresponding integer codes like setcolor(4). Below is the color code in increasing order.

COLOR MACRO INTEGER VALUE
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15

At the end of our graphics program, we have to unloads the graphics drivers and sets the screen back to text mode by calling closegraph function. Here is our first C Graphics program to draw a straight line on screen.

C Graphics Programming Tutorial

/* C graphics program to draw a line */
#include<graphics.h>
#include<conio.h>
int main() {
    int gd = DETECT, gm;
    /* initialization of graphic mode */
    initgraph(&gd, &gm, "C:\\TC\\BGI"); 
    line(100,100,200, 200);
    getch();
    closegraph();
    return 0;
}

In this program initgraph function auto detects an appropriate graphics driver and sets graphics mode maximum possible screen resolution. Then line function draws a straight line from coordinate (100, 100) to (200, 200). Then we added a call to getch function to avoid instant termination of program as it waits for user to press any key. At last, we unloads the graphics drivers and sets the screen back to text mode by calling closegraph function.

C Graphics Programs

 

Circle RECTANGLE ELLIPSE CONCIR BARGRAPH 3DBarGraph SINE_GRAPH COSINE_GRAPH TANGENT STARS PIECHART COUNTER DIGITAL_CLOCK HUT BOUNCING_BALL MOVING_CAR