# Thread: Need Help With Functions

1. ## Need Help With Functions

I am a college student studying c programming and i need help with using functions because when i create a program i insert all the code into the main function which is very difficult to work with...

I wondering if there was anyone who could help me understand the basics of using functions...

Thank You.

2. One of the first functions we used is here.

Take a look how we take the code from main and put it in the function.

If main is a bit difficult to understand, replace main with this
Code:
```int main(void)
{
int i = 5;
int result;
result = isPrime(i);
if(result == 1)
{
printf("It is prime\n");
}
else
{
printf("It is not\n");
}

return 0;
}```

3. Originally Posted by Hackstorix
I wondering if there was anyone who could help me understand the basics of using functions...
A function should be anythign that represents a logical unit.

E.g. the area of a circle, or other geometrical shape. The maximum, minimum, or average in a list. Loading a data base of employees from disk. Paying the employees. Saving the updated data with the new pay information back to disk.

There are some tricks. Don't be afraid to softcode a fucntion parameter, then hardcode the argument. Say you input a line consisting of a list of numbers, separated by commas. You can count the numbers by counting the commas.
The function

Code:
```int strcount(char *str, char ch)
{
while(*str)
{
if(*str =ch)
str++;
}
}```
will do this for you. However the comma will be hardcoded, higher up.

Code:
`Nnumbers = strcount(line, ',') + 1;`
The second trick is to use pointers a lot. Virtually all of you C functions will pass information to and from caller, using pointers,usually pointers to structures or arrays of structures.

Also use malloc() a lot. Mostly there won't be a natural limit to the
amount of data you are operating on. By using malloc(), you allow the program to grow, until the machine runs out of memory.