Thursday, September 20, 2012

Functions in C

The function is a self contained block of statements which performs a coherent task of a same kind.
C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call function whenever we want to process that functions statements.

Types of functions :

There are 2(two) types of functions as:

1. Built in function
2. User defined function


1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g.
  • scanf()
  • printf()
  • strcpy
  • strlwr
  • strcmp
  • strlen
  • strcat
2. User Defined Functions :
The functions which are created by user for program are known as 'User defined functions'.
Syntax:

void main()
{
 // Function prototype
 <return_type><function_name>([<argu_list>]);
 
 // Function Call
 <function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
 <function_body>;
}

Example program :
#include <stdio.h>
#include <conio.h>
void add()
{
 int a, b, c;
 clrscr();
 printf("\n Enter Any 2 Numbers : ");
 scanf("%d %d",&a,&b);
 c = a + b;
 printf("\n Addition is : %d",c);
}
void main()
{
 void add();
 add();
 getch();
}

Output:
Enter Any 2 Numbers : 23 6
Addition is : 29

Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type.

Syntax of function prototype:
return_type function_name(type(1) argument(1),....,type(n) argument(n));

Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked).
function_name(argument(1),....argument(n));

Function definition
Function definition contains programming codes to perform specific task.
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
                //body of function
}
Function definition has two major components:

1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function.
return_type function_name(type(1) argument(1),....,type(n) argument(n))

2. Function body
Function declarator is followed by body of function which is composed of statements.

Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or  variable) passed from a program to the function.



In above example two variable, num1 and num2 are passed to function during function call and these arguments are accepted by arguments a and b in function definition.

Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same.
A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to calling function.
return (expression);
          OR
     return;

For example:
return;
return a;
return (a+b);


Types of User-defined Functions in C Programming
For better understanding of arguments and return in functions, user-defined functions can be categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 categories of user defined functions.

Function with no arguments and no return value.
/*C program to check whether a number entered by user 
   is prime or not using function with no arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
    prime();      //No argument is passed to prime().
    return 0;
}
void prime(){  
/* There is no return value to calling function main(). Hence,
   return type of prime() is void */
    int num,i,flag=0;
    printf("Enter positive integer enter to check:\n");
    scanf("%d",&num);
    for(i=2;i <=num/2;++i){
        if(num%i==0){
             flag=1;
         }
    }
    if (flag==1)
        printf("%d is not prime",num);
    else
       printf("%d is prime",num);  
    }

Function prime() is used for asking user a input, check for whether it is prime of not and display it accordingly. No argument is passed and returned form prime() function.

Function with no arguments but return value
/*C program to check whether a number entered by user 
is prime or not using function with no arguments but having return value */
#include <stdio.h>
int input();
int main(){
    int num,i,flag;
    num=input();     /* No argument is passed to input() */
    for(i=2,flag=i;i<=num/2;++i,flag=i){
    if(num%i==0){
        printf("%d is not prime",num);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",num);
    return 0;
}
/* Integer value is returned from input() to calling function */
int input(){  
    int n;
    printf("Enter positive enter to check:\n");
    scanf("%d",&n);
    return n;
}
There is no argument passed to input() function But, the value of n is returned from input() to main() function.
Function with arguments and no return value
/*Program to check whether a number entered by user is prime or  not using function with arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
    int num;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
    check_display(num);  /* Argument num is passed to function. */
    return 0;
}
void check_display(int n){     
/* There is no return value to calling function.
Hence, return type of function is void. */
    int i,flag;
    for(i=2,flag=i;i<=n/2;++i,flag=i){
    if(n%i==0){
        printf("%d is not prime",n);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",n);
}
Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function.

Function with argument and a return value
/* Program to check whether a number entered by user is prime or not using function with argument and return value */
#include <stdio.h>
int check(int n);
int main(){
    int num,num_check=0;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
  /* Argument num is passed to check() function. */ 
   num_check=check(num); 
    if(num_check==1)
       printf("%d in not prime",num);
    else
       printf("%d is prime",num);
    return 0;
}
int check(int n){   
/* Integer value is returned from function check() */ 
    int i;
    for(i=2;i<=n/2;++i){
    if(n%i==0)
        return 1;
}
   return 0;
}
Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

Recursion :
A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.
Example of recursion
Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main(){
    int num,add;
    printf("Enter a positive integer:\n");
    scanf("%d",&num);
    add=sum(num);
    printf("sum=%d",add);
}
int sum(int n){
    if(n==0)
       return n;
    else
       return n+sum(n-1);    /*self call  to function sum() */
}

Output
Enter a positive integer:
5
15

In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15

Storage Class
Every variable and function in C programming has two properties: type and storage class. Type refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:
  • automatic
  • external
  • static
  • register
Automatic storage class
Keyword for automatic variable
auto
Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
External storage class
External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.

Example to demonstrate working of external variable

#include <stdio.h>
#include <conio.h>
void Check();
int a=5;    
/* a is global variable because it is outside every function */
int main(){
    a+=4;
    Check();
    return 0;
}

void Check(){
   ++a;
/*  ----- Variable a is not declared in this function but, 
works in any function as they are global variable -------  */
   printf("a=%d\n",a);
}

Output:
 a=10

Register Storage Class
Keyword to declare register variable
register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it in memory.

Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
#include <conio.h>
void Check();
int main(){
   Check();
   Check();
   Check();
}
void Check(){
    static int c=0;
    printf("%d\t",c);
    c+=5;
}

Output
0      5     10

During first function call, it will display 0. Then, during second function call, variable c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0     0     0

Function Examples programs:
Write a C program to reverse a number entered by user. Make function Reverse() to reverse the numbers.
#include <stdio.h>
#include <stdio.h>
int Reverse(int n);
int main()
{
    int num,i;
    printf("Enter number to reverse\n");
    scanf("%d",&num);
    printf("Reverse of %d=%d",num,Reverse(num));
    return 0;
}
int Reverse(int n)
{
    int rem,rev=0;
    while(n!=0){
       rem=(n%10);
       n=(n/10);
       rev=rev*10+rem;
    }
    return rev;
}

Output:
Enter number to reverse
56
Reverse of 56=65

Write a C program to reverse a sentence using recursive function. 

#include <stdio.h>
void Reverse(char c);
int main(){
   char c;
   printf("Enter sentence to reverse: \n");
   Reverse(c);
   return 0;
}
void Reverse(char c){
    scanf("%c",&c);
    if(c!='\n'){
        Reverse(c);
        printf("%c",c);
      }
}

output:
Enter sentence to reverse:
dog
god

C program to find hcf and lcm using recursion 

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}

C program to find hcf and lcm using function 

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long x, long y) {
  if (x == 0) {
    return y;
  }
 
  while (y != 0) {
    if (x >y) {
      x = x - y;
    }
    else {
      y = y - x;
    }
  }
 
  return x;
}

Output:
Enter two integers
9  15
Greatest common divisor of 9 and 15 = 3
Least common multiple of 9 and 15 = 45

Important questions:

Q. What are built in functions?
Ans: The functions that are predefined and supplied along with the compiler are known as built-in functions.They are also known as library functions.

Q. What do the ‘c’ and ‘v’ in argc and argv stand for?
Ans: The c in argc(argument count) stands for the number of command line argument the program is invoked with and v in argv(argument vector) is a pointer to an array of character string that contain the arguments.

Q. In header files whether functions are declared or defined?
Ans: Functions are declared within header file. That is function prototypes exist in a header file,not function bodies. They are defined in library .

Q.What is the difference between "printf(...)" and "sprintf(...)"?
sprintf(...) writes data to the character array whereas printf(...) writes data to the standard output device.

No comments:

Post a Comment