Programming in C&Libraries PDF
Programming in C&Libraries PDF
1. Introduction
Example of a typical program in C
#include<stdio.h>
#include<stdlib.h> Header Files
#include<conio.h>
#define N 10 Declaration of constants
int main()
Main function {printf(“HELLO WORLD, I AM BEGINNING TO PROGRAM”);
return 0;
}
The structure of a c program
A c program has basically four parts
parts:
i. Compilation directives
ii. Declaration
eclaration of constants and global variables
iii. Function declaration and definition
iv. The main function
unction (the main program)
(a) Compilation directives
Compilation directives are names of header files given at the beginning of a c program. These header files
contain in-built functions
ions that are used in the program. They are included so as to guide the compiler on where to
find the various in-built
built functions used in the program. These are included using the syntax: #include<file.h>
e.g #include<stdio.h>,, to mean that functions of the standard input output (stdio)) file will be used. Without
mentioning any header file the compiler signals an error whenever a function from such a file is used without
redefining it.
It is practically impossible
sible to depend only on user defined functions because that will be tantamount to writing
your own compiler.
(b) Declaration of constants and global variables
Constants: immediately after the compilation directives, comes the declaration of constants, done with
the syntax: #define constant value.
value This means that the constant constant is given the value value. E.g
#define pi 3.14 defines pi as having the value 3.14. Once an identifier is defined as a constant its
content cannot be modified.
Global variables: global variables are declared just after the definition of constants. A global variable
variable,
is that variable that is not declared within any function. However,
However any function modifying it does so
permanently. That is the modifications stay even after the function has terminated execution.
Declaration of global variables is the same as the declaration of any other variable. Variable declaration
is done as follows:
Variable_typee identifier; this means the variable identifier is of type variable_type.
E.g int n means n is an integer. When two or more variables are of the same type, the type is given,
followed by a list of these variables separated by comas. E.g float a, b, c, d; meaning a, b, c and d are
floating point numbers (real numbers). Below is a summary of the simple (basic) da data types in c.
1
32,767
Short int or short Integer (coded in≤16 bits)
Integer (coded in 32 bits)) can represent integers from -
Long int or long
2,147,483,648 to 2,147,483,647
Floating point number(real numbers). They are numbers of the
Float form 1.5×108 etc. That is m×be where m is the mantissa, b the
Float base and e the exponent. Here the truncation error isis10-6
Double Double precision float
Long double error10-10
Extra high precision with truncation error
Character (coded in 1 byte i.e 8bits) all characters are considered
Char Char
in c to be integer in nature.
Note:: there exist other data types in c which are complex forms of these basic ones
(c) Function declaration/definition
In c functions are declared as follows:
Function_type function_name(parameters)
function_name(
Where:
Function_type is the type of value the function returns. If the function returns nothing we use the type
“void”
Function_name is the identifier of the function
Parameters represent the declaration of the variables used as arguments to the function. This could be
empty if function has no arguments.
Note: declaration of parameters to a function does not follow the normal variable declaration as seen
above. If the variables given
given as parameters are of the same type, they are not chained
chained-up as seen above,
rather each and every parameter has its own separate declaration.
declaration. These separate declarations are
separated by comas.
E,g int popo(int x, int y, float z). This is the only situation
uation where a declaration does not end with a
semicolon.
(d) The main program.
The main program (main function) is a function just like other functions. However, it is a function that
coordinates all other functions to work together. It is here that the order in which the functions are called is
determined. Without the main function the program does not compile at all. E.g.
Void main()
{
}
2. Input/output
The inputs and outputss in c are managed by two main functions; printf to output processing results on to the standard
output-screen and scanf to input(reading input into the system from a standard input-keyboard).
input keyboard). These are inin-built
functions taken from the standard input/output library (stdio.h).
(
i. Printf:
Syntax; printf(format,
format, list of expressions);
E.g printf(“hello world”); prints simply the chain hello world. However if we use printf(“there are %d of us”,
n); where n is a variable containing the value 10,
The output statement is there are 10 of us.us
Here we see that printf has two major types of arguments; first the chain of characters in quotes “”, followed by
the next which is a list of variables or expressions.
expressions Thee variables/expressions can be of various data types. These
types are converted to text using the various conversion codes such as %d seen above to convert integers to their
corresponding text format.
Example: printf(“mr. %s is %f meters tall”,a,b);
tall”,a,b) if a=john
ohn and b=1.75 that is a is a string and b a float then the
statement becomes: mr john is 1.75m tall.tall Below is a list of various conversion codes:
codes
Conversion code Corresponding data type
%d For integers
%c For characters
%f For double or float
%s For a chain of characters(string)
%ld For long int.
The space occupied by (size of) what you output on the standard output may also be your concern. You can limit
the space on the screen to be occupied by this output using an additional formatting of the conversion code. E.g
“%10f” means the corresponding real number will occupy 10 spaces. If we use “%10.5f” the real then occupies
10 spaces with 5 decimal places.
In using printf you can go to the next line
line at any position in your text just by using the constant “\n” in the first
argument which is the chain of characters. There exists other constants that perform various formatting effects as
summarised below.
2
S/n Notation in c Significance
1 \a Bip (audible bell)
2 \b Back space
3 \f Form feed (page down)
4 \n Line feed (going to the next line)
5 \r Carriage return
6 \t Horizontal tab (horizontal shift)
7 \v Vertical tab (vertical shift)
8 \\ \
9 \’ ’
10 \” ”
11 \? ?
ii. Scanf
Syntax scanf(“format”, address).
address E,g scanf(“%d”,&x); this simply means read an integer (specified by %d) and
place it in the address of the variable x (here specified by &x). We can equally read a set of values of
same/different formats at once.
E,g scanf(“%d %f %c”,&a,, &b &c) reads an integer, a real and a character and places them in the addresses of
a,b and c respectively.
Note:
1. To place a variable of a particular type in the address of any variable, the variable must be of the same type as
the value read.
2. All characters in C are considered as integers.
int However when using a character in place of an integer, the
value of its ASCII code is used.
3. Scan is not
3. Operations/operators
There are various operators in C, namely; assignment, arithmetic, logical and unaryunary. These four can be
classified into two. That is binary and unary operators. The binary operators combine two operands while a
unary operator acts on a single operand.
i. Assignment operator: the assignment operator is the usual equal sign e.g. A=b, means assign to A the
value in b.
ii. Arithmetic operators:
operators they are the usual mathematical operators
Operator Operation Meaning
+ C=a+b C is assigned the value generated by the addition of a and b.
- C=a-b C is assigned the value generated by a-bb (a minus b)
* C=a/b C is assigned the value generated by a/bb (a divided by b)
/ C=a*b C is assigned the value generated by a*bb (a times b)
% C=a%b
=a%b C is assigned the value generated by a%bb (a modulo b)
The priority with which operations are done follows BODMAS (Brackets, Of, Division, Multiplication, Addition
and Subtraction) the modular operation is treated with same priority like multiplication and division. E.g.
A*B+C%D(A*B)+(C%D)
N/B: the PL C is a case sensitive language. that is Aa,
A bB … etc
iii. Unary operators. As seen above they act on one operand. These are generally negation, increment and
decrement operators
Operator Operation Meaning
- -A Negate A; e.g. –A + B*C(-A)+(B*C)
Increase i by 1 after current use. E.g. If i=2,the instruction printf(i++) prints
I++
2 but after printing the value of i is 3
++
Increase i by 1 before current use. E.g. If i=2,the instruction printf(++i) prints
++i
3 and after printing the value of i is 3
I-- Decrement i by 1 after current use
-- Decrement i by 1 before current use ; the same effects are seen as in prior and
--i
post increments above.
3
== A==B A equal to B?; Trying to verify equality between A and B
> A>B A greater than B?; Trying to test whether A >B
< A<B A less than B?; Trying to test whether A <B
>= A>=B B A greater than or equal to B?; Trying to test whether A ≥B
<= A<=B B A less than or equal to B?; Trying to test whether A A≤ B
!= A!=BB A different from B?; Trying to test whether A B B
These relational operations also return true or false just like logical operations below.
vi. Logical operators: these are the basic logical operators; the AND, the OR and the NOT
Operator Operation Meaning
&& A&&B A^B i.e. A and B
|| A||B
B A or B
! !A Not(A)
4. Instructions
An instruction block in C is delimited by two braces; the left (open) and the right (closed) braces. That is begin
and end are replaced by “{” and “}”. Every instruction in C ends with a semicolon.
5. Control structures
If_then_else
if (logical condition) {
instructions; e.g. if (D<0)
} printf(“ROOTS ARE COMPLEX”);
OR OR
Example1: write a program that prints a positive integer read from the keyboard only when the number is even.
If it is odd, the word odd should be printed
Solution:
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int n; int n;
printf(“Enter a positive integer”); OR printf(“Enter a positive integer”);
scanf(“%d”, &n); scanf(“%d”, &n);
if (n%2!=0) if (n%2= = 0)
printf(“ODD”); printf(n);
else else
printf(n); printf(“ODD”);
} }
Example2: write a program to calculate the roots of a quadratic equation + + = when they are
real. When they are complex, the message “COMPLEX ROOTS” should be printed. The coefficients a,b,c
should be given by the user.
Solution:
#include<stdio.h>
#include<stdio.h> void main()
void main() {float a, b, c, D, x1, x2;
{float a, b, c, D, x1, x2; printf(“\nn Enter the coefficients a, b and c of the
printf(“\nn Enter the coefficients a, b and c of the quadratic”); quadratic”);
scanf(“%f %f %f”, &a, &b, &c); scanf(“%f”, &a); scanf(“%f”, &b); scanf(“%f”,
D=b*b-4*a*c; &c);
if(D>=0) D=b*b-4*a*c;
{ if(D>=0)
x1=(-b + sqrt(D))/(2*a); OR {
x2=(-b - sqrt(D))/(2*a); x1=(-bb + sqrt(D))/(2*a);
printf(“\nThe
nThe roots are %f and %f”, x1, x2);x x2=(-b - sqrt(D))/(2*a);
} printf(“\nThe
nThe roots are %f and %f”, x1, x2);
else printf(“\nCOMPLEX ROOTS”); }
} else printf(“\nCOMPLEX ROOTS”);
}
4
Note: when there is just one instruction after a conditional statement, there is no need for the left({ ) and right
(})braces. This
his is same for loop statements.
Exercises
1) Write a program to give the roots of the quadratic above, including complex roots when they exist.
Switch_case
When
hen we look at exercise (2) above we discover that the “if” can be used so many times. However if the choice
of a grade depended on discrete integral values, the construct switch would be used. For example: we need to
write each of the numbers 1, 2, 3 given by the user at random, in words. The
he solution is as seen below.
main()
{int n;
printf(“Give an integer”);
scanf(“%d”, &n);
switch(n)
{ case 1: printf(“One”);break;
case 2: printf(“Two”);break;
eak;
case 3: printf(“Three”); break;
}
printf(“Bye Bye”);
}
The
he expression following the switch (which is n in this case) is evaluated. If its value corresponds to any of the
etiquettes indicated after “case” e.g. 1, the instruction block following the column is executed up to “break”.
At the break instruction, the execution quits the switch block. If this break is not there the processor continues execution
with the ensuing instructions unconditionally.
Example: write a C program that reads 10 numbers from the keyboard and calculates their average.
Solution: main()
{ int i;
float Avg, n, Sum=0;
for (i=1;i<=10;i++)
{ printf(“enter
“enter number n”
n”);
scanf(“%f”, &n);
Sum=Sum + n;
}
Avg=Sum/10;
printf (“average =%f”, Avg);
Avg)
}
Exercises:
1) Write a C program to calculate the value of n! Where n≥0, bearing in mind that 0!=1 and
N!=1×2×3× …×n for n>0.
2) Write a C program that prints the multiplication table for the first ten positive integers, that is, 1 to 10. As seen
below;
5
* 1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6
4 4 8
5 5 10
AND SO ON
6 6 12
7 7 14
8 8 16
9 9 18
10 10 20
Example 2: write a C program that returns 1 if a number read from the keyboard is a prime number and 0 if it is not.
Solution
The principle is that a prime number is divisible only by itself
main() and by 1. However 1 is not a prime. We also know that a
{int n, i=2; number n cannot be divisible by any number m, where
“Enter a positive integer n”);
printf(“Enter n n 1
scanf(“%d”,&n); m so we chose m
while((n%i!=0)&&(i(n+1)/2)
(n+1)/2 )i++; 2 2
Therefore if a number n is not divisible by any number i<m (n
if(i(n+1)/2)
mod i0), then n is a prime
return 0;
else
return 1;
}
Exercises
1) With inspiration from the algorithm in the example above, write another algorithm to determine and print all the
prime numbers between 1 and 100.
2) Given the algorithm above, could the “FOR” loop be used in place of the “WHILE” loop as seen? Justify!
3) Use the while loop to calculate the sum of n numbers read at random from the keyboard.
6
4) Write an algorithm to determine the value of the nth term (n given from the keyboard) of the Fibonacci
series;
Un=Un-1+Un-2, n>2
With U1 =U2=1
main()
{int A, B, C, i=0;
printf(“Enter A and B”);
C=0;
scanf(“%d %d”, &A, &B);
do
{C=C+A;
i++;
}
while (i<B);
printf(“the product of %d*%d=%d”,
%d A, B, C );
}
b) Recursive functions
A recursive algorithm/function is an algorithm/function
algorithm that calls itself within its own definition. For example the
Fibonacci series defined above is recursive. Instead of giving us the nth term Un in terms of n we are instead asked
to look for Un-1 and Un-2 whose definitions will still be in the same manner.
Example
Write a recursive function for n! Defined mathematically as n!=n×(n-1)!,where where n>0,n, with 0!=1
Solution
int facto(int n)
Here, the test “if(n<0)” is to take care of negative integers, if ever the user
{ does gives n<0. Also notice that the instruction “return n*facto(n-1);”
if( n<0) return -1; representing n*(n-1)!, is written without any ““else”. This is because it is
else if(n=0) return 1; coming just after a return statement. At any return instruction, control is
return n*facto(n-1); returned to the main program (program that called the current one).
} Therefore the statement “return n*facto(n-1);” 1);” can only be executed if the
statement “ return 1;” is not executed that is if n 0.
Exercises
1) Write a recursive C function to calculate the nth term of the Fibonacci series.
2) Write a recursive C function to compute the HCF of two positive integers a and b with the following
definition of HCF.
a,b 0
H C F ( a , b ) H C F ( a b , b ), a b
H C F ( b a , a ), a b
(c) Strings
A string which is a chain of characters (e.g. A word in ordinary language) is considered a simple data type
and at same time it can be considered a data structure. Ass a simple data type it can be read and written as
one variable when this has to do with the whole chain. However
owever if only parts of the chain are considered,
we need to treat this chain as a 1-dim
1 dim array of characters hence making it a data structure.
Declaration syntax
There are two ways to declare a string; either as a pointer or as an array.
As a pointer we use char * var_name. E.g. Char *p; declares p as a chain of characters. Here there is
no limit to the number of characters the chain can take (no limit in length).
As an array we use char var_name[dim]. Where dim is the maximum number of characters the chain
var_name can take. E.g. Char p[50]; declares p as a chain of 50 characters.
Access of element
The variable p as declared can be treated either as a single variable or as an array of characters. If we
want to manipulate p character by character we use it as an array of characters.
I/o operations
Input: to get p into memory from the key board we can use either scanf(“%s”,
canf(“%s”, &p) or gets(p) the
major difference between these two is input methods is that scanf reads the string but does not
consume the end of line character-“/0”.
character This becomes an inconvenience when reading the next string,
as the previous end of line is first read in place of the current string. The resultant values stored in
memory become faulty.
Output: we either use printf(“%s”, p) or puts(p).
(d) Records
A record is a grouping (collection) of related fields (attributes) describing an entity
Declaration
eclaration syntax
In C a record is known as a structure. It is therefore as follows:
struct struct_type_name {type_field1 var1; struct struct_type_name {type_field1 var1;
type_field2 var2; type_field2 var2;
…. OR ….
}; } var_name;
A B
Where struct_type_name = type name given to the structure.
Type_fieldi = type given to ith field.
Vari = variable name for field i or simply field name.
Var_name=thethe name of the variable containing the structure
Note: When declared as in A, the containing variables of the structure can later be declared as
ct struct_type_name var_name;. However if declared as in B, there is no need for this second
Struct
declaration.
Access of element
To access any field of the record we use the field selector “dot” (.). For example a structure for a point in
the Cartesian plane can be declared as follows:
To have
ve access to the x-coordinate
x of the point P we use P.x and P.y for the yy-coordinate.
I/o operations
To read into the x and y coordinates of the point P above we can use scanf(“%f %f”, &P.x,
& &P.y).
When a record is already populated we can assign a record to another record just like we do with simple
data types. For example; if Q is also of type “struct point”, then we can do an assignment such as P=Q;
9
however the manipulation of elements of the records must be done field after field. E.g. To calculate the
. .
gradient between P and Q given by We can use . . I.e. (Q.y-P.y)/(Q.x
P.y)/(Q.x-P.x)
(e) Arrays of records
This is a 1-dim array whose elements are records.
Declaration syntax
The declaration is same as that of arrays but the data type concerned is that of a record.
E.g. Struct point T[10]
T[10]; this declares an array of 10 elements of type struct point.
point
Access of element.
T[i] in this case becomes a reference to the ith record. The x and y coordinates of the ith point will be
referenced by T[i].x and T[i].y.
I/o operations
Input/output operations are same as in other records when considering individual records.
Example
Write a C program that reads the coordinates of ten points (points declared in advance)
advance), puts each
coordinate pair in an array record and then prints
print the pairs each in a line.
Solution
#include<stdio.h>
#include<conio.h>
#define N 10
struct point {float x;
float y;
};
struct point p[N];
void main()
{ int i;
for (i=1; i<10;i++)
{
printf(“enter x coordinate”);
scanf(“%f”, &t[i].x);
printf(“enter y coordinate”);
scanf(“%f”, &t[i].y);
].y);
}
for (i=1; i<10;i++)
printf(“ (%f,%f)”, t[i].x, t[i].y);
getch() ;
}
Project 1
Your teacher is not versed with techniques of high level computing. However he can learn how to use various
software. His needs are as follows:
Register students for his subject
Register marks against the registered students
Rank student in order of merit
Calculate class average mark for his subject
Using the information given above, write a C program to help your teacher do all these. Your program should be
able to allow the teacher do things by choice.
10
Dynamic data structures
1. Head insertion
q
info next
2. Middle insertion
q
info nex
t
info next
q
info next info next info
p q
11
MAJOR BUILT IN FUNCTIONS AND THEIR LIBRARIES
Class
FUNCTION
of Meaning/return values
synopsis
functions
<stdio.h> header
The pathname argument is the name of the file to open,
such as that returned from tmpnam, or some program-
specific filename. Files can be opened in a variety of
modes, such as read mode for reading data, write mode
FILE *fopen(const char
for writing data, and so on. Note that if you only want
*pathname, const char
to write data to a file, fopen will create the file if it does
*mode);
not already exist, or truncate it to zero length (losing its
previous contents) if it did exist. The Standard list of
File Handling modes is shown in Table 9.3, although implementations
may permit extra modes by appending extra characters
at the end of the modes.
Any unwritten data buffered for stream is flushed out
and any unread data is thrown away. If a buffer had
int fclose(FILE *stream); been automatically allocated for the stream, it is freed.
The file is then closed. Zero is returned on success, EOF if
any error occurs.
int fprintf(FILE *stream, General formatted output as described. Output is written
const char *format, ...); to the file indicated by stream.
int printf(const char *format, Printf is Identical to fprintf with a first argument equal
...); to stdout.
Sprintf is Identical to fprintf except that the output is
int sprintf(char *s, const char
*format, ...); not written to a file, but
written into the character array pointed to by s.
Fscanf takes its input from the designated stream, scanf
12
error indicator is set for the associated stream.
Successive calls will obtain characters
chara sequentially. The
functions, if implemented as macros, may evaluate their
stream argument more than once, so do not use side
effects here.
There is also the supporting ungetc routine, which is used
to push back a character on to a stream, causing it to
become the next character to be read. This is not an
output operation and can never cause the external
contents of a file to be changed. A fflush, fseek, or rewind
operation on the stream between the pushback and the
read will cause the pushback to be forgotten.
f Only one
character of pushback is guaranteed, and attempts to
pushback EOF are ignored. In every case, pushing back a
number of characters then reading or discarding them
leaves the file position indicator unchanged. The file
position indicator iss decremented by every successful call
to ungetc for a binary stream, but unspecified for a text
stream, or a binary stream which is positioned at the
beginning of the file.
int fputc(int c, FILE These are identical in description to the input functions
*stream); already described, except performing output. They
int putc(int c, FILE return the character written, or EOF on error. There is
*stream); no equivalent to End of File for an output file.
int putchar(int c);
13
for an implementation-de_nedde_ned set of characters which do
not return true results from any of iscntrl, isdigit,
Ispunct or isspace. In the C locale, this extra set of
characters is empty.
isprint(int c) True if c is a printing character (including space)
True if c is any printing character that is neither a space
ispunct(int c)
nor a character which would return true from isalnum
True if c is either a white space character (one of ' ' ,
'\f','\n', '\r', '\t','\v')
isspace(int c)
or, in other than the C locale, characters which would
not return true from isalnum
Tolower(char c) if given a upper case character, will return the lower
case equivalent. For example: tolower('A') == 'a'
Toupper( char c) Does the revers conversion of tolower
<string.h> header
Handling This copies n bytes from the place pointed to by s2 to the
void *memcpy(void *s1, const
of place pointed to by s1. If the objects overlap, the result is
void *s2, size_t n);
strings undefined. The value of s1 is returned.
void *memmove (void *s1, Identical to memcpy, but works even for overlapping
const void *s2, size_t n); objects. It may be marginally slower, though.
char *strcpy(char *s1, const copies the string pointed to by s2 into the string pointed
char *s2); to by s1, including the trailing null.
Strncpy will copy at most n characters, and pad with
char *strncpy(char *s1, const
trailing nulls if s2 is shorter than n characters. If the
char *s2, size_t n);
strings overlap, the behaviour is undefined. It returns s1.
Strcat appends the string in s2 to s1, overwriting the null
char *strcat(char *s1, const
at the end of s1. A final null is always written. It ret
return
char *s2);
s1
At most n characters are copied from s2 and appended
to s1 by strncat, which means that for safety the
char *strncat(char *s1, const
destination string should have room for its original
char *s2, size_t n);
length (not counting the null) plus (n ( + 1) characters. It
return s1
Compares the first n characters in the objects pointed to
int memcmp(const void *s1, by s1 and s2 . It is very dodgy to compare structures in
const void *s2, size_t n); this way, because unions or 'holes' caused by alignment
padding can contain junk.
Compares the two strings. This is one of the most
int strcmp(const char *s1,
commonly used of the string-handling
string functions.(
const char *s2);
Returns n=0 if s1=s2, n>0 if s1>s2, n<0 if s1<s2)
int strncmp(const char *s1, As for strcmp, but compares at most n characters.
const char *s2, size_t n);
The string in from is converted (by some magic), and
placed wher-ever
ever to points. At most maxsize characters
(including the trailing null) are written into the
destination. The magic guarantees that two such
transformed strings will give the same comparison with
each other for the user's current locale when using
size_t strxfrm(char *to, const
strcmp, as when strcoll is applied to the original two
char *from,
strings.
In all cases, the length of the resulting string (not
counting its termi-nating
nating null) is returned. If the value is
equal to or greater than maxsize, the contents of *to is
undefined. If maxsize is zero, si may be a null pointer. If
the two objects overlap, the behaviour is undefined.
int strcoll(const char *s1, const This function compares the two strings according to the
char *s2); collating
llating sequence specified by the current locale.
void *memchr(const void *s, Returns a pointer to the first occurrence in the initial n
int c, size_t n); characters of *s of the (unsigned char)c. Returns null if
14
there is no such occur-rence.
rence.
Returns a pointer to the first occurrence of (char)c in *s,
char *strchr(const
strchr(const char *s, int
including the null in the search. Returns null if there is
c);
no such occurrence.
Returns the length of the initial part of the string si
size_t strcspn(const char *s1,
which contains no characters from s2. The terminating
const char *s2);
null is not considered to be part of s2.
char *strpbrk(const char *s1, Returns a pointer to the first character in si which is
const char *s2); any of the characters in s2, or null if there is none.
char *strrchr(const char *s, Returns a pointer to the last occurrence in si of (char)c
int c); counting the null as part of si, or null if there is none.
size_t strspn(const char *s1, Returns the length of the initial part of s1 consisting
const char *s2); entirely of characters from s1.
char *strstr(const char *s1, Returns a pointer to the first occurrence in s1 of the
const char *s2); string s2, or null if there is none.
Breaks the string in s1 into 'tokens', each delimited by
one of the characters from s2 and returns a pointer to
char *strtok(const char *s1, the first token, or null if there is none. Subsequent calls
const char *s2); with (char *)0 as the value of s1 return the next token in
sequence, with the extra fun that s2 (and hence the
delimiters) may differ on each subsequent call. A null
pointer is returned if no tokens remain.
<math.h> header
Principal value of the arc cosine of x in the range 00-
double acos(double x); _radians. Errors:EDOM
if x is not in the range -1-1.
Principal value of the arc sine of x in the range -_/2-+_/2
double asin(double x); radians. Errors:EDOM
if x is not in the range-1-1.
Principal value of the arc tangent of x in the range -_/2-
double atan(double
(double x);
+_/2 radians.
Principal value of the arc tangent of y/x in the range -_-
double atan2(double y, double
+_radians, using the signs of both arguments to
x);
determine the quadrant of the return value. Errors:
EDOM may occur if both x and y are zero.
double cos(double x); Cosine of x (x measured in radians).
double sin(double x); Sine of x (x measured in radians).
Tangent of x (x measured in radians). When a range
double tan(double x); error occurs, the sign of the resulting HUGE VAL is not
guaranteed to be correct.
Hyperbolic cosine of x.Errors: ERANGE occurs if the
double cosh(double x);
magnitude of x is too large.
Mathematical
Hyperbolic sine of x. Errors: ERANGE occurs if the
functions double sinh(double
uble x);
magnitude of x is too large.
double tanh(double x); Hyperbolic tangent of x.
Exponential function of x. Errors: ERANGE occurs if the
double exp(double x);
magnitude of x is too large.
Break a floating point number into a normalized
double frexp(double value, int
fraction and an integral power of two. This integer is
*exp);
stored in the object pointed to by exp.
double ldexp(double x, int Multiply x by 2 to the power exp. Errors:ERANGE
Errors may
exp); occur.
Natural logarithm of x. Errors: EDOM occurs if x is
double log(double x);
negative. ERANGE may occur if x is zero.
Base-ten
ten logarithm of x. Errors: EDOM occurs if x is
double log10(double x);
negative. ERANGE may occur if x is zero.
Break the argument value into integral and fractional
double modf(double value,
parts, each of which has the same sign as the argument.
double *iptr);
It stores the integrbal part as a double in the object
15
pointed to by iptr, and returns the fractional part.
p
Compute x to the power y.
double pow(double x, double
Errors: EDOM occurs if x < 0 and y not integral, or if the
y);
result cannot be represented if x is 0, and y_0.
ERANGE may also occur.
Compute the square root of x.
double sqrt(double x);
Errors: EDOM occurs if x is negative.
double floor(double x); Largest integer not greater than x.
double ceil(double x); Smallest integer not less than x.
double fabs(double x); Absolute value of x.
double fmod(double x, double Floating point remainder of x/y.
y); Errors: If y is zero, it is implementation defined whether
fmod returns zero or a domain error occurs.
<stdlib.h> header
For each of the functions, the number is converted and
Double atof(const char the result returned. None of them guarantees to set
*nptr); errno (although they may do in some imim-plementations),
long atol(const char *nptr); and the results of a conversion which overflows or
int atoi(const char *nptr); cannot be represented is undefined. More sophisticated
so
functions are:
Rand returns a pseudo-random
random number in the range 0 to
Int rand (void);
RANDJMAX, which has a value of at least 32767.
Srand allows a given starting point in the sequence to be
chosen according to the value of seed. If srand is not
called before rand, the value of the seed is taken to be 1.
void srand(unsigned int seed); The same sequence of values will always be returned
from rand for a given value of seed. The Standard
describes an algorithm which may be used to implement
rand and srand. In practice, most implementations will
probably use this algorithm.
These are all memory allocation functions that each
return a pointer to allocated storage of size t_size
t_ bytes.
If there is no free storage, they return a null pointer. The
differences between them are that calloc takes an
argument nmemb which specifies the number of elements
in an array, each of whose members is size bytes, and so
allocates a larger piece of store (in general) than malloc.
Also, the store allocated by malloc is not initialized,
whereas calloc sets all bits in the storage to zero. This is
not necessarily the equivalent representation of floating-
floating
void *malloc(size_t_size);
void *calloc(size_t nmemb, point zero, or the null pointer.
size_t_size); Realloc is used to change the size of the thing pointed to
void *realloc(void
alloc(void *ptr, size_t by ptr, which may require some copying to be done and
size); the old storage freed. The contents of the object pointed
void *free(void *ptr);
to by ptr is unchanged up to the smaller of the old and
the new sizes. If ptr is null, the behaviour is identical to
malloc with the appropriate size.
Free is used to free space previously obtained with one of
the allocation routines. It is permissible to give free a
null pointer as the argument, in which case nothing is
done. If an attempt is made to fr
free store which was
never allocated, or has already been freed, the behaviour
is undefined. In many environments this causes an
addressing exception which aborts the program, but this
is not a reliable indicator.
16
Causes abnormal program termination to occur, by
raising the SIGABRT signal. Abnormal termination is
only prevented if the signal is being caught, and the
void abort(void); signal handler does not return. Otherwise, output files
may be flushed and temporary files may be removed
re
according to implementation definition, and an
'unsuccessful termination' status returned to the host
environment. This function cannot return.
atexit The argument func becomes a function to be
called, without argu-ments,
ments, when the program
int atexit(void (*func)(void)); terminates. Up to at least 32 such functions may be
registered, and are called on program termination in
reverse order of their registration. Zero is returned for
success, non-zero
zero for failure.
exit Normal program termination occurs when this is
called. First, all of the functions registered using atexit
are called, but beware-by by now, main is considered to
have returned and no objects with automatic storage
duration may safely be used. Then, all the o open output
streams are flushed, then closed, and all temporary files
created by tmpfile are removed. Finally, the program
void exit(int status);
returns control to the host environment, returning an
implementation-defined
defined form of successful or
unsuccessful termination status depending
dep on whether
the argument to exit was EXITSUCCESS or EXIT
FAILURE respectively. For compatibility with Old C,
zero can be used in place of EXITSUCCESS, but other
implementation-defined effects. Exit cannot
values have implementation
return.
The implementation-defined
defined environment list is searched
to find an item which corresponds to the string pointed
to by name. A pointer to the item is returned-it
returned points to
char *getenv(const char
an array which must not be modified by the program,
*name);
but may be overwritten by a subsequent call to getenv.
A null pointer is returned
rned if no item matches. The
purpose and implementation of the environment list
depends on the host environment.
An implementation-defined
defined command processor is passed
the string string. A null pointer will cause a return of
int system(const char *string); zero if no command proces-sor
sor exists, non
non-zero otherwise.
A non-null
null pointer causes the command to be processed.
The effect of the command and the value returned are
implementation defined.
These return the absolute value of their argument-choose
argument
the appropriate
ate one for your needs. The behaviour is
Int abs(int j);
undefined if the value cannot be represented-this
represented can
Long labs(long j);
happen in two's complement systems where the most
negative number has no positive equivalent.
These divide the numerator by the denominator and
div_t div(int numerator, return a struc-ture
ture of the indicated type. In each case the
int denominator);
structure will contain a member called quot which
ldiv_t ldiv(long numerator,
long denominator); contains the
he quotient of the division trun-cated
trun towards
zero, and a member called rem which will contain the
remainder. The type of each member is int for div and
17
long for ldiv. Provided that the result could be
represented, quot*denominator+rem == numerator.
<time.h> header
These functions deal with either 'elapsed' or 'calendar' time. They share the <time.h>
header, which declares the functions as necessary and also the following:
CLOCKS_PER_SEC This is the number of 'ticks' per second returned by the clock function.
clock_t These are arithmetic types used to represent different forms of time. struct tm This
structure is used to hold the values representing a calendar time. It contains the following
members, with the meanings as shown.
Int tm_sec seconds after minute [0-61]
61] (61 allows for 2 leap-seconds)
Int tm_min minutes after hour [0-59]
Int tm_hour hours after midnight [0-23]
Int tm_mday day of the month [1-31]
Int tm_mon month of year [0-11]
Int tm_year current year-1900
Int tm_wday days since Sunday [0-6]
Int tm_yday days since January 1st [0-365]
365]
Int tm_isdst daylight savings indicator
The tm_isdst member is positive if daylight savings time is in effect, zero if not
and negative if that information is not available. The time manipulation
functions are the following:
clock Returns the best available approximation to the
time used by the current invocation of the program, in
'ticks'. (clock_t)-i is returned if no value is available. To
find the actual time used by a run of a program, it is
clock_t clock(void); necessary to find the difference between the value at the
start of the run and the time of interest-there
interest is an
implementation-defined
defined constant factor which biases
biase the
value returned from clock. To determine the time in
seconds, the value returned should be divided by
CLOCKS_PER_SEC.
The functions asctime, ctime, gmtime, localtime, and strftime all share static data
structures, either of type struct tm or char [],, and calls to one of them may overwrite the
data stored by a previous call to one of the others. If this is likely to cause problems, their
users should take care to copy any values needed.
double difftime(time_t time1, difftime This returns the difference in seconds
time_t time2); between two calendar times.
mktime This returns the calendar time corresponding to
the values in a struc-ture
ture pointed to by timeptr, or
(time_t)-1 if the value cannot be rep-resented.
rep
The tm_wday and tm_yday members of the structure
time_t mktime(struct tm
are ignored, the other members are not restricted to
*timeptr);
their usual values. On successful conversion, the
members of the structure are all set to appropriate
values within their normal ranges. This function is
useful to find out what value of a time_t corresponds to
a known date and time.
time Returns the best approximation to the current
time_t time(time_t *timer);
calendar time in an un-specified
specified encoding. (time_t)-1 is
returned if the time is not available.
asctime Converts the time in the structure pointed to by
char *asctime(const struct tm
timeptr into a string of the form Sun Sep 16 01:03:52
*timeptr);
1973\n\0
18
the example being taken from the Standard. The
Standard defines the algorithm used, but the important
point to notice is that all the fields within that string are
of constant width and relevant to most English-speaking
English
communities. The string is stored in a static structure
which may be overwritten by a subsequent call to one of
the other time-manipulation
manipulation functions (see above).
char *ctime(const time_t ctime Equivalent to asctime(localtime(timer)). See
*timer); asctime for the return value.
gmtime Returns a pointer to a struct tm set to represent
the calendar time pointed to by timer. The time is
struct tm *gmtime(const
time(const
expressed in terms of Coor
Coor-dinated Universal Time
time_t *timer);
(UTC) (formerly Greenwich Mean Time). A null pointer
is returned if UTC is not available.
localtime Converts the time pointed to by timer into local
struct tm *localtime(const
time and puts the results into a struct tm, returning a
time_t *timer);
pointer to that structure.
strftime Fills the character array pointed to by s with at
most maxsize characters. The format string is used to
size_t strftime(char *s, size_t format the time represented in the structure pointed to
maxsize, timeptr. Characters in the format string (including the
const char *format,const terminating null) are copied unchanged into the array,
struct tm *timeptr);
unless one of the following format directives is found-
found
then the value specified
pecified below is copied into the
destination, as appropriate to the locale.
19