Wednesday, October 28, 2015

Code in C : Function

I will explain about function in C.~~~~ \(^0^)/

What is function? 

Function is the place where every activity occurs in C, actually we have been using function when we use C programming language. Because "int main () {}" that we always use is a function. The different with other function, "int main(){}" is the main "activity" that will be executed.

There is also Procedure in C.... =w=

What is the difference??

Function usually returns value, unlike procedure.
Procedure doesn't have to return a value
Procedure always uses "void" and it doesn't have to have argument.
Function can have any type of argument/parameter or return value, depend on the type..
If you declare the function or procedure first before main(), then you don't have to add declaration for function or procedure. else ~, then you need pre-declaration to the function .~


//Example of Procedure:
#include<stdio.h>
void printline(){
printf("_________");
}

//In this procedure, It will print "______" if you execute it in function main()...

//Example of Function:
int multiply(int a, int b){ // inside () are argument/parameter
int result=(a*b); //or you can write return a*b;
return result; //this is return statement
}

int main(){
int x,y;
scanf("%d %d",&x,&y);
printline();
printf("%d",multiply(x,y));
printline();
}


If you execute this code, you can see that we only need to call procedure and function name to execute them. 
When printf command executed ,x and y will go to function as the argument/parameter (a and b) and  it will give the "result" as return value. 
You will get an integer return value from multiplying x with y because the function type is "Int".


Why do we use function?

We use function to simplify the code that we write, so we don't have to write it again and again.
We only need write the function, and it will be executed. 

Function is very useful, because if you need change something in program that have a lot of code, you only need change something inside the function (if you use function =w=)

You can put any code in function or procedure as long as you follow the structure that is:

Function:
type of function__name of function (type of parameter _any parameter){
body of function : any code
}
Procedure:
void__name of procedure ((type of parameter _any parameter) or none){
body of procedure : any code
}

You can combine function and procedure with anything.
For example, procedure to input array:

#include <stdio.h>
void inputarray(int array[],int limit){//using pointer?? xD
int x;
for(x=0;x<limit;x++){
scanf("%d",&array[x]);
}
}
int main(){
int score[100];
int students;
scanf("%d",&students);
inputarray(score,students);// pointer?? xD
}

And many things~~~ =w=

Thank you for watching~~ ^__^


No comments:

Post a Comment