Learn how to write the C program step-by-step | Lesson - 5

C FUNCTIONS

 

 

Topics:

  • Accessing a Function
  • Passing Arguments To A Function
  • Specifying Argument Data Type
  • Recursive Function

 

Basic of C program
 C program

 Accessing a Function

  • A function can be accessed by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the function's name.
  • There may be several different calls to the same function from various places within a program. The actual arguments may differ from one function call to another.
  •  The following sequence of steps occur when a function is invoked:
  • Memory is reserved for function arguments.
  • actual argument values are determined, and they are assigned to the formal arguments.
  • Space is reserved for the local variable of the function. Initial values, if necessary are assigned to the local variables.
  • Program control passes to the first executable statement of the function.
  • The function is executed. It may in turn invoke other functions.
  • When a return statement with an expression is encountered, the value of the expression in calculated.
  • After a return statement, if present, otherwise after the last statement in a function body, program control is passed back to the invoking function.
  • Memory space used by the formal arguments and the local variable of the function is released.
  • The return value is used, if required, by the statement in the invoking function that contained the function reference.

 

Calculate the factorial of number

Program-1

#include<stdio.h>
/* Calculate the factorial of number */
void main ()
      
{      int numb;
        long int factorial( );
        printf("\nNumber = ");
        scanf("%d",&numb);
        printf("\nFactorial = %Id\n\n",factorial(numb));
       

long int factorial(numb)      
 int numb;
{     int i;
       counter=2;
       long int ans = 1;
       if(numb > 1)
            for(i = 2;i<=numb;++i)   
                {    counter += counter;
                     ans *=i;
                     printf("%d * %d = %d\n",ans, counter,ans);
                    }
       return(numb);       
       }
 
 
Passing Arguments To A Function
 
  • When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. So, the value of the corresponding formal argument can be modified within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value.
  • When the arguments of a function are passed by value, a copy of the value is sent from the calling routine to the function, rather than allowing the function direct access to the memory location of the variable. Therefore, in call by value the function uses a copy of the argument value copy of the argument value only. 
  • It can not access the actual memory location of the variable and therefore cannot change the value of the actual argument of the calling function. Since only copies of values are being manipulated, the original values in the calling function are never affected by the called function.
 
Advantage of passing an argument by value
  • It allows a single-valued actual argument to be written as an expression rather than being restricted to a single variable.
  • if the actual argument is expressed as a single variable, it protects the value of this variable from alterations within the function.
 
Arrays are passed differently than single-valued entities. If an array name is specified as an actual argument, the individual array elements are not copied to the function. Instead, the location of the array (i.e the location of the first element) is passed to the function. If an element of the array is accessed within the function, the access will refer to the location of that array element relative to the location of the first element. Thus, any alteration to an array element within the function will carry over to the calling routine.
 

Passing Argument to a Function


Program-1
#include<stdio.h>
/* Passing Argument to a Function */
Void main( )
{    int a = 2;
    printf("\nThis Is From Main Program\n");
    printf("a = %d",a);
    change(a);
    printf("\nThis Is Again From Main Program\n");
    printf("a = %d\n",a);
    }

change(a)
int a:
{    a *=3;
    printf("\nThis Is From Called Function\n");
    printf("a = %d",a);
    return(a);
    }



Demonstration of the use of multiple parameters



Program-2
#include<stdio.h>
/* Demonstration of the use of multiple parameters */
Void main( )
{    int length, width ;
    printf("\nEnter the length of a rectangle :");
    length = get_int( );
    printf("Enter the width : ");
    width = get_int( );
    printf("\nThe area is %d. \n",area(length,width));
    }

get_int( )
{    int a:
    scanf("%d", &a);
    return(a);
    }
area(length,width)
int length,width;
{    return(length * width);
    }


Specifying Argument Data Type

It is possible to include the data types of the arguments within the function declaration. The compiler
will then convert the value of each actual argument to the declared data type (if necessary) and then compare each (converted) actual data type with its corresponding formal argument.

A compilation error will result if the data types do not agree.  Thus, the use of function declarations will allow the programmer to be informed of data-type inconsistencies detected during the compilation process.

Example to calculate depreciation. using-defined Functions

Program-1
#include<stdio.h>
/* Example to calculate depreciation. using-defined Functions */
Void main( )
{    int n, year, choice=0;
    float value, flag, depri;
    while(choice !=4)
    {    printf("\n\n\t *** Depreciation Method *** \n");
        printf("\t\t1. Straight Line \n");
        printf("\t\t2. Double Declining \n");
        printf("\t\t3. Sum Of The Years' Digit \n");
        printf("\t\t4. Stop \n");
        Printf("\nEnter Your Choice : ");
        scanf("%d",&choice);
        if(choice>=1 && choice <= 3)
            {    Printf("Enter Product Value : ");
                scanf("%f",&value);
                printf("Enter No. of Years : ");
                scanf("%d",&n);
                }

switch(choice)
{

Case 1:
    printf("\n End of Year\t Depreciation\tCurrent Value\n");
    Sl(value,n);
    break;

Case 2:
    printf("\n End of Year\t Depreciation\tCurrent Value\n");
    ddb(value,n);
    break;


Case 3:
    printf("\n End of Year\t Depreciation\tCurrent Value\n");
    syd(value,n);
    break;


Case 4:
    
    break;

default:
    printf("\nInvalid Choice, Try Again");
    }
     }
  }

sl(value, n)
float value;
int n;
{    float depri;
    int year;
    depri =value/n;
    for(year=1;year<=n;++year)
    {    value-= depri;
        printf("\t%2d\t %7.2f\t %8.2f\n",year,depri,value);
        }
    return;
    }


ddb(value, n)
float value;
int n;
{    float depri;
    int year;
    depri =value/n;
    for(year=1;year<=n;++year)
    {    depri=2*value/n;   
        value-= depri;
        printf("\t%2d\t %7.2f\t %8.2f\n",year,depri,value);
        }
    return;
    }




syd(value, n)
float value;
int n;
{    float flag,depri;
    nt year;
    flag=value;
    for(year=1;year<=n;++year)
{    depri=(n-year+1)*flag/(n*(n+1)/2);   
        value-= depri;
        printf("\t%2d\t %7.2f\t %8.2f\n",year,depri,value);
        }
    return;
    }


Recursive Function

Recursion is a process by which a function calls itself repeatedly until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous result.

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 condition.


14 Way to make money online

 

Calculate the factorial of number. Using Recursion

Program-1

#include<stdio.h>
/* Calculate the factorial of number. Using Recursion */
Void main( )
{    int numb;
    long int factorial(int numb);
    printf("Number =");
    scanf("%d",&numb);
    printf("Number's Factorial = %ld\n",factorial(numb));
    }   


change(a)
int a:
{    a *=3;
    printf("\nThis Is From Called Function\n");
    printf("a = %d",a);
    return(a);
    }
    long int factorial(int numb)
{    if(numb<=1)
        return(1);
        else
        return(numb * factorial(numb-1));
    }


The same program can also be written as follows:

Calculating factorial, Using Recursive Function

Program-2
#include<stdio.h>
/* Calculating factorial, Using Recursive Function */
Void main( )
{    int n, factorial;
    printf("Number =");
    scanf("%d",&n);
    factorial = calc(n);
    printf("\nFactorial of %d Is %d. \n", n, factorial);
    }   

calc(x)
int x;
{    if(x==1 || x==0)
        return(1);
        else
        return(x*calc(x-1));

    }


Reverse a String of Text. Using Recursive Function

Program-3
#include<stdio.h>
/* Reverse a String of Text. Using Recursive Function */
Void main( )
{    void reverse(void);
    printf("\nEnter a Line : ");
    reverse( );
    }   

void reverse(void)
{    char c;
    if((c=getchar()) != '\n') reverse();
    putchar(c);
    return;
    }


 
 

Thanks a lot for reading.
Neel Kamal
Learn how to write the C program step-by-step | Lesson - 5 Learn how to write the C program step-by-step | Lesson - 5 Reviewed by Neel Kamal on November 20, 2020 Rating: 5

No comments:

For More Details Subscribe & Comment..!

Powered by Blogger.