You are on page 1of 5

Muhammad Ali

muhammadallee@gmail.com

Functions – Focus on Verbs!


What
 “A portion of code within a larger program, which performs a specific task and can be relatively
independent of the remaining code.” – Wikipedia

Why
 Makes code easier to understand and solve the problem.
 We can reuse our code!
 They make it easier to track errors in the code.
 Allows you to develop in parallel.

When
 Always!
 To break the problem into smaller pieces.
 Ideally a function should perform only one task!
 Verbs in your problem statement are candidates for functions. Choose among them!

How
Steps involved

1. Declaration

2. Definition

3. Call

Missing any of the above steps (except 3) will result in error(s). Try to follow the same sequence of
steps.

General Syntax

ReturnType functionName ( parameters )

Where

 Return Type is any valid C++ data type and ‘void’.


 functionName is any unique name in the program.
 parameters is a list of values that we can pass to a function

Important: Declare before use.


Page 1 of 5
1. Declaration

(Write the declarations before the main function).

void anyFunction();

int anotherFunction();

void oneMoreFunction(int num);

2. Definition

(Write the definitions after the main funciton).

void anyFunction()

cout << ”Inside anyFunction()”;

void oneMoreFunction(int num)

cout << ”Inside oneMoreFunction(). Value of num is:” << num;

3. Call

int main( )

anyFunction();

oneMoreFunction();

return 0;

Page 2 of 5
Complete Example

Description: A function that returns the sum of two integer values.

Inputs: Two integer values.

Outputs: Sum of the two input integer values.

Analysis Steps:

1. Add the input integer values and return their sum.

Code:

/*

Author: Muhammad Ali

Date: April 19, 2008

Description: A program that calculates the sum of two integer values.

*/

#include <iostream>

using namespace std;

/*

Input: Two integer values.

Output: Sum of the two input integer values.

*/

int sum(int num1, int num2);

Page 3 of 5
int main()

cout << “\nProgram to calculate sum of two numbers\n”;

cout << “Enter an integer value:”;

int num1 = 0;

cin >> num1;

cout << “Enter another integer value:”;

int num2 = 0;

cin >> num2;

int result = sum(num1, num2);

cout << “Sum of the values is:” << result;

return 0;

/*

Input: Two integer values.

Output: Sum of the two input integer values.

*/

int sum(int num1, int num2)

int result = 0;

Page 4 of 5
result =num1 + num2;

return result;

Page 5 of 5

You might also like