C-Tutorial: FUNCTIONS

Latest

Showing posts with label FUNCTIONS. Show all posts
Showing posts with label FUNCTIONS. Show all posts

Friday, 11 November 2016

Actual arguments, Formal arguments

Friday, November 11, 2016 0
Actual arguments (or) Actual Parameters

The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function.

Formal arguments (or) Formal Parameters

The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments.

/* Demonstrating the actual and formal arguments */

#include <stdio.h>
int add(int, int); /* Function Prototype */
int main()
{
  int a = 10, b= 20, sum;

  /* a and b are actual arguments. They are the source
     of data. Caller program supplies the data to called
     function in form of actual arguments. */

  sum = add(a,b); /* function call */

  printf("Sum of %d and %d is: %d \n", a, b, sum);
}

/* a and b are formal parameters. They receive the values from
   actual arguments when this function is called. */

int add(int a, int b)
{
  return  a + b;
}

OUTPUT:

Sum of 10 and 20 is: 30

Read More

Types of Function calls in C (or) Parameter passing techniques

Friday, November 11, 2016 0
Types of Function calls in C (or) Parameter passing techniques

Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them,

1. Call by Value
2. Call by Reference

1. Call by Value: 
In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.

#include<stdio.h>
#include<conio.h>

void swap(int, int);
int main()
{
 int x = 10, y=20;
printf("\n Before swapping the X=%d, Y=%d",x,y);
swap(x,y);
printf("\n After swapping the X=%d, Y=%d",x,y);
}

void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}

In this case if we made any changes with receiving arguments, Those changes are not reflect on outside of the function


2. Call by Reference (or) Call by address:

In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.

#include<stdio.h>
#include<conio.h>

void swap(int *, int *);
int main()
{
 int x = 10, y=20;
printf("\n Before swapping the X=%d, Y=%d",x,y);
swap(&x, &y);
printf("\n After swapping the X=%d, Y=%d",x,y);
}

void swap(int *x, int *y)
{
int temp;
temp= *x;
*x = *y;
*y = temp;
}

In this case if we made any changes with receiving arguments, Those changes are reflect on outside of the function

Read More

Return statement in C

Friday, November 11, 2016 0
Return statement

                     A function may or may not return a value. A return statement returns a value to the calling function and assigns to the variable in the left side of the calling function. If a function does not return a value, the return type in the function definition and declaration is specified as void.

Syntax:
1. return expression ; (or)
2. return ;


Example:
#include<stdio.h>
#include<conio.h>
int mul(int, int);
main()
{
int a=10,b=20,m;
clrscr();
m=mul(a,b);
printf(“\n Multiplication = %d”,m);
}
int mul(int x,int y)
{
return x*y;
}
Read More

Passing arrays to functions

Friday, November 11, 2016 0
Passing single dimension array to function


A single array (or) entire array can be passed to a function. Both one dimensional array (or) two dimensional (or) multidimensional array can be passed to a function as argument.

1. Passing entire array to function : To pass an entire array to a function, The array name must appear by itself without braces (or) subscripts as an actual arguments with in the function call. whereas formal parameters should be represented as a array variables. In function prototype, array arguments are represented as empty pair of braces.
syntax: function_prototype(data_type []);
calling function(arrayname);
called_function(data_type arrayname[])

Example program for passing entire array to function:
void action(int []);
main()
{
int i, a[10];
clrscr();
printf("\n Enter 5 array elements");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
action(a);
getch();
}
void action(int a[])
{
int i;
for(i=0;i<5;i++)
printf("%d",a[i]);
}


2. Passing single array element to a function: In C-language the name of the array represents the address of its first element. By passing the array name, actually we are passing the address of the array to the called function.

syntax: function_prototype(data_type);
calling function(arrayname[]);
called_function(data_type arrayname)

Example program for passing single array element to a function:
void action(int);
main()
{
int i, a[5];
clrscr();
printf("\n Enter 5 array elements");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
action(a[2]);
getch();
}
void action(int a)
{
printf("%d",a);
}
Read More

C – Type Qualifiers

Friday, November 11, 2016 0
C – Type Qualifiers


• The keywords which are used to modify the properties of a variable are called type qualifiers.

Types of C type qualifiers:
There are two types of qualifiers available in C language. They are,
1. const
2. volatile

1. const keyword:

  • Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.
  • They refer to fixed values. They are also called as literals.
  • They may be belonging to any of the data type.

• Syntax:       const data_type variable_name;

1. Example program using const keyword in C:
#include <stdio.h>
void main()
{
const int height = 100;  
const float number = 3.14;
printf(“value of height :%d \n”, height );
printf(“value of number : %f \n”, number );

}

2. volatile keyword:
• When a variable is defined as volatile, the program may not change the value of the variable explicitly.
• But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile.
• For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable.

