Raid the Library!

22.04.2016 |

Episode #9 of the course Getting started with C programming by Sudeshna Das

 

Hey there!

Yesterday’s lesson was all about functions. Today, we are going to look at some important pre-defined functions like printf() that will really come in handy for your programs.

Remember I told you that we need to include stdio.h if we want to use printf()? Well, it is quite the same for other pre-defined functions too. For the next pre-defined function, we will need to include math.h.

 

#include<stdio.h>
#include<math.h>
void main()
{
int num = 25;
int result;
result = sqrt(num);
printf(“%i”,result);
}

http://codepad.org/EKkuGvev

 

The pre-defined function here is sqrt(). The sqrt() finds out the square root of a number. We have to indicate the number whose square root we want to find within the round brackets.

Another common pre-defined function is pow().

 

#include<stdio.h>
#include<math.h>
void main()
{
int num = 10, power = 2;
int result;
result = pow(num, power);
printf(“%i”,result);
}

http://codepad.org/5je45P5U

 

pow() finds out the result of a number raised to a given power. The number we use as a base is to be written first, followed by the power to which we want to raise it.

For working with strings, we need to include string.h at the beginning of our program.

 

#include<stdio.h>
#include<string.h>
void main()
{
char word[5]={‘h’,’a’,’p’,’p’,’y’};
int result;
result = strlen(word);
printf(“%i”, result);
}

http://codepad.org/yHCGc8W6

 

strlen() finds out the length of the string, which is the number of characters or alphabets in the string. In the above example, it might seem obvious that the length of the string is 5, because we have taken a character array of size 5. However, it is useful when you are working with a large character array that is storing a string of any size that is less than the array size.

 

#include<stdio.h>
#include<string.h>
void main()
{
char word[10]={‘h’,’a’,’p’,’p’,’y’};
int result;
result = strlen(word);
printf(“%i”, result);
}

http://codepad.org/zZSrlqvn

 

There are hundreds of pre-defined functions in C language that will aid you in simplifying the way you code. You don’t have to reinvent the wheel—just use it. Some other .h files of interest to you are math.h and stdlib.h.

 

Recommended book

“C Pocket Reference” by Peter Prinz

 

Share with friends