C and C++ Programming Resources

Custom Search

Functions in C Programming

Functions in C/C++ Programming

Functions groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind. e.g

Simple Functions

Our first example demonstrates a simple function those purpose is to print a line of 45 asterisks.The example program generates a table , and lines of asterisks are used to make the table more readable. Here”s the listing for Table:

 // table .cpp
   // demonstrates simpole function
   # include
   using namespace std;
   void starline( );
   into main ()
   {
	   starline ( );
	   cout << "Data type Range" << endl;
	   starline ( );
	   cout << "char -128 to 127 " << endl
	   << "short -32 ,768 to 32,767"<< endl
	   << "int system independent: << endl
	   << " long q-2,147,483,648 to 2,147,483,647" << endl;
	   starline ( );
		return 0;
	}
//""""""""""""""""""""""""..
//starline ( )
// function defintion
void starline ( )
{
	for(into j=0;j<45; j++)
	cout << "*" ;
	cout << endl;
}

The output from the program looks like this
*************************************
Data type Range
*************************************
Char -128 to 127
Short -32,768 to 32,767
Into system dependent
Double -2,147,483,648 to 2,147,483,647
*************************************

Why we use Functions”

The most important reason to use functions is to aid in the conceptual organization of a program.

Another reason to use functions is to reduce program size. Any sequence of instructions that appears in program more than once is a candidate for being made into a function. The function”s code is stored in only one place in memory, even though the function is executed many times in the course of the program.

Two reasons

  1. Writing functions avoids rewriting the same code over and over. Suppose that there is a section of code in a program that calculates area of a triangle. If, later in the program we want to calculate the area of a different triangle we wont like to write the same instructions all over again. Instead we would prefer to jump to a “section of code” that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function.
  2. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code in to modular functions also makes the pro-gram easier to design and understand.

Function Declaration

Just as you can”t use a variable without first telling the compler what it is, you also can”t use a funciotns without teling the compiler about it, There are two ways to do this . The approach we show here ist o declare the funtion before it is called. The other approach is to define it before it”s called. ; we”ll examine that next.) in the Table program, the functions starline() is declared in the line.

 Void starline ( );

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no arguments.

Notice that the funtois declarations is terminated with a semicolon It is a complete statement in itself.

Function declarations are also called prototypes, since they provide a model or blueprint for the function. They tell the compiler,” a function that looks like this is coming up later in the program, so it”s all right if you see references to it before you see the function itself.”

Calling the Function

The function is called (or invoked) three times from main (). Each of the three calls look like this:

 Starline():

This is all we need to call a function name,followed by parentheses. The syntax of the call is very similar to that of declaration, except that the return type is not used. A semicolon terminates the call. Executing the call statement causes the function to execute; that is, control is transferred to the function, the statement in the function definition are executed, and then control returns
to the statement following the function call.

Function Definition

Finally, we come to the functions its self, which is referred to as the functions definition, The definition contains the actual code for the function. Here’s the definition for starline( ) .

 void starline ( )
   {
   for ( intj=0, j < 45; j++ )
   cout << "*" ;
   cout << endl;
   }

The definition consists of a line called the decelerator, followed by the function body , The function body is composed of the statements that make up the function, delimited by braces.

The decelerator must agree with the declaration: It must use the same function name, have the same argument types in the same order( if there are arguments), and have the same return type.

Notice that a semicolon does not terminate the declarator. Figure shows the syntax of the function declaration, function call, and function definition.

When the function is called, control is transferred to the first statement in the functions body. The other statements in the function body are then executed, and when the closing brace is encountered, control returns to the calling program.

Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4] [Page - 5]

Tags:

There are 103 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.

  • ena says:

    What are the functions in C programming? Write a note with examples.

    • ruffa naomi says:

      guys, can you help me out with this prob: Make a program that would ask for two numbers then display their quotient aand modulo without using operators / and %.

    • kokila says:

      function is used for reusability of the code..the code inside the program can used anywhere in the program by calling the name of the function
      and also it used for easy understanding of the code functionality…

  • vasu says:

    write a program using one dimensional array that searches a number if it is found on the list of the given 5 input numbers and locate its exact location in the list…..
    SAMPLE INPUT/OUTPUT DIALOGUE:
    enter a list of numbers:
    5 4 8 2 6

    enter a number to be searhed: 2
    2 is found in location 4

    /*this is the program that gives the desired output*/
    #include<stdio.h>
    main()
    {
      int num[10],i,n,searchno;
      clrscr();
      printf("enter num to be searched");
      scanf("%d",&searchno);
      printf("enter n");
      scanf("%d",&n);
      printf("enter number in list");
      printf("the entered numbers are:");
      for(i=0;i<n-1;i++)
      {
         scanf("%d",&num[i]);
      }
      for(i=0;i<n-1;i++)
      {
        if(num[i]==searchno)
          printf("the searchno is %d , loc is %d",num[i],i);
        else
          printf("not found");
          break;
      }
      getch();
    }
    
  • #include<stdio.h>
    #include<conio.h>
    void main(void)
    {
    	int hour,min,sec,i;
    	clrscr();
    	printf("ENTER HOURS:");
    	scanf("%d",&hour);
    	printf("ENTER MINUTES:");
    	scanf("%d",&min);
    	printf("ENTER SECONDS:");
    	scanf("%d",&sec);
    	clrscr();
    	for(i=1;i<=I+1;i++)
    	{
    		sec=sec+1;
    		if(sec==60)
    		{
    			sec=0;
    			min=min+1;
    		}
    		if(min==60)
    		{
    			min=0;
    			hour=hour+1;
    		}
    		if(hour==24)
    		hour=0;
    		clrscr();
    		gotoxy(10,25);
    		printf("%02d:%02d:%02d",hour,min,sec);
    		sleep(1);
    	}
    	getch();
    }
    
  • #include<stdio.h>
    #include<conio.h>
    void main(void)
    {
    	int hour,min,sec,i;
    	clrscr();
    	printf("ENTER HOURS:");
    	scanf("%d",&hour);
    	printf("ENTER MINUTES:");
    	scanf("%d",&min);
    	printf("ENTER SECONDS:");
    	scanf("%d",&sec);
    	clrscr();
    	for(i=1;i<=I+1;i++)
    	{
    		sec=sec+1;
    		if(sec==60)
    		{
    			sec=0;
    			min=min+1;
    		}
    		if(min==60)
    		{
    			min=0;
    			hour=hour+1;
    		}
    		if(hour==24)
    		hour=0;
    		clrscr();
    		gotoxy(10,25);
    		printf("%02d:%02d:%02d",hour,min,sec);
    		sleep(1);
    	}
    	getch();
    }
    
    • ilimbek says:

      n!/n^n (from n=1 to infinity)
      Write a C program which will find the sum of the N-terms of the aboveseries. The program will consist of a MAIN function and a function.
      Within the MAIN function.
      . Number of terms N will be read from the standard input.
      . N will be passed to the function as an argument.
      . Sum of the N terms(return value from the function) will be printed.
      Within the function.
      . Sum of the N terms of the given series will be calculated and returned to the MAIN function.

  • Asadullah says:

    Detail About Recursion and its Type

    Here I am going to give a detail about Recursion in C++.
    Definition: Recursion is the process where a function is called itself but stack frame will be out of limit because function call will be infinite times. So a termination condition is mandatory to a recursion.
    In C++, Recursion can be divided into two types:
    (a) Run- Time Recursion: Normal as in C
    (b) Compile- Time Recursion: By using Template

    Each of these can be also divided into following types:

    1. Linear Recursion
    2. Binary Recursion
    3. Tail Recursion
    4. Mutual Recursion
    5. Nested Recursion

    1. Linear Recursion: This recursion is the most commonly used. In this recursion a function call itself in a simple manner and by termination condition it terminates. This process called ‘Winding’ and when it returns to caller that is called ‘Un-Winding’. Termination condition also known as Base condition.

    Example: Factorial calculation by linear recursion

    Run-Time Version

     int Fact(long n)
    {
     	if(0>n)
                   return -1;
    	if(0 == n)
    	   return 1;
    	else
    {
          return ( n* Fact(n-1));
    }
    }
    

    Winding Process:

    Function called Function return

    Fact(6) 6*Fact(5)
    Fact(5) 5*Fact(4)
    Fact(4) 4*Fact(3)
    Fact(3) 3* Fact(2)
    Fact(2) 2* Fact(1)
    Fact(1) 1* Fact(0)
    Terminating Point
    Fact(0) 1

    Unwinding Process

    Fact(1) 1*1
    Fact(2) 2*1
    Fact(3) 3*2*1
    Fact(4) 4*3*2*1
    Fact(5) 5*4*3*2*1
    Fact(6) 6*5*4*3*2*1

    Compile-Time Version

    // template for Base Condition
    template <>
    struct Fact<0>
    {
       enum 
      { 
          factVal = 1 
       };
    };
    
    template <int n>
    struct Fact
    {
       // Recursion call by linear method
       enum
      { 
    value = n * Fact<n - 1>::factVal
       };
    }; 

    To test it how it’s working at compile time, just call
    cout << Fact<-1>::factVal ;
    And compile it then compiler error will come, because no template for -1.

    2. Binary Recursion: Binary Recursion is a process where function is called twice at a time inplace of once at a time. Mostly it’s using in data structure like operations for tree as traversal, finding height, merging, etc.

    Example: Fibonacci number

    Run Time Version Code:

    int FibNum(int n)
    {
       // Base conditions
          if (n < 1)
             return -1;
          if (1 == n || 2 == n)
            return 1;
    
       // Recursive call by Binary Method
         return FibNum(n - 1) + FibNum(n - 2);   // At a time two recursive function called so               
                                                                          //   binary
    }

    Compile Time Version Code

    // Base Conditions
    template<>
    struct FibNum<2>
    {
       enum { val = 1 };
    };
    template <>
    struct FibNum<1>
    
    {
       enum { val = 1 };
    };
    
    // Recursive call by Binary Method
    template <int n>
    struct FibNum
    {   
       enum { val= FibNum<n - 1>::val + FibNum<n - 2>::val };
    };

    3. Tail Recursion: In this method, recursive function is called at the last. So it’s more efficient than linear recursion method. Means you can say termination point will come(100%) only you have to put that condition.

    Example: Fibonacci number

    Run Time Version Code:

    int FibNum(int n, int x, int y)
    {   
       if (1 == n)    // Base Condition
       {
          return y;
       }
       else        // Recursive call by Tail method
      {
          return FibNum(n-1, y, x+y);
       }
    }
    

    Compile Time Version Code

    template <int n, int x, int y>
    
    struct FibNum
    {
       // Recursive call By tail method
       enum 
      { 
            val = FibNum<n-1, y, (x+y)>::val
       };
    };
    
    // Base Condition or Termination 
    template<int x, int y>
    struct FibNum<1, x, y>
    {
       enum 
    
  • I would like to know how to write source code for this assignment:
    Write a new “Currency Conversion” program, with a title, to accept one input currency, which is error checked as a valid entry, and then display its equivalency in US dollars. For example: 300 Canadian Dollar = 189.19 US Dollar.

  • i find problems in handling functions and arguments my programs when run give me an error reading declaration syntax error can anyone help me

  • multi functional programes help alot in easy understanding of the programe and they enable you to break down the programe into smaller parts i myself i enjoy using them in my programes

  • i have seen passing on constants and variables as to another function from the main but what about when the main passes on a constant or a variable to the other function and then it has ti use it and return a value to the main function, is it possible?

  • indu says:

    function called min(x,y)that returns the smaller of two double values

  • thrish says:

    .phelp nmn po. my project kme. ang problema ayaw bumlik nung mga value, anong gagawin ko?? my alam po ba kau program. ung pang hyperlink, halimbawa, pag a ung pinundot, pupunta sa new page, mala gnun po.. salamat po sa tutulong, badly needed.. salamat.

  • Anu says:

    Should every C program use return 0;before the closing braces of a block?

    • Nila Kamal Nayak says:

      no
      every c function doesn’t return 0
      but a function can return value is integer
      generally 1(when function is executed successfully),-1(Abnormal termination) and 0 (when nothing is retuned)

      if we return a integer 76 or 68 it does not matter

      actually
      why a function should return a value?
      ans- if a function does not return value then how can processor knew that that functionality is finished and other function is to executed so a function should return a value which is by default integer if not mentioned as void

    • naveen says:

      When we use int main() in the place of main we must write return0; at the end of the program. Not for all the programs

  • adeth usares says:

    can u pls give me some sample program with source code of function?thanks…

  • deepak tapa says:

    type of the funtion should be properly declared

  • imran says:

    what is type of main() function in c?
    is it predefined or userdefined?
    if it is predefined then where is it stored in the files of c?

  • [...] about functions and how they work for exemple: Functions in C Programming – C and C++ Programming Resources In your code, try to see what can you put in a function and apply what you've learn reading [...]

  • ayesha says:

    plz help me how can i make this program
    calculate the average of num by using function that reading the num to be averaged, calculating their sum as they are reading the second funcion should complete the deviation of each num about the average

  • liban says:

    write program in C to do the basic arithmethic operation (addition, subtraction, multiplication and division). Each operation must have it’s own function. The main function must call all the functionwith the same data set.
    and write its psedu code?

  • ohsocordy says:

    I need help with this. I have an idea of what to do just don’t know how to start implementing it and my text book is absolutely useless.

    Write a function called “parkingCharge” that, given the type of vehicle (c for car, b for bus, t for truck) and the hours a vehicle spent in the parking lot, returns the parking charge based on these rates: car = $2 per hour, bus = $3 per hour, truck = $4 per hour.

  • guna182003 says:

    plz help me how can i can solve this program.

    suppose x,y,z are floating-point variables that have been assigned the values x=8.8, y=3.5, z=5.2 . determine the value of each of the following arithmetic expressions:

    a) x%y

  • guna182003 says:

    hello all. I am still new on this programme (C source code). Need your help on this.

    int i=8, j=5;
    float x=0.005, y=-0.01;
    char c=’c', d=’d';

    determine the value of each of the following expression. use the values initially assigned to the variables for each expressions.

    (a) (3*i-2*j)% (2*d-c)

    (b) 2*((i/5)+(4*(j-3))%(i+j-2))

  • mattwilli92 says:

    can someone help me real quick

  • Vani says:

    please help on this program am really confusion to solve

    From the given input array remove the negative elements and then sort the remaining array
    elements, store that into the output array. Consider input1 is array elements and input2 is array
    size.

  • naveen says:

    What are the differences between c and c++? What are the extra features of c++?


Leave a Reply

You must be logged in to post a comment.