"Learn C programming!" 6-1 Introduction |
6-1 Introduction
As we said in lesson 1, a C program consists of one or more functions. main() is a special function because program execution starts from main() function.
A function is combined of a block of code that can be called or used anywhere in a program by calling function name. Body of a function starts with { and ends with } . As you see this is the same as main function in our previous programs.
Example below shows how we can write a simple function.
Example 6-1:#include<stdio.h>
/*Function prototypes*/
myfunc();main()
{
myfunc();
}myfunc()
{
printf("Hello, this is a test\n");
}In above function we have put a section of program in a separate function. Function body can be very complex.
After creating a function we can call it using its name. Functions can call each other. Even a function can call itself. This is used in recursive algorithms. But must be sure that this will not enter our program in an infinite loop.
Most of C programming language commands are functions. For example printf is a function that accepts one or more arguments and do printing.
-----------------------------------------------------------------------------
6-2 Reasons for using functionsThere are many reasons for using functions.
a. A part of code may be reused many times in different parts of program.
b. Program will be divided to separate blocks. Each block will do a special job. Understanding and design of programs will be simplified in this way.
c. A block of code can be executed with different numbers of initial parameters. These parameters are passed to
function with arguments.Assume we want to read scores of students from a file, calculate their average and print results. If we want the
program to be written just inside main() function block we will have a large main() function. But if we spread
the program to different functions, we will have a small main() function.main()
{
readscores();
calculate()
writetofile();
printsresults();
}Now lets look at this example:
Example 6-2:
#include<stdio.h>
#include<stdlib.h>add();
subtract();
multiply();main()
{
int choice;while(1)
{
printf("\n\nMenu:\n");
printf("1- Add\n2- Subtract\n");
printf("3- Multiply\n4- Exit");
printf("\n\nYour choice -> ");
scanf("%d",&choice);
switch(choice)
{
case 1 : add();
break;case 2 : subtract();
break;case 3 : multiply();
break;case 4 : printf("\nProgram Ends. !");
exit(0);default:
printf("\nInvalid choice");}
}
}add()
{
float a,b;printf("\nEnter a:");
scanf("%d",&a);
printf("\nEnter b:");
scanf("%d",&b);printf("a+b=",a+b);
}subtract()
{
float a,b;printf("\nEnter a:");
scanf("%d",&a);
printf("\nEnter b:");
scanf("%d",&b);printf("a-b=",a-b);
}
multiply()
{
float a,b;printf("\nEnter a:");
scanf("%d",&a);
printf("\nEnter b:");
scanf("%d",&b);printf("a*b=",a*b);
}-----------------------------------------------------------------------------
6-2 Function argumentsFunctions are able to accept initial values for some variables. These values are accepted as function arguments.
Example 6-3:
#include<stdio.h>
/* use function prototypes */
sayhello(int count);
main()
{
sayhello(4);
}sayhello(int count)
{
int c;for(c=0;c<count;c++)
printf("\nHello");
}
In above example we have called sayhello() function with the parameter 4.Function receives an input value and assigns it to count variable before starting execution of function body.
sayhello() function will print a message for count times on the screen.
Pay attention that we must use a function prototype before we can call a function inside main() or another function in our program. We usually insert these prototypes after precompiler commands in our program. This is usually before main() function at the top of our program.
You can copy function header exactly for prototype section.
If you do not use prototypes of your functions you will get an error in most of new C compilers. This error mentions that you need a prototype for each of your functions.
-----------------------------------------------------------------------------
6-3 Function return valuesIn mathematics we generally expect a function to return a value. It may or may not accept arguments but it always returns a value.
y=f(x)
y=f(x)=x+1
y=f(x)=1 (arguments are not received or not important)In C programming language we expect a function to return a value too. This return value has a type as other values in C. It can be integer, float, char or anything else. Type of this return value determines type of your function.
Default type of function is int or integer. If you do not indicate type of function that you use, it will be of type
int.As we told later every function must return a value. We do this with return command.
Sum()
{
int a,b,c;
a=1;
b=4;
c=a+b;
reurn c;
}Above function returns the value of variable C as the return value of function.
We can also use expressions in return command. For example we can replace two last lines of function with return a+b;
If you forget to return a value in a function you will get a warning message in most of C compilers. This will warn you that your function must return a value. Warnings do not stop program execution but errors stop it.
In our previous examples we did not return any value in our functions. For example you must return a value in main() function.
main()
{
.
.
.
return 0;
}Default return value for an int type function is 0. If you do not insert return 0 or any other value in your main()
function a 0 value will be returned automatically.-----------------------------------------------------------------------------
6-4 void return valueThere is another type of function yet. It is void type. Void type function is a function that does not return a
value.For example you can define a function that does not need a return value as void.
void test ()
{
/* fuction code comes here but no return value */
}void functions cannot be assigned to a variable because it does not return value. So you cannot write:
a=test();
Using above command will generate an error.
In next lesson we will continue our study on functions. This will include function arguments and more.
----------------------------------------------------------Exercises:
1- Write a complete program that accepts a decimal value and prints its binary value. Program must contain a function that accepts a decimal number and prints the binary value string.
2- Write a complete program that asks for radius of a circle and calculates its area using a function with return value of float type.
===========================================