• Syntax:      
volatile data_type variable_name; (or) volatile data_type *variable_name;

1. Example program using const keyword in C:

#include <stdio.h>
void main()
{
const int height = 100;  
const float number = 3.14;
printf(“value of height :%d \n”, height );
printf(“value of number : %f \n”, number );
}

Read More

Recursion, Advantages, Disadvantages

Friday, November 11, 2016 0
Recursion

A function calls itself is called recursion and the function is called as recursive function.  The main advantage of recursion is to avoid the length of the code.

Ex: main()
{
     --
     main();
     --
}

Recursion can be classified into two types as:
1. Direct recursion
2. Indirect recursion

1. Direct recursion: A function calls itself is known as direct recursion.

Ex: void sum()
{
--
sum();
--
}

2. Indirect recursion: A function calls another function, which initiates to call of the initial function is known as indirect recursion.

Ex: void sum()
{
call();
}

void call()
{
sum();
}

/*  Example program for GCD using recursion */

#include<stdio.h>
#include<conio.h>

int rgcd(int,int);
main()
{
int m,n;
clrscr();

printf("\n Enter m,n values:\t");
scanf("%d%d",&m,&n);
printf("\n GCD = %d",rgcd(m,n));
getch();
}

int rgcd(int m,int n)
{
if(n==0)
return m;
else
return rgcd(n,m%n);
}

Recursion Advantages: 

i. It is easily, simple and understandable.
ii. Using recursion we can avoid unnecessary calling of functions.
iii. The recursion is very flexible in data structure
iv. Using recursion, the length of the program can be reduced.

Recursion Disadvantages:

i. It requires extra storage space. The recursive calls and automatic variables are stored on the stack.
ii. For every recursive calls separate memory is allocated to automatic variables with the same name.
iii. If the programmer forgets to specify the exit condition in the recursive function, the  program will execute out of memory.
iv. The recursion function is not efficient in execution speed and time.
Read More

NESTED FUNCTIONS

Friday, November 11, 2016 0

NESTED FUNCTIONS

Functions can also be placed within another function.  Such representation is known as nested functions.

Syntax: main() Fun1() Fun2()
{ { {
  --   - -    - -
  --   Fun2();    - -
  Fun1();   - - }
  - - }
}

/* EXAMPLE PROGRAM FOR NESTED FUNCTIONS */

#include<stdio.h>
#include<conio.h>

void fun1();
void fun2();

main()
{
clrscr();
printf("\n main function starts");
fun1();
printf("\n main function ends");
}
void fun1()
{
printf("\n function1 starts");
fun2();
printf("\n  function1 ends");
}
void fun2()
{
printf("\n function2 starts");
printf("\n function2 ends");
}

Read More

Functions prototypes (or) Function categories (or) Types of user defined functions

Friday, November 11, 2016 0
Functions prototypes (or) Function categories (or) Types of user defined functions

Depending on whether arguments are passed or not and function returns any value or not, functions are classified into different categories as:

1. Function with arguments (parameters) and with return type
2. Function with arguments (parameters) and without return type
3. Function without arguments (parameters) and without return type
4. Function without arguments (parameters) and with return type


1 with arguments and with return values
int function ( int );         // function declaration
function ( a );                // function call
int function( int a )       // function definition
{
statements;
return a;
}

2 with arguments and without return values
void function ( int );     // function declaration
function( a );                // function call
void function( int a )   // function definition
{
statements;
}

3 without arguments and without return values
void function();             // function declaration
function();                     // function call
void function()              // function definition
{
statements;
}

4 without arguments and with return values
int function ( );             // function declaration
function ( );                  // function call
int function( )               // function definition
{
statements;
 return a;
}

Note:
• If the return data type of a function is “void”, then, it can’t return any values to the calling function.
• If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values to the calling function.

Case1 : Function with arguments and with return type
#include<stdio.h>
#include<conio.h>
int sum(int, int);  
void main()
{
 int i=10,j=20,k;
 clrscr();
 k=sum(i,j);  
 printf("%d",k);
 getch();
}

int sum(int a, int b)  
{
return a+b;
}


Case2: Function with arguments and without return type
#include<stdio.h>
#include<conio.h>
void sum(int, int);  

void main()
{
 int i=10,j=20;
 clrscr();
 sum(i,j);    
 getch();
}
void sum(int a,int b)  
{
 printf("\n Sum=%d", a+b);
}

Case3 : Function without arguments and with return type
#include<stdio.h>
#include<conio.h>
int sum();

void main()
{
 int k;
 clrscr();
 k=sum();    
 getch();
}
int sum()  
{
 int a=10,b=20;
 return a+b;
}

Case4: Function without arguments and without return type
#include<stdio.h>
#include<conio.h>
void sum();  
void main()
{
sum();    
}
void sum()  
{
int a=10,b=20;
printf("sum=%d",a+b);
}

Read More

User defined functions in C

Friday, November 11, 2016 0

User defined functions in C


  • ·         The functions which are defined by the user at the time of writing program.
  • ·         Functions are made for code reusability and for saving time and space.
  • ·         For creating user defined function user can follow the three things.

1. Function prototype
2. Calling function
3. Called function

Function prototype (or) Function Declaration:
General syntax of function declaration is,
return-type function-name (parameter-list) ;
Like variable and an array, a function must also be declared before it is called. A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration consist of 4 parts.
·         return-type : It specifies what type of values returned by the function
·         function name: It specifies the name of the function and it follows the identifiers rules.
·         parameter list: The arguments used to perform the function implementation
·         must terminating with semicolon

Calling Function:
·                  A function can be accessed by specifying it's name followed by list of arguments enclosed with parenthesis and separated by comma operator. 
·                  If  in function call doesn't require any arguments, Then empty pair of parenthesis must follow the name of the function.
·                  If return type is void in function prototype then syntax to write the calling function is as follows.                  calling_function(var1,var2,var3,......,varn);
                                                                                                Actual arguments (or) actual parameters
·                  If return type is not void in function prototype then syntax to write the calling function is as follows.                            Var_name=calling_function(var1,var2,var3,......,varn);
Ex:          1. message();
                2. add(x,y);
                3. x=add();
                4. x=rfact(n);
Called function (or) Function Definition:
Function definition contains implement code of the function.  The general format of a function definition is:

Syntax: Return_type Function_name (datatype arg1, - - - - - - - , datatype argn)
              {
                        Local Variable Declarations
                        --
                        --          (Implementation Code)
                        --
                        return value;
              }
Where,
  • arg1, arg2,  --- , argn arguments are known as “formal arguments”.  List of values passed from the function call are temporarily stored in these formal parameters.
  • Variables declared in the function definitions are called local variables.
  • After completing implementation of the function, it should return a value to the calling function with a return statement.
  • The syntax of a return statement is:
Syntax:           return value;
            If the function should not return any value, then simply placed as:

                        Syntax:           return;
Read More

Library functions in C

Friday, November 11, 2016 0
Library functions

Functions that are predefined by the compiler are known as library functions. 

Ex:                          scanf(), printf(), getch(), getche(), etc.,

For all the library functions, definitions and necessary information is available in header files.  Some of the important header files are:

            stdio.h             -           Standard Input and Output header file
            conio.h            -           Console Input and Output header file
            stdlib.h            -           Standard library header file

            ctype.h                        -           Character type header file

            math.h             -           Mathematical header file

ctype.h                       -           Character type header file

            ctype.h header file provides several library functions used for character testing and conversions.

1. islower():                            Syntax:            islower(ch)
Function determines whether the given argument is in lowercase or not.  If it is in lowercase, then returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that represents FALSE.

2. isupper():                            Syntax:            isupper(ch)
Function determines whether the given argument is in uppercase or not.  If it is in uppercase, then returns a non-zero value that represents TRUE; otherwise, it returns ‘0’ that represents FALSE.

3. tolower():                            Syntax:            tolower(ch)
            Function converts the given argument from upper case to lower case.

4. toupper():                           Syntax:            toupper(ch)
            Function converts the given argument from lower case to upper case.

math.h                        -           Mathematical header file

        math.h header file provides several library functions used for mathematical operations.


1. sin():                        Syntax:            sin(d)

            Where, d is a double type argument.
            Function receives a double type argument and returns the sine value as double.
                        Ex:       printf(“%lf”, sin(45));

2. cos():                       Syntax:            cos(d)
            Function receives a double type argument and returns the cosine value as double.
                        Ex:       printf(“%lf”, cos(45));

3. tan():                       Syntax:            tan(d)
            Function receives a double type argument and returns the tangent value as double.
                        Ex:       printf(“%lf”, tan(45));

4. log():                       Syntax:            log(d)
            Function receives a double type argument and returns the natural logarithm (base e) value as double.
                        Ex:       printf(“%lf”, log(10));

5. sqrt():                      Syntax:            sqrt(d)
            Function receives a double type argument and returns the square root value as double.
                        Ex:       printf(“%lf”, sqrt(36));

6. pow():                     Syntax:            pow(d1, d2)
            Function receives two double type arguments and returns the d1 raised to the d2 power value as double.

                        Ex:       printf(“%lf”, pow(3,4));
Read More

Functions in c

Friday, November 11, 2016 0

Functions in c



Definition: A function is a self contained program segment (or) A function is a sub program (or) A function is a module that carries out some specific, well defined task.

