5 Computer -- Programming II

Define functions. Write the advantages of function with program example.

Define functions. Write the advantages of function with program example.

function is basically a block of statements that performs a particular task. Suppose a task needs to be performed continuously on many data at different points of time, like one at the beginning of the program and one at the end of the program, so instead of writing the same piece of code twice, a person can simply write it in a function and call it twice. And after the execution of any function block, the control always comes back to the main() function.

Here are several advantages of using functions in your code:

  • Use of functions enhances the readability of a program. A big code is always difficult to read. Breaking the code in smaller Functions keeps the program organized, easy to understand and makes it reusable.
  • The C compiler follows top-to-down execution, so the control flow can be easily managed in case of functions. The control will always come back to the main() function.
  • It reduces the complexity of a program and gives it a modular structure.
  • In case we need to test only a particular part of the program we will have to run the whole program and figure out the errors which can be quite a complex process. Another advantage here is that functions can be individually tested which is more convenient than the above mentioned process.
  • A function can be used to create our own header file which can be used in any number of programs i.e. the reusability.



For eg:

In the following program, the function can be called / reused many times instead of having to write the same codes again and again.

#include<stdio.h> int sum(int,int); // function prototype int main() { int a,b,s; printf("Enter two integers:"); scanf("%d%d",&a,&b); s=sum(a,b); // fucntion call printf("Sum = %d",s); return 0; } int sum(int x,int y) // function definition { return (x+y); // return statement }


More questions on Programming II

Differentiate between structure and union.

Structures in Cis a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record.

Defining a structure:To define astructure, you must use thestructstatement. The struct statement defines a newdata type, with more than or equal to one member. The format of the struct statement is as follows:

struct [structure name] { member definition; member definition; ... member definition; }; (OR) struct [structure name] { member...
Close Open App