Some C Predefined Functions

C Tutorials from Roots - Part 23

Chrys Forcha
Introduction
This is part 23 of my series, C Tutorials from Roots. In this part of the series, we look at what is known as the rand function and the atoi function. The rand function is used to generate a random number. The atoi function is used to convert a string to an integer. In this part of the series, we look at some C predefined functions.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

The rand Function
The rand function returns a random integer from zero to 32767 everything being equal. You need to include the stdlib.h header file in order to use the rand function. Read and try the following code:

#include

int main()
{
int myRandom = rand();

printf("%i", myRandom);

return 0;
}

The atoi Function
The atoi function converts a string (whole number) to an integer. That is it takes a datum in the form of a string and returns another datum in the form of an int. The function needs to have the stdlib.h header file included. Read and try the following code.

#include

int main()
{
char *myChar = "257";
int myInt = atoi(myChar);

printf("%i", myInt);

return 0;
}

In the above two code samples, the stdio.h header is for the printf function.

Many functions belong to libraries and in order for me to explain them I have to explain many other things. I do not want this basic tutorial to be very long, so I end here. I may just add a few more pre-defined functions to this tutorial, later. We continue in the next part of the series.

Chrys

Published by Chrys Forcha

I have more than 10 years experience in computer programming, software, electronics and telecommunications. I have a First Degree in Electronics and a Master's Degree in Technical Education. As well a...  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.