These functions are already defined in the system libraries. So you
do not need to code anything, you just need to know in which library it
is, what it does and when to use it. Just like a regular written
function, predefined functions have a name, datatype parameter and a
return type. A good example of a predefined function is the
printf()
. The parameter for the printf()
is a
string and the return type is “void” (but it is omitted) and it is found
in the <stdio.h>
library.
Here are some more fun library functions:
A library full of functions for perfoming input and output.
#include <stdio.h>
int main(void)
{
int a;
("Please enter the number 1: ");
printf("%d", &a);
scanf
return 0;
}
This code will display, if the user has enter the number 1 as requested:
Please enter the number 1: 1
A library with general functions such as:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int x = abs(-10);
("The absolute value of -10 = %d\n", x);
printf
// seeds the random number generator with the current time
(time(NULL));
srand
// generates a number between 1 and 100
int y = 1+rand()%100;
("The random number is %d\n", y);
printf
("Bye now!\n")
printf
(0);
exit
("End of the program\n");
printf
return 0;
}
This code will display:
The absolute value of -10 = 10
The random number is ~integer~
Bye now!
An assort of mathematical functions. To use them, you must include
<math.h>
. Some of the most used ones are:
Let’s see it how it works in code:
#include <stdio.h>
#include <math.h>
int main(void)
{
int a = -3;
int b = fabs(a);
("The absolute value of %d is %lf\n", a, b);
printf
// you can also use it inside printf with the appropriate formatter
("The value of 2.0 ^ 3 = %lf\n", pow(2, 3));
printf
int c = 25;
("The square root of %d is %lf\n", c, sqrt(c));
printf
return 0;
}
This code will display:
The absolute value of -3 is 3.000000
The value of 2.0 ^ 3 = 8.000000
The square root of 25.000000 is 5.000000
You can find more functions from this library here!
A library with functions regarding dates and time.
The one we use the most is the time(NULL)
, which returns
the time since the January 1, 1970 (the Epoch), measured in seconds.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
time_t seconds;
= time(NULL);
seconds ("Hours since January 1, 1970 = %ld\n", seconds/3600);
printf
return 0;
}
This code will display:
Hours since January 1, 1970 = 457100
This library has functions for mapping characters.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int a = 'd';
int b = '2';
if(isalpha(a))
{
("|%c| is an alphabetic character\n", a);
printf} else
{
("|%c| is not an alphabetic character\n", a);
printf}
if(isalpha(b))
{
("|%c| is an alphabetic character\n", b);
printf} else
{
("|%c| is not an alphabetic character\n", b);
printf}
char c = 'D';
("%c\n", tolower(c));
printf= 'e';
c ("%c\n", toupper(c));
printf
return 0;
}
This code will display:
|d| is an alphabetic character
|2| is not an alphabetic character
d
E