You are on page 1of 8

Introduction to Programming

Functions

Functions
Functions help to modularise programs Modularising means breaking a complex program into manageable units or blocks Modularising programs make them easier to write, understand, test and maintain functions reduce the duplication of code

Modularisation
void main() {

void main() {function1(); function2(); } function1() { } function2()

{ }

C Functions
return_type functionName (type arg1, type arg2,...type argn)

{ /* function body where the data is processed*/ return return_value; } If return_type is ommited C defaults to int

Function Example
data RETURNED data IN

int square (int num) { int answer = num * num; return answer; }

Calling Functions
#include <stdio.h> void main() { int number = 4; printf( The number to be squared is %d, number); int answer = square(number); /*calls the method Square */ display(answer); /*calls the method Display */} int square(int x) { /*definition of the method Square */ return x * x; } void display(int num) { /*definition of the method Display */ printf( The number squared is %d, num); } }

C function Definitions
return types functions that return values

return type

method name
int getPrice() { return price; }

parameter list (empty) return statement

start and end of method body (block)

C function Definitions
void functions that do not return a value
return type (void) method name
void insertMoney(int amount) { balance = balance + amount; }

parameter

assignment statement

field being changed


start and end of method body (block)

You might also like