A function is a block of code that performs a particular task. Sometimes we need to write a particular block of code for more than once in our program. This may lead to bugs and irritation for the programmer. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.

Benefits of Using User Defined Functions

1.      It provides modularity to the program.
2.      Easy code Reusability. You just have to call the function by its name to use it.
3.      In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions.


In C - language functions can be classified into two categories,

Read More

Monday, 10 October 2016

C – Storage Class Specifiers

Monday, October 10, 2016 0

C – Storage Class Specifiers


Ø  A storage class is used to declare variables. To fully defined a variable one needs to mention not only it's data type, But also it's storage class.    
Ø  Storage class specifiers in C language tells the compiler where to store a variable, what is the initial value of the variable, What is the scope of the variable and life time of the variable.

Storage class tells the compiler about the following information

1. Storage area: It specifies the location where the variable is stored.  i.e, Either in CPU memory unit (or) Register memory.

2. Default / Initial value:  If we are not going to provide value to a variable then system automatically provide values to the variable. There are two types of default/initial values. Those are
            1. Garbage value (Unpredictable value)
            2. Zero

3. Scope:  It specifies the scope of the variable. i.e, In which function the value of the variable would be available.

4. Life time of a variable:  It specifies the life of the variable. i.e, how long a variable exits

Types of Storage Class Specifiers in C:

     There are 4 storage class specifiers available in C language. They are,
1)      Automatic Storage class
2)      External Storage class
3)      Static Storage class
4)      Register Storage class

Syntax:
                      storage_specifier   data_type   variable _name;

example:                   static  int  x;

                      Here 'x' is the static storage class variable


1)      Automatic Storage class;
Ø    Automatic variables are declared with in a function with the keyword called "auto"

Ø          They are local to the function in which they are declared

Ø           Automatic variables are created when they function is called and destroyed automatically    when the function is completed

Ø          A variable inside a function without any storage class specification is by default an auto variable

#include<stdio.h>
void increment();
int main()
{
increment();
increment();
increment();
}
void increment()
{
auto int i = 0 ;
printf ( “%d “, i ) ;
i++;
}

2) Static Storage class:

Ø        static variables are declared outside of the function with the keyword called "static"

Ø         static variable holds the latest value of the variable in the function in which they are declared.

Ø        There are two types of static variables are available, Those are
            1. Local static variable [ variables declare inside of the function]
            2. Global static variable [ variables declare outside of the function ]

Ø          It specifies the following information to the compiler
            Storage area: CPU memory
            Default value:            Zero
            Scope:             1. Scope of local static variable is local to the function  in which                                                      the variable is declared.
                                    2. Scope of the global static variable is throughout the program.
            life time:         Through out the program. Variable definition might be any where                                       in the program.

  Static variables retain the value of the variable between different function calls.
//C static example
#include<stdio.h>
void increment();
int main()
{
increment();
increment();
increment();
}
void increment()
{
static int i = 0 ;
printf ( “%d “, i ) ;
i++;
}

3) Extern Storage Class:

Ø          extern variables are declared outside of the function with the keyword called "extern"

Ø          extern variables are global to all functions within the program

Ø          The variables declared outside a function without any storage class is by default  external variables. But when ever, we use the extern keyword then the variables must be initialized.

Ø           It specifies the following information to the compiler
            Storage area:    CPU memory
            Default value:   Zero
            Scope:             Global all functions with in a program
            life time:         Through out the program. Variable definition might be any where                                                   in the program.


#include<stdio.h>
extern int x = 10 ;
 main( )
{
clrscr();
printf(“The value of x is %d \n”,x);

getch();
}


4) Register Storage class:

Ø         Register variables are declared with in a function with the keyword called "register"

Ø         Register variables are local to the function in which they are declared

Ø         Register variables are created when they function is called and destroyed automatically when the function is completed

Ø          Syntax for register storage variable is as follows
   register data_type  variable_name;
   ex:       register int x;
            register float y;

Ø         It specifies the following information to the compiler
            Storage area:    Register memory
            Default value:   Garbage value
            Scope:             Local to the function which they are declared
            life time:         With in the function only

Ø          Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.

Ø   Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.

Ø          But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)

#include <stdio.h>
int main()
{
register int i;
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
printf(“value of arr[%d] is %d \n”, i, arr[i]);
}
return 0;
}


S. No.
Storage Specifiers
Storage place
Initial / default value
Scope
Life time
1
auto
CPU Memory
Garbage value
local
Within the function only.
2
extern
CPU memory
Zero
Global
Till the end of the main program.
Variable definition might be anywhere in the C program
3
static
CPU memory
Zero
Local/
Global
Retains the value of the variable
between different function calls.
4
register
Register memory
Garbage value
local
Within the function
Read More