ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Library Functions in C Programming Language

Updated on July 9, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with 9 years of exp in C#, Angular, React, Vue.

In this C language tutorial we will learn about library function available in C. Before I start explaining about library function let me refresh your idea about function. There are two type of function available in C, user defined functions, also know as UDF, and library functions.

A library function comes with C compiler setup program and we can directly use these function in our program by including corresponding header file. Library function contains many commonly used functions like mathematical function, string function, I/O function (to interact with display, keyboard etc). If you have written any program in C language then you must have used at least one library function. Commonly used library function is printf, scanf, clrscr, getch etc.

Whereas, UDF in C is function written by user (programmer) when there is no suitable library function available to fulfill his/her logical requirement. You can read more about User Defined Function (UDF) and its usage here.

Library function example

#include<stdio.h>
#include<conio.h>

void main()
{
	clrscr();
	printf("I am part of library function.");
	getch();
}
Library function example
Library function example

C library function example with User Defined Function (UDF)

#include<stdio.h>
#include<conio.h>

void greeting();

void main()
{
	clrscr();
	greeting();
	getch();
}

void greeting()
{
	printf("I am library function.\n");
	printf("But I am inside user defined function.");
}
Library function example
Library function example

In C, there are numerous library functions available to programmer. Here I am going to list some frequently used library function.

String functions in C (Requires “string.h”)

This header file contains all the functions related to string manipulation (or modification) like changing case of string to lower or upper, concatenating (or appending) one string to another etc. If you want to use any string library functions then you have to include “string.h”. Below is one simple example of few commonly used string library functions.

Example of string library program in C

#include "stdio.h"
#include "conio.h"
#include "string.h"

void main()
{
	char *name = "Raj Loves ";
	char *name2 = "C Program";
	int diff=0;

	clrscr();

	printf("After comparison	:");
	diff = strcmp(name, name2);
	printf("%d\n", diff);

	strcat(name, name2);
	printf("After concatenating	:");
	printf("%s\n",name);

	printf("After Upper Case	:");
	printf("%s\n",strupr(name));

	printf("After Lower Case 	:");
	printf("%s\n",strlwr(name));

	printf("After Reverse		:");
	printf("%s",strrev(name));

	getch();
}
String functions example in C
String functions example in C

Explanation of string.h library function

As you can see this is a very simple example but, from my side, I think I should explain few lines of code and we will go line by line.

We have two character pointer variables (name and name2) to store some string. These two variables contains some string value (“Raj Loves ” and “C Program”).

Code Block 13 – 15 (strcmp in C): First we will compare both string and for that we will use library function “strcmp()”. The “strcmp()” function takes two character pointer parameter (click here to know more about parameter in function) and compare both strings. If parameter values are equal then this function returns 0 else returns their difference in from of integer (see line no. 14 for usage). Variable "diff" is used for storing the comparison result and as you can see in output window screen shot both string (“name” and “name2”) are not equal so this function returned their difference i.e. 15.

Code Block 17 – 19 (strcat in C): Next we have “strcat()” function which concatenates second string in first string. You might me thinking which one is first and second string. This method have following prototype “strcat(char *dest, char * src)” and we are passing “strcat(name, name2)”. That means variable “name” is destination pointer and “name2” is source pointer. So variable “name” will contain concatenated string i.e “Raj Loves C Program”.

Code Block 21 – 22 (strupr in C): In this block we are changing case of string available in “name” variable to upper case. As a result string “Raj Loves C Program” will become “RAJ LOVES C PROGRAM”. The “strupr()” function takes string (character pointer) as parameter and returns string (character pointer) in upper case.

Code Block 24 – 25 (strlwr in C): In this block we are changing case of string to lower case. As a result string “RAJ LOVES C PROGRAM” will become “raj loves c program”. The “strlwr()” function takes string (character pointer) as parameter and returns string (character pointer) in lower case.

Code Block 27 – 28 (strrev in C): In this block we are reversing string stored in “name” variable. As a result string “raj loves c program” will become “margorp c sevol jar”. The “strrev()” function takes string (character pointer) as parameter and returns string (character pointer) in lower case.

Apart from this, there is lots of other function available in “string.h”. Don’t hesitate to explore this header file.

Math functions in C (Requires “math.h”)

This header file contains all the functions required for mathematical calculation like sin, tan, log, sqrt, ceil, floor etc. To use any of the C math functions you have to include “math.h”. I am going to show you few C math library functions in below example.

