Functions in C

(a) What is Function? Write briefly its importance.

C functions are basic building blocks in a program that performs some action. All C programs are written using functions to improve re-usability.

Importance of Functions
Functions facilitates the programmers to break a large programming problem into smaller parts. Each function is a complete unit. They can call each other to provide their services. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. Debugging becomes easy while using Functions.

(b) Write any three differences between local and global variable.

Local Variable
1. Local variables are declared within a function.
2. Local variables can be used only in the function in which they are declared.
3. Local variables are destroyed when the control leaves the function.

Global Variable
1. Global variable are declared outside any function.
2. Global variables can be used in all functions.
3. Global variables are destroyed when the program terminates.

(c) What is the scope of local variable?

The area where a variable can be accessed is known as scope of variable. Local variable can be used only in the function in which it is declared. If a statement accesses a local variable that is not in scope, the compiler generates a syntax error.

(d) What is function declaration or function prototype?

Function declaration is a model of function. It is also known as function prototype. It provides information to compiler about the structure of the function to be used in program. It ends with a semicolon. Function prototypes are usually placed at the beginning of the source file just before the main() function. It consists of function name, function return type and number and types of parameters.
The syntax of function prototype is as follows:
Return-type Function-name (parameters);

(e) Write a note on local variables.

These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
The syntax of declaring a local variable is as follows:
auto data_type identifier;

(f) Write a program to print the table of a number on the screen. Input a number from the keyboard and print its table using the function.

#include
#include
void table(int n);
void main()
{
int num;
printf(“Enter a number: “);
scanf(“%d”,&num);
table(num);
getch();
}
void table(int n)
{
int c;
for(c=1;c<=10;c++)
{
printf(“%d%d=%d\n”,n,c,nc);
}
}

(g) Write a program that displays a message “Best of luck” on the screen using function.

#include
#include
void show (void);
void main()
{
show();
getch();
}
void show()
{
printf(“Best of luck.”);
}