Computersnyou

C Programming–Functions

Posted on  4/13/2012
For a procedural language like C , functions are very important. Functions give you a way in which you can use your important code without retyping it again. It makes your code shorter and easier to follow.Functions are identified by ‘()’.
Syntax for creating a function



return_type  function_name ()
{
//body;
}
Return Type can be :
int
float
double
char
array
string
structure
pointer
void

Function Name has to be a combination of :
digits [0-9]
alphabets [a-z,A-Z]
underscore [ _ ]
Note : Name of a function never begin with digits.

Arguments can be :
int
float
double
char
array
string
void
pointer
Note : You can have no argument or one or more  arguments . If you don’t have any argument that means you are not passing any value.

Body
Your Important Code

Illustration with Example
# include
# include

int add (int a,int b)
{
a + b;
return (a+b) ;
}
void main ()
{
int sum = 0,num1,num2;
printf(“Enter Your  Number :”);
scanf(“%d”,&num1;);
printf(“nnEnter Your 2nd Number :”);
scanf(“%d”,&num2;);
sum = add(num1,num2);
printf(“nn The Sum is %d”,sum);
getch();
}

Output
Enter Your 1st Number : 5
Enter Your 2nd Number : 6
The Sum is 11

In the above program we have two functions main() and add().
First we have add() function in which we are performing the addition.
In the add() function we have two arguments (int a , int b). argument a contains the value of num1 and argument b contains the value of num2. Finally, we are returning the added value of a and b which is of type int .
In the main() function we are taking the two inputs from the users and then storing it in two variables num1 and num2 using printf() and scanf() functions . Then making a call to function add() and storing the value returned by the add() function in the variable sum .
And finally we printing the sum on the screen with a proper message .
If you have any query in any part then do leave us a comment . Thanks !!!


  • Home
  • About