Example of math library program in C

#include "stdio.h"
#include "conio.h"
#include "math.h"

void main()
{
	float num = 9.25;

	clrscr();

	printf("Sqrt of %f	: ", num);
	printf("%f\n", sqrt(num));

	printf("Ceil of %f	: ", num);
	printf("%f\n", ceil(num));

	printf("Power of %f	: ", num);
	printf("%f\n", pow(num,num));

	getch();
}
Math functions example in C
Math functions example in C

Explanation of math.h library function

I tried to keep this program as simple as I can. In this program, I am showing you uses of sqrt(), ceil() and pow() function of math library (or “math.h”).

Code Block 11 – 12 (sqrt in C): In this block we are calculating square root of value stored in “num” float variable, i.e. 9.25. Function used to calculate square root is very simple, “sqrt()” function takes one double type parameter and returns double type value. You can see the output in above screenshot.

Code Block 14 – 15 (ceil in C): In this block we are ceiling (rounding up) value stored in “num”. Function used for this purpose is “ceil()” which takes one double type parameter and returns double type value. Similarly if you want to floor (round down) any value then you can use “floor()” function to achieve that. The “floor()” function has same prototype as “ceil()” function.

Code Block 17 – 18 (pow in C): In this last important code block we are calculating power of value stored in “num” float variable, i.e. 9.25. Function used to calculate power is “pow()” function. Unlike other two function we used in this program, “pow()” takes two double type parameter and returns one double type value (obviously ;)). I have passed same “name” variable to “pow()” function and you can see the output in screenshot.

These are few functions from “math.h” header file. I suggest you to explore other math library function in your own program to see how those functions work.

Graphics function in C (requires “graphics.h”)

I find this library one of the very interesting libraries available in C programming language. When I used to teach C language that time I have written many small application using graphics in C. And obviously I will share those programs with you in my upcoming tutorials on graphics in C.

If want to draw line, circle, rectangle etc. in C then you have to use “graphics.h” in your program. I have one sample graphics program in C where it draws one line and one circle on screen. I know it’s a bit difficult to understand this program now (trust me this is the easiest graphic progam) and in this tutorial I am not going to explain you graphics concept. I properly commented code wherever I thought it is necessary. If you still find difficulty to understand this code, don’t worry we will have different session on graphics topic. Now smile and try to go through below code slowly, I am sure you will understand something from there.

Example of graphics program in C

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main()
{
	clrscr();

	/* auto detect graphic driver */
	int gdriver = DETECT, gmode, errorcode;

	/* start graphics system */
	initgraph(&gdriver, &gmode, "G:\\TC\\BGI");

	/* check result if graphic initialization was successful */
	errorcode = graphresult();

	/* check error code for any error */
	if (errorcode != grOk)  
	{
		printf("Error: %s\n", grapherrormsg(errorcode));
		printf("Press any key to exit:");
		getch();
		exit(1);             /* return with error code */
	}

	/* draw a line */
	line(0, 0, getmaxx()/3, getmaxy()/3);
	/* draw a circle */
	circle(getmaxx()/2, getmaxy()/2, 50);
	
	getch();
	/* shut down C graphic system */
	closegraph();
	return 0;
}

Graphics in C

graphics program in C
graphics program in C

Explanation of graphics.h library function

In this example of graphics library in C, we will concentrate on line no. 29 and 31. As function name is self explanatory, “line()” function draws line and “circle()” draws circle on screen. The “line()” function takes four parameter of integer type, first two parameter is for starting point X & Y coordinates and last two parameter is for ending point X & Y coordinates. Whereas “circle()” function takes three parameter of integer type, first two parameter is for X & Y coordinates and last parameter for radius of the circle.

Don’t you think these methods are really simple and easy to use? If you don’t think so then I would suggest you to read “Bresenham's line algorithm” and then compare that with “line()” function of graphics library of C.

Having a rich library in any programming language helps programmer to write less code and C language has no exception in that. Your C language library size will differ from vendor to vendor; few may have extra functions along with standard one.

Reader's Feedback

Did this help you to learn about Library function in C Programming Language?

See results

© 2012 RAJKISHOR SAHU

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      monika 

      5 years ago

      it gives more information.thanks 4 it

    • profile image

      peterlatigo 

      6 years ago

      wrote the code but dint have the graphics.h library funtion so got compiler error, what can i do,really looks interesting, thanks.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)