CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

Function Introduction


Description

Function in C language is a block of code that performs a specific task. Function name which is unique, indicates type of task it is performing and can be executed several times in different parts of the program as needed. There are basically two types of functions : built-in (library) and user-defined functions.

Built-in functions like printf, clrscr, getch and many more other functions, which are already defined in standard library files like stdio.h, conio.h, time.h etc. User-defined functions are defined by the user, example is the main function in C program.

Declaring function

Return data-type function_name()
{
  //function body
}

Advantages

  • Dividation of big programs into small parts.
  • Reduction of program size.
  • Easy to write and locate errors in the program.

Types

  • Built-in(library) functions like clrscr(), getch(), printf(), scanf() etc.
  • User-defined function is a self written block of statements in the program. Eg : Functions written in below source code program like main(), goodmorning(), goodafternoon() and goodevening().

Source code

  • //Implementing function
  • #include <stdio.h>
  • #include <conio.h>
  • void goodmorning(); //function declaration
  • void goodafternoon();
  • void goodevening();
  • void main()
  • {
  • clrscr();
  • goodmorning();
  • goodafternoon();
  • goodevening();
  • getch();
  • }
  • void goodmorning() //function definition
  • {
  • printf("\nGood morning sir");
  • }
  • void goodafternoon()
  • {
  • printf("\nGood afternoon sir");
  • }
  • void goodevening()
  • {
  • printf("\nGood evening sir");
  • }

Program working steps

  • First line of the program is the comment to indicate what the program is all about.
  • 2nd and 3rd line are preprocessor directive statements which include definition of printf, clrscr, getch function.
  • Declaration of function which we are going to use and their return data-type void.
  • Void main function is the function where program execution starts.
  • Clrscr() function to clear the screen like cls in windows and clear in linux.
  • Line no.12 calls or invokes goodmorning() function whose definition of function is written on line no.17. It implements the function body and returns nothing as the function is declared void.
  • Similarly other functions goodafternoon(), goodevening() are called and executed.
  • getch() function which takes input from the user but doesn't prints on the screen.

Tip Box

Naming function

Function name should indicate the purpose of the code.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved