C-Program (function & pointer)

We can write codes in C-program without using functions but when we start working on larger projects, using function makes our work easier and simpler. So, learning about function and adding function to our inventory makes us a better coder in the long term.

Functions: 

Functions are the self-contained program that contains several block of statement which performs the defined task. In C language, we can create one or more functions according to the requirements.Usually, In C programs flows from top left to right bottom of main() functions. We can create any number of functions below that main() functions. These function are called from main() function. The proper steps to use a function is :

a) Declare a function

b) Call statement

c) Definition of function.

After the function is called from the main(), the flow of control will return to the main() function.

 Example of using function in a program:
WAP to calculate simple interest using function

 #include<stdio.h>
 int interest(void); //function declaration 
int main() 
{
 int si;
 si=interest(); //function call
 printf("Simple interest is %d\n",si);
 return 0; 
int interest() //function definition 
{
 int p,t,r,i; 
 printf("Enter Principal, Time and Rate");
 scanf("%d %d %d",&p,&t,&r); 
 i=(p*t*r)/100;
 return i; //function return value
 }


Advantage:


1. Program development will be faster.

2. Program debugging will be easier and faster.

3. Big programs can be divided into smaller module using functions.

4. Use of functions reduces program complexity.

5. Several developer can work on a single project.


Pointer :

Pointers in C are similar to as other variables that we use to hold the data in our program but, instead of containing actual data, they contain a pointer to the address (memory location) where the data or information can be found.

These is an important and advance concept of C language since, variables names are not sufficient to provide the requirement of user while developing a complex program. However, use of pointers help to access memory address of that entities globally to any number of functions that we use in our program.

Importance of Pointer :

While using several numbers of functions in C program, every functions should be called and value should be passed locally. However, using pointer variable, which can access the address or memory location and points whatever the address (memory location) contains.

Pointer declaration

Data_type *variable_name

Eg:  int *age;

Advantages :

1. It helps us to access a variable that is not defined within a function.

2. It helps to reduce program length and complexity i.e. faster program execution time.

3. It is more convenient to handle datas.


Example :

#include<stdio.h>
 int main() 
 int p,*ptr;
 printf("Enter any number");
 scanf("%d",&p);
 ptr =&p; 
 printf("Value is %d\n",*ptr);  
}


Comments

Popular Posts