Programming for Problem Solving (3110003)

BE | Semester-1   Winter-2019 | 07-01-2020

Q5) (c)

Explain the function definition, function prototype and function call with relative example.

  • A function is a block of code that performs a specific task.
  • It has a unique name and it is reusable i.e. it can be called from any part of a program.
  • Parameter or argument passing to function is optional.
  • It is optional to return a value to the calling program. Function which is not returning any value from function, their return type is void.
  • While using function, three things are important.

Function Declaration

  • Like variables, all the functions must be declared before they are used.
  • The function declaration is also known as function prototype or function signature. It consists of four parts,
    1. Function type (return type)
    2. Function name
    3. Parameter list
    4. Terminating semicolon
Syntax:
FunctionName (Argument1, Argument2,...);
Example:
int sum(int , int);
In this example, function return type is int, name of function is sum, 2 parameters are passed to function and both are integer.

Function Definition

  • Function Definition is also called function implementation.
  • It has mainly two parts.
    1. Function header: It is the same as function declaration but with argument name.
    2. Function body: It is actual logic or coding of the function.

Function Call

  • Function is invoked from main function or other function that is known as function call.
  • Function can be called by simply using a function name followed by a list of actual argument enclosed in parentheses.

Syntax or general structure of a Function

 FunctionName (Argument1, Argument2,...) { 
	Statement1; 
	Statement2; 
	Statement3; 
} 

An example of function

 
#include <stdio.h>
int sum(int, int); 
void main() { 
int a, b, ans; 
scanf(“%d%d”, &a, &b);
ans = sum(a, b);
printf(“Answer = %d”, ans); 
} 
int sum (int x, int y) { 
int result; 
result = x + y; 
return (result); 
}