Friday, 30 September 2011

Function in C\C++

Functions


All languages have a construct to separate and package blocks of code. C uses the "function" to package blocks of code. This article concentrates on the syntax and peculiarities of C functions. The motivation and design for dividing a computation into separate blocks is an entire discipline in its own.

A function has a name, a list of arguments which it takes when called, and the block of code it executes when called. C functions are defined in a text file and the names of all the functions in a C program are lumped together in a single, flat namespace. The special  function called "main" is where program execution begins. Some programmers like to begin their function names with Upper case, using lower case for variables and parameters, Here is a simple C function declaration. This declares a function named  Twice which takes a single int argument named num. The body of the function computes the value which is twice the num argument and returns that value to the caller.

/*
Computes double of a number.
Works by tripling the number, and then subtracting to get back to double.
*/

static int Twice(int num)
{
   int result = num * 3;
   result = result - num;
   return(result);
}


How to use function ?


#include<stdio.h>
#include<conio.h>
int header();
int sum; /* This is a global variable */
int main( )
{
int index;
header(); /* This calls the function named header */
for (index = 1;index <= 7;index++)
square(index); /* This calls the square function */
ending();
getch(); /* This calls the ending function */
}


header() /* This is the function named header */
{
sum = 0; /* initialize the variable "sum" */
printf("This is the header for the square program\n\n");
}


square(number) /* This is the square function */
int number;
{
int numsq;
numsq = number * number; /* This produces the square */
sum += numsq;
printf("The square of %d is %d\n",number,numsq);
}
ending() /* This is the ending function */
{
printf("\nThe sum of the squares is %d\n",sum);


}

No comments:

Post a Comment