Learnem, Computer education over Internet - Since the year 2000
Home Ebook E-learning Courses Free E-books Login Discussion Boards
Lesson 6 : More on Functions

More on Functions

In lesson 1 we that each C program consists of one or more functions. main() is a special function because program execution starts from it.

A function is combined of a block of code that can be called or used anywhere in the program by calling the name. Body of a function starts with ‘{‘ and ends with ‘}’ . This is similar to the main function in our previous programs. Example below shows how we can write a simple function.

Example 6-1: example6-1.c

#include<stdio.h>

/*Function prototypes*/
myfunc();

main()
{
  myfunc();
  system("pause");
}

myfunc()
{
  printf("Hello, this is a test\n");
}

In above example we have put a section of program in a separate function. Function body can be very complex though. After creating a function we can call it using its name. Functions can also call each other. A function can even call itself. This is used in recursive algorithms using a termination condition (to avoid the program to enter in an infinite loop). For the time being do not call a function from inside itself.

By the way pay attention to “function prototypes” section. In some C compilers we are needed to introduce the functions we are creating in a program above the program. Introducing a function is being called “function prototype”.

Most of C programming language commands are functions. For example “printf” is a function that accepts one or more arguments and does printing. Bodies of these functions are defined in C library files which are included in your C compiler. When you use a C function, compiler adds its body (where the actual code of the function exists) to your program and then creates the final executable program. Function prototypes (introduction before use) of internal C functions is in header files (i.e stdio.h, …) which are included at the top of a program.

Reasons for using functions

There are many reasons for using functions.

·         You may need to reuse a part of code many times in different parts of a program.

·         Using functions, program will be divided to separate blocks. Each block will do a specific job. Designing, understanding and managing smaller blocks of code is easier. 

·         A block of code can be executed with different numbers of initial parameters. These parameters are passed to function with function arguments.

Assume we want to read scores of students from a file, calculate their average and print results. If we write the program just inside a single main() function block we will have a large function. But if we spread the program functionality to different functions, we will have a small main() function and several smaller functions which perform their specific task.

main()
{
Read_scores();
calculate()
write_to_file();
print_results()
}

Now let’s look at this example:

Example 6-2: example6-2.c

#include<stdio.h>
#include<stdlib.h>

add();
subtract();
multiply();

main()
{
char choice;
while(1)
  {
  printf("\nMenu:\n");
  printf("1- Add\n2- Subtract\n");
  printf("3- Multiply\n4- Exit");
  printf("\n\nYour choice -> ");
  choice=getch();

  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("%f",&a);
printf("\nEnter b:");
scanf("%f",&b);
printf("a+b=%f",a+b);
}

subtract()
{
float a,b;

printf("\nEnter a:");
scanf("%f",&a);
printf("\nEnter b:");
scanf("%f",&b);
printf("a-b=%f",a-b);
}

multiply()
{
float a,b;
printf("\nEnter a:");
scanf("%f",&a);
printf("\nEnter b:");
scanf("%f",&b);
printf("a*b=%f",a*b);
}

Function arguments

Functions are able to accept input parameters in the form of variables. These input parameter variables can then be used in function body.

Example 6-3: example6-3.c

#include<stdio.h>

/* use function prototypes */
sayhello(int count);

main()
{
sayhello(4);
system("pause");
}

sayhello(int count)
{
int c;
for(c=0;c<count;c++)
  printf("Hello\n");
}

In above example we have called sayhello() function with the parameter “4”. This function receives an input value and assigns it to “count” variable before starting execution of function body. sayhello() function will then print a hello message ‘count’ times on the screen.

Again we use a function prototype before we can call a function inside main() or another function in our program. As you see these prototypes are put after pre-compiler commands (those starting with # sign), before main() function at the top of our program. You can copy function header from the function itself for the prototype section. However do not forget that function prototype needs a semicolon at its end while in function itself it does not.

If you do not put prototypes of your functions in your programs you might get an error in most of new C compilers. This error mentions that you need a prototype for each of your functions.

Function return values

In 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 earlier 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 message 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. If you are planning to return an int value in your function, it is seriously preferred to mention the return value in your function header and make.

“void” return value

There is another “void” type of function in C language. Void type function is a function that does not return a value. 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 program that accepts a decimal value and prints its binary value. Program should have a function which accepts a decimal number and prints the binary value string.

2. Write a program that asks for radius of a circle and calculates its area using a function with return value of float type.


 

Next Lesson


Links
Discussion Boards
Paid Ebooks
Free Ebooks
Testimonials
Faq
Contact
About us
Course Pages
Web Design
C Programming
Free Tutorials
Web Design
PHP Web Prog.
C Prog.
ASP Web Prog.
Free Ebooks
Web Design Ebook
C Prog. Ebook
Free Support
Support for e-books and free courses are offered through CourseFarm website. In order to use the CourseFarm website, You need to create a free member account on it (see main page of the website).

Web Design in 7 Days Course Page

Programming in C in 7 Days Course Page

PHP Web Programming in 7 Days Course Page

Support on CourseFarm is provided by authors of the e-books themselves. You may also contact them on the website for your possible questions.
Home | Educational E-books | Online Courses | Free Books | Discussion Boards
Testimonial | Contact us | FAQ | About us
Society50 Asian Social Network | Science and Tech Blogs | Asia Weblog | CupidB Free MatchMaker

© 2000-2010 Learnem.com, All Rights Reserved. Last Update April, 2011.