Module 4. Functions

Lesson 14

FUNCTIONS IN ‘C’ – PART II

(Library Functions and Recursion)

14.1  Library Functions

A function, which is predefined in ‘C’ is known as library function, e.g., printf, scanf, getch, etc., are library functions. Mind it carefully that appropriate header files must be included in the programme for using the library functions. A list of various library functions vis-เ-vis header files (adopted from Gottfried, 1998) is given in Table-14.1 below.

Example 1: Modified programme (using inbuilt library functions) for Example-2 of Lesson-9 to compute real roots of a quadratic equation (See Example-2 of Lesson-2 for pseudo code and flowchart; and Example-2 of Lesson-9 for simple programme for this problem).

#include <stdio.h>

#include <math.h>

int main()

{

   float a,b,c,d, x_1, x_2;

   printf(“Enter a, b and c: “);

   scanf(“%f %f %f”, &a, &b, &c);

   d=sqrt(pow(b,2)-4ืaืc); //inbuilt functions used

   x_1=(-b+d)/(2*a); 

   x_2=(-b-d)/(2*a);

   printf(“a, b, c, x_1, x_2: %5.2f, %5.2f, %5.2f,  
          %5.2f,%5.2f",a, b, c, x_1, x_2);

   return 0;

}

Test Output:
Enter a, b and c: 2 3 1
a, b, c, x_1, x_2:  2.00,  3.00,  1.00, -0.50,-1.00
Table 14.1 ‘C’ Library functions vis-เ-vis header files

Function

Type

Purpose

Header File

abs(i)

int

Returns the absolute value of i.

stdlib.h

acos(d)

double

Returns the arc cosine of d.

math.h

asin(d)

double

Returns the arc sine of d.

math.h

atan(d)

double

Returns the arc tangent of d.

math.h

atan2(d1,d2)

double

Returns the arc tangent of d1/d2.

math.h

atof(s)

double

Converts string s to a double-precision quantity.

stdlib.h

atoi(s)

int

Converts string s to an integer.

stdlib.h

atol(s)

long

Converts string s to a long integer.

stdlib.h

calloc(u1,u2)

void*

Allocates memory for an array having u1elements, each of length u2 bytes. Returns a pointer to the beginning of the allocated space.

malloc.h, or stdlib.h

ceil(d)

double

Returns a value rounded up to the next higher integer.

math.h

cos(d)

double

Returns the cosine of d.

math.h

cosh(d)

double

Returns the hyperbolic cosine of d.

math.h

difftime(l1, l2)

double

Returns the time difference l1 – l2, where l1 and l2 represent elapsed times beyond a designated base time (see the time function).

time.h

exit(u)

void

Closes all files and buffers, and terminate the programme. (Value of u is assigned by function, to indicate termination status).

stdlib.h

exp(d)

double

Raises e to the power d (e= 2.7182818… is the base of the natural (Naperian) system of logarithms).

math.h

fabs(d)

double

Returns the absolute value of d.

math.h

fclose(f)

double

Closes file f. Returns 0 if file is successfully closed.

stdio.h

feof(f)

int

Determines if an end-of-file condition has been reached. If so, returns a nonzero value; otherwise, returns 0.

stdio.h

fgetc(f)

int

Enters a single character from file f.

stdio.h

fgets(s, i,f)

char*

Enters string s, containing i characters, from file f.

stdio.h

floor(d)

double

Returns a value rounded down to the next lower integer.

math.h

fmod(d1,d2)

double

Returns the remainder of d1/d2 (with same sign as d1).

math.h

fopen(s1,se)

file*

Opens a file named s1 of type s2. Returns a pointer to the file.

stdio.h

fprintf(f,…)

int

Sends data items to file f (remaining arguments are complicated

stdio.h

fputc(c,f)

int

Sends a single character to file f.

stdio.h

fputs(s,f)

int

Sends string s to file f.

stdio.h

fread (s,i1,i2,f)

int

Enters i2 data items, each of size i1 bytes, from file f to string s.

stdio.h

free(p)

void

Frees a block of allocated memory whose beginning is indicated by p.

malloc.h, or stdlib.h

fscanf(f,…)

int

Enters data items from file f (remaining arguments are complicated.

stdio.h

fseek(f,l,i)

int

Moves the pointer for f a distance 1 bytes from location i (i may represent the beginning of the file, the current pointer position, or the end of the file).

stdio.h

ftell(f)

long int

Returns the current pointer position within file f.

stdio.h

fwrite(s, i1,i2,f)

int

Sends i2 data items, each of size i1 bytes, from string s to file f.

stdio.h

getc(f)

int

Enters a single character from file f.

stdio.h

getchar()

int

Enters a single character from the standard input device.

stdio.h

gets(s)

char*

Enters string s from the standard input device.

stdio.h

isalnum(c)

int

Determines if argument is alphanumeric. Returns a nonzero value if true; 0 otherwise.

ctype.h

isalpha(c)

int

Determines if argument is alphabetic. Returns a nonzero value if true; 0 otherwise.

ctype.h

isascii (c)

int

Determines if argument is an ASCII character.  Returns a nonzero value if true; 0 otherwise.

ctype.h

iscntrl(c)

int

Determines if argument is ASCII control character. Returns a nonzero value if true; 0 otherwise.

ctype.h

isdigit(c)

int

Determines if argument is decimal digit. Returns a nonzero value if true; 0 otherwise.

ctype.h

isgraph(c)

int

Determines if argument is graphic ASCII character (hex 0x21-0x7e; octal 041-176). Returns a nonzero value if true; 0 otherwise.

ctype.h

islower(c)

int

Determines if argument is lowercase. Returns a nonzero value if true; 0 otherwise.

ctype.h

isodigit(c)

int

Determines if argument is an octal digit. Returns a nonzero value if true; 0 otherwise.

ctype.h

isprint(c)

int

Determines if argument is printing ASCII character (hex 0x20-0x7e; octal 040-176). Returns a nonzero value if true; 0 otherwise.

ctype.h

ispunct(c)

int

Determines if argument is a punctuation character. Returns a nonzero value if true; 0 otherwise.

ctype.h

isspace(c)

int

Determines if argument is white space character. Returns a nonzero value if true; 0 otherwise.

ctype.h

isupper(c)

int

Determines if argument is uppercase. Returns a nonzero value if true; 0 otherwise.

ctype.h

isxdigit(c)

int

Determines if argument is a hexadecimal digit. Returns a nonzero value if true; 0 otherwise.

ctype.h

labs(l)

long int

Returns the absolute value of 1.

math.h

log(d)

double

Returns the natural logarithm of d.

math.h

log10(d)

double

Returns the logarithm (base 10 of d.)

math.h

malloc(u)

void*

Allocates u bytes of memory. Returns a pointer to the beginning of the allocated space.

malloc.h, or stdlib.h

pow(d1,d2)

double

Returns d1 raised to the d2 power.

math.h

printf(…)

int

Sends data items to the standard output device (arguments are complicated).

stdio.h

putc(c,f)

int

Sends a single character to file f.

stdio.h

putchar(c)

int

Sends a single character to the standard output device.

stdio.h

puts(s)

int

Sends string s to the standard output device.

stdlib.h

rand()

int

Returns a random positive integer.

stdio.h

rewind(f)

void

Moves the pointer to the beginning of file f.

stdio.h

scanf(…)

int

Enters data items from the standard input device (arguments are complicated)

stdio.h

sin(d)

double

Returns the sine of d.

math.h

sinh(d)

double

Returns the hyperbolic sine of d.

math.h

sqrt(d)

double

Returns the square root of d.

math.h

srand(u)

void

Initialises the random number generator.

stdlib.h

strcmp(s1,s2)

int

Compares two strings lexicographically. Returns a negative value if s1<s2; 0 if s1 and s2 are identical; and a positive value if s1>s2.

string.h

strcmpi(s1,s2)

int

Compares two strings lexicographically, without regard to case. Returns a negative value if s1<s2; 0 if s1 and s2 are identical; and a positive value if s1>s2.

string.h

strcpy(s1,s2)

char*

Copies string s2 to string s1.

string.h

strlen(s)

int

Returns the number of characters in a string.

string.h

strset(s,c)

char*

Sets all characters within s to c (excluding the terminating null character \0).

string.h

system(s)

int

Passes command s to the operating system. Returns 0 if the command is successfully executed; otherwise, returns a nonzero value, typically -1.

stdlib.h

tan(d)

double

Returns the tangent of d.

math.h

tanh(d)

double

Returns the hyperbolic tangent of d.

math.h

time(p)

long int

Returns the number of seconds elapsed beyond a designated base time.

time.h

toascii(c)

int

Converts value of argument to ASCII.

ctype.h

tolower(c)

int

Converts letter to lowercase.

ctype.h, or stdlib.h

toupper(c)

int

Converts letter to uppercase.

ctype.h, or stdlib.h


 Note: Type refers to data type of the quantity that is returned by the function. An asterisk
(*) denotes a pointer. c denotes a character-type argument. d denotes a double-precision argument.

Example 2: Write a function to calculate the real roots of a quadratic equation. Revised version of Example-1 given above.

#include <stdio.h>

#include <math.h>

float quad(float a1, float b1, float c1);

main()

{

   float a,b,c;

   printf("Enter a, b and c: ");

   scanf("%f %f %f", &a, &b, &c);

   quad(a, b, c);

   return 0;

}

float quad(float a1, float b1, float c1)

{

   float d, x_1, x_2;

   d=sqrt(pow(b1,2)-4*a1*c1);

   x_1=(-b1+d)/(2*a1);

   x_2=(-b1-d)/(2*a1);

   printf("a, b, c, x_1, x_2: %5.2f, %5.2f, %5.2f,%5.2f, %5.2f", a1,

           b1, c1, x_1, x_2);

   return 0;

}

Test Output:

Enter a, b and c: 2 3 1

a, b, c, x_1, x_2:  2.00,  3.00,  1.00,-0.50, -1.00

14.2 Recursion

Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. This process is useful for repetitive computations in which each action is expressed in terms of a previous result. Many iterative problems can be written in this form. In order to solve a problem recursively, two conditions must be satisfied. First, the problem must be written in a recursive form; and second, the problem statement must include a stopping criterion. 

// Programme to demonstrate function recursion.

#include <stdio.h>

#include <conio.h>

recursion()

{

     int num;

     printf("\nRecursion... ");

     printf("\n\n Enter Number : ");

     scanf("%d",&num);

     if (num==3)

         {     printf("End of Recursion Function.\n");

          exit(0);}

     else

          recursion();

     return 0;

}

void main()

{

     clrscr();

     recursion();

}

Test Output

Recursion...

 Enter Number : 4

Recursion...

 Enter Number : 55

Recursion...

 Enter Number : 6543

Recursion...

 Enter Number : 3

End of Recursion Function.

Example 3: Programme to multiply two integer numbers by recursion.

#include<stdio.h>

int multiply(int x,int y);

int main(){

    int a,b,product;

    printf("Enter any two integers: ");

    scanf("%d%d",&a,&b);

    product = multiply(a,b);

    printf("Multiplication of two integers is %d",product);

    return 0;

}

int multiply(int x,int y){

    static int product=0,i=0;

    if(i < x){

      product = product + y;

      i++;

      multiply(x,y);

    }

    return product;

}

Test Output:

Enter any two integers: 5 8

Multiplication of two integers is 40.

Example 4: Programme to find the sum of first n natural numbers by recursion:

#include<stdio.h>

int main(){

    int n,sum;

    printf("Enter the value of n: ");

    scanf("%d",&n);

    sum = getSum(n);

    printf("Sum of n numbers: %d",sum);

    return 0;

}

int getSum(n){

    static int sum=0;

    if(n>0){

         sum = sum + n;

         getSum(n-1);

    }

    return sum;

}

Test output:

Enter the value of n: 10

Sum of n numbers: 55

Note that recursion can be used as an alternative to looping structures.

Example 5: Programme to compute factorial of a positive integer number.

Commonly, this problem is defined as , where n is the given integer number. However, you can express this problem in another way, by writing  This is a recursive statement of the problem, in which the desired action is expressed in terms of previous result. Also, you know that  by definition, therefore, this provides the stopping criterion. The following programme accomplishes this task.

#include <stdio.h>

long int factorial(int n);

void main()

{

int n;

long int factorial(int n);

printf(“n = ”);

scanf(“%d”, &n);

printf(“n! = %ld\n”, factorial(n));

}

long int factorial(int n)

{

if (n <= 1)

return(1);

else

return(n * factorial(n-1));

}

Test Output

n = 10

n! = 3628800   

Explanation:                                                       

The main portion of the programme simply reads the integer quantity n and then references the long-integer recursive function, factorial. Note that the long integers are used for this calculation as factorials of even modest values of n are large integer quantities. The function, factorial accesses itself recursively, with an actual argument (n-1) that decreases in magnitude for each successive access. The recursive access terminates when the value of the actual argument becomes equal to 1. Note that when the programme is executed, the function, factorial will be accessed repeatedly, once in main and (n-1) times within itself, though the end-user using this programme will not be aware of this. Only resultant value will be displayed. For example, for the value of n=10, the factorial is 3628800. The input and output of the programme is:

n = 10

n! = 3628800