Skip to main content

C Programming #9 (Functions)

Function is a self contained block of statement that perform a coherent task of some kind.
In simple word to write a C Program in a professional manner and in a clean way it is must to use  functions.
Function is used in the C program where you want to do a specific kind of work always.
Example:
#include<stdio.h>
void message();
int main()
{
message();
printf("This is 1\n");
return 0;
}
void message()
{
printf("This is 2\n");
}
Output:
This is 2
This is 1
Now you must be wondering that This is 1 Should come first but I have made use of function and designed how it should appear.
In this program I have used Message() three times

  • void message()
This is for function prototype declaration It is necessary to mention prototype of every function that we intend to define in a program
  • message()
This is the function call means it call it's own function and main() is temporarily suspended till the control is in function message after that the control get back to main()
  • void message()
This is the function definition means when the control was in message() the statement inside this was performed in this case it was printf but you can use any thing like if,for,while etc..
  1. C Program is the collection of function.
  2. If a C program contains only one function it must be main as C program begins with main()
  3. A function can be called any number of time

Passing values between function

Till now we have seen normal function calling and now we will see if we have to give some values to the function and do the program what we have to do.

Now we are going to be more flexible with function
Example:
#include<stdio.h>
int calsum(int x, int y, int z);
int main()
{
int a,b,c,sum;
printf("Enter any three numbers\n");
scanf("%d%d%d",&a,&b,&c);
sum=calsum(a,b,c);
printf("sum=%d\n",sum);
return 0;
}
int calsum(int x, int y, int z)
{
int d;
d=x+y+z;
return(d);
}
In this program I have given the value of a b c to x y z in the function calsum and returned the answer d to the main function

Note:Any questions can be asked here related to tech so feel free to ask to get better idea of tech and subscribe if you want to be connected here. 

Comments