Functions

Chapter 11 · Tamil Nadu State Board

  • 18 min read
  • 6-question quiz

Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content

In short

This lesson explains how functions divide C++ programs into manageable, reusable parts and describes built-in and user-defined functions. It shows how library functions handle character, string, and mathematical operations, while user-defined functions can receive arguments and return values. The lesson compares ways of passing arguments and explains recursion, inline functions, and variable scope. These ideas help students write programs that are easier to organise, reuse, understand, and test.

Written by AI from this lesson. How we check it

Key points

  • Functions split large programs into smaller parts that are easier to understand, test, and debug.
    From your textbook
    “Functions reduce the size and complexity of a program, makes it easier to understand, test, and check for errors.”
  • C++ functions may be ready-made library functions or functions created by the programmer.
    From your textbook
    “Functions can be classified into two types, 1. Pre-defined or Built-in or Library Functions 2. User-defined Function.”
  • Header files provide information and definitions needed to use library functions.
    From your textbook
    “Header files provide function prototype and definitions for library functions.”
  • A function may take arguments and return a value, depending on how it is defined.
    From your textbook
    “A function can optionally define input parameters that enable callers to pass arguments into the function.”
  • With call by value, changes to a function's formal parameter do not change the actual argument.
    From your textbook
    “changes made to formal parameter within the function will have no effect on the actual parameter.”
  • With call by reference, a change to the formal parameter is reflected in the actual argument.
    From your textbook
    “any change made in the formal parameter will be reflected back in the actual parameter.”
  • A recursive function calls itself, and scope determines where a variable can be accessed.
    From your textbook
    “A function that calls itself is known as recursive function.”
Test yourself: 6 questions

Formulas in this chapter

Functions and why programs use them

Definition

Function
A function is a small program block that performs a specific task.

Functions divide a large program into smaller parts. This makes the program easier to understand, test, and check for errors. Functions can also reduce repeated code and make a program smaller.

Why functions are useful

  • Divide and Conquer: Split a complicated program into manageable functions.
  • Programmers can develop, debug, and test functions separately.
  • Different programmers can work on different functions at the same time.
  • Reusability: Call a function again with different inputs instead of duplicating its code.

Two types of functions

Built-in functionsUser-defined functions
Provided by the C++ standard library and ready to use.Created by the user for a particular task.
Their definitions are grouped in header files.The user decides the function's task and the data it needs.

Header files and standard input/output functions

Definition

Header file
A header file provides function prototypes and definitions, along with data types and constants used by library functions.

A header file can be identified by the .h extension. One header file can contain several built-in functions. stdio.h contains standard input/output functions.

Functions in stdio.h

  • getchar() reads one character from the keyboard.
  • putchar() displays a character.
  • gets() reads a string from standard input and stores it in the string variable.
  • puts() prints the string read by gets() on a new line.

Worked example

A program reads the character T using getchar() and displays it using putchar(). What is displayed?

Try it first, then show the solution
  1. getchar() reads T from the keyboard.
  2. putchar(ch) displays the character stored in ch.

Answer: The entered Character is: T

Worked example

A program reads Computer Science using gets(str) and displays it using puts(str). What is displayed?

Try it first, then show the solution
  1. gets(str) reads the string and stores it in str.
  2. puts(str) prints the stored string on a new line.

Answer: You entered: Computer Science

Character functions: isalnum(), isalpha(), and isdigit()

The ctype.h header file provides functions for working with characters. Include ctype.h in a program to use these character functions.

What each character function checks

FunctionWhat it checks and returns
isalnum(char c)Returns a non-zero value if c is a digit or a letter. Otherwise, it returns 0.
isalpha(char c)Returns 1 if c is an alphabet. Otherwise, it returns 0.
isdigit(char c)Returns 1 if c is a digit. Otherwise, it returns 0.

Worked example

What does isalnum(ch) return when ch is 'A' or '?'?

Try it first, then show the solution
  1. A is a letter, so isalnum(ch) returns a non-zero value.
  2. ? is neither a letter nor a digit, so isalnum(ch) returns 0.

Answer: For 'A', the shown output is 1. For '?', the output is 0.

Worked example

What do isalpha('a') and isdigit('3') return?

Try it first, then show the solution
  1. 'a' is an alphabet, so isalpha('a') returns 1.
  2. '3' is a digit, so isdigit('3') returns 1.

Answer: Both functions return 1.

Remember: isalnum() checks for a letter or digit; isalpha() checks for a letter; isdigit() checks for a digit.

Character case-checking and conversion functions

Character functions

FunctionWhat it does
islower(char c)Returns a non-zero value if c is a lowercase alphabet; otherwise returns 0.
isupper(char c)Returns 1 if c is uppercase; otherwise returns 0.
toupper(char c)Returns the uppercase equivalent of c. An uppercase character stays the same.
tolower(char c)Returns the lowercase equivalent of c. A lowercase character stays the same.

For example, islower('n') assigns 1 to n, while islower('P') assigns 0. isupper('A') assigns 1, and isupper('a') assigns 0.

Worked example

What do these conversion statements produce?

Try it first, then show the solution
  1. toupper('k') converts the lowercase character to uppercase.
  2. tolower('K') converts the uppercase character to lowercase.
  3. toupper('B') and tolower('b') leave those characters unchanged.

Answer: The results are 'K', 'k', 'B', and 'b', respectively.

Remember: islower() and isupper() check a character; toupper() and tolower() change its case when needed.

String manipulation functions

The string.h library, also called cstring, contains common functions for strings stored in character arrays. Include the string.h header file before using a string function.

What the string functions do

FunctionPurpose
strcpy(Target String, Source String)Copies the source string to the target, including the null terminating character (\0).
strlen(string)Returns the length of a null-terminated string, without counting the null (\0) character.
strcmp(String1, String2)Compares two strings lexicographically.
strcat(Target, source)Adds a copy of the source string to the end of the target string.
strupr(string)Converts the given string to uppercase letters.
strlwr(string)Converts the given string to lowercase letters.

Results returned by strcmp()

  • A positive value means the first differing character in string1 is greater than the corresponding character in string2, based on ASCII values.
  • A negative value means the first differing character in string1 is less than the corresponding character in string2.
  • 0 means the strings are equal.

Worked example

What happens when strcpy(target, source) copies source = "Computer Science" into target?

Try it first, then show the solution
  1. The source string is copied into the target string.
  2. The null terminating character is copied too.

Answer: The target contains "Computer Science".

Worked example

What length does strlen(source) return for source = "Computer Science"?

Try it first, then show the solution
  1. strlen() counts the characters in the string.
  2. It does not count the null (\0) character.

Answer: It returns 16.

Worked example

What does strcmp(string1, string2) report when string1 is "Computer" and string2 is "Science"?

Try it first, then show the solution
  1. The first differing characters are compared using their ASCII values.
  2. The first differing character in "Computer" is less than the corresponding character in "Science".

Answer: The function returns a negative value, so the strings are not equal.

Worked example

What is target after strcat() joins target = "Learning C++ is fun" and source = " , easy and Very useful"?

Try it first, then show the solution
  1. A copy of source is added to the end of target.

Answer: Learning C++ is fun , easy and Very useful

strupr() changes a lowercase string such as "computer science" to "COMPUTER SCIENCE". strlwr() changes an uppercase string such as "COMPUTER SCIENCE" to "computer science".

Remember: strlen() excludes \0, while strcpy() copies it along with the string.

Mathematical functions and cos()

The math.h header file contains basic mathematical functions. The cos() function takes one argument in radians and returns a value in the range [-1, 1]. Its returned value can be double, float, or long double.

Worked example

What does cos(0.5) return in the given program?

Try it first, then show the solution
  1. The argument 0.5 is passed to cos().
  2. The program displays the returned value.

Answer: The output is COS(0.5)= 0.877583.

Remember: cos() takes its argument in radians and returns a value from -1 to 1.

Math functions: sqrt(), sin() and pow()

What each function does

FunctionPurpose and rules
sqrt()Returns the square root of one non-negative argument. A negative argument causes a domain error.
sin()Takes one argument in radians and returns a value from -1 to 1.
pow()Takes a base and an exponent, then returns the base raised to that exponent.

The return type of sin() can be double, float, or long double. For pow(), the return type is long double if any argument is long double. Otherwise, it is double.

Worked example

Find sqrt(625) using the given program.

Try it first, then show the solution
  1. Set x = 625.
  2. Call result = sqrt(x).

Answer: sqrt(625) = 25

Worked example

Find pow(5, 4) and sin(25) using the given program.

Try it first, then show the solution
  1. Set base = 5 and exponent = 4, then call pow(base, exponent).
  2. Set x = 25, then call sin(x).

Answer: pow(5^4) = 625; sin(25)= -0.132352

User-defined functions and function definitions

Definition

User-defined function
A function created by the user to perform a specific task.

A function can take input parameters and can return an output value. It can also place a common operation in one reusable block with a name that describes its task. In C++, define a function before using it, or declare it first.

Parts of a function definition

  • Return_Data_Type is a valid C++ data type.
  • Function_name is a user-defined identifier.
  • The optional parameter list contains variables with data types, separated by commas.
  • The body contains the C++ statements that perform the task.

A C++ program can contain any number of functions, but it must have only one main() function to begin program execution. Function definitions can be written in any order if each function is declared before it is used.

Function definition form

Return_Data_Type Function_name(parameter list) Body of the function

Return_Data_Type is the value type returned, Function_name identifies the function, and the optional parameter list gives its inputs.

Function prototypes, void and function calls

Definition

Function prototype
A declaration that gives the compiler a function’s return type, name and argument data types before the function is used.

For example, long fact (int, double) says that fact returns a long value and takes two arguments: an int followed by a double. A prototype may be written outside main().

Definition

void
void indicates that a function does not return a value; it can also declare a generic pointer.

void fun(void) tells the compiler that fun() receives no values from the calling program and returns no value. A function call uses the function name and the required arguments.

Four ways to call display()

  • display() calls without arguments and without a return value.
  • display (x, y) calls with arguments and without a return value.
  • x = display() calls without arguments and uses a return value.
  • x = display (x, y) calls with arguments and uses a return value.

The compiler checks a function call against its prototype. If an argument type does not match, the compiler converts it when possible. If conversion is impossible, it generates an error message.

Formal parameters, actual arguments and default arguments

Function parameters

Formal parametersActual parameters or arguments
Variables written in a function definition.Constants, variables or expressions written in a function call.

Arguments pass values from the calling function to the called function. In sum (a, b), x and y are formal parameters in the definition sum (int x, int y), while a and b are actual arguments in the call.

Definition

Default argument
A value assigned to a formal parameter so a function call can leave out that argument.

Rules for default arguments

  • The compiler uses a default value for a missing argument.
  • A default value is given in the form of variable initialization.
  • Default values can be written from right to left in the parameter list.
  • A parameter in the middle of the list cannot have a default value if a later parameter has none.

Worked example

Use the given area function with radius 5 and the default value pi=3.14.

Try it first, then show the solution
  1. Call area(rad) with rad = 5.
  2. The omitted pi argument uses its default value, 3.14.
  3. The function returns pi*r*r.

Answer: The Area of Circle =78.5

Default argument prototypes

PrototypeStatus
void defaultvalue(int n1=10, n2);Invalid prototype
void defaultvalue(int n1, n2 = 10);Valid prototype

Constant Arguments in C++ Functions

The const keyword makes a variable’s value unchangeable inside a function. Give a constant argument its initial value when declaring it. Trying to change it in the function causes a compiler error.

Worked example

What happens if r is changed in a function where it is a constant argument?

Try it first, then show the solution
  1. Declare the parameter with const, as in double area(const double r, const double pi=3.14).
  2. Try to assign r=25; inside the function.

Answer: The compiler reports an error because r is a read-only parameter.

Remember: Use const when a function argument must not be changed inside the function.

Call by Value and Call by Reference

C++ functions can receive arguments by value or by reference. The method used determines whether changes inside the function affect the original argument.

How function arguments are passed

Call by valueCall by reference or address
The value of the actual argument is copied to the formal parameter.The address of the actual argument is passed to the formal parameter.
Changes to the formal parameter do not change the actual argument.Changes to the formal parameter also change the actual argument.
The parameter is written without &.The parameter is written with &.

Worked example

In Program 11.17, what is displayed when the input value is 5?

Try it first, then show the solution
  1. display(a) passes a by value to x.
  2. Inside display, a is calculated as x*x, giving 25.
  3. The original a in main remains unchanged.

Answer: The display function shows 25, and main shows 5.

Worked example

In Program 11.18, what happens when the input value is 45?

Try it first, then show the solution
  1. display(n1) passes a reference to n1 through the parameter int &x.
  2. The function changes x to x*x, giving 2025.
  3. Because x and n1 refer to the same memory location, n1 also becomes 2025.

Answer: The function shows 2025, and main shows 2025 after the call.

Remember: With call by value, the original stays unchanged. With call by reference, a change in the function is reflected in the original.

Inline Functions

Definition

Inline function
An inline function inserts its code directly into the calling program.

A normal function call makes the program jump to the function and then return to the instruction after the call. For small function definitions, an inline function can reduce overheads like STACKS. Write the keyword inline in the function header.

Advantages of inline functions

  • They execute faster.
  • They require more memory space.
  • They reduce the complexity of using STACKS.

Worked example

What does the inline add function do when x is 10 and y is 20?

Try it first, then show the solution
  1. The function adds a and b.
  2. The result is returned to the calling statement z=add(x,y).

Answer: The sum is 30.

Four Forms of User-Defined Functions

Function forms

ParametersReturn value
No parametersNo return value: display() has return type void and displays First C++ Program with Function.
No parametersReturns a value: display() has return type int and returns the sum of a=10 and b=5, which is 15.
Has parametersNo return value: display(int x, int y) adds the passed values and displays their sum. With 50 and 45, the output is 95.
Has parametersReturns a value: display(int x, int y) returns the sum. With 45 and 20, the returned sum is 65.

A function can have parameters, return a value, do both, or do neither. A return statement sends a value back when the function has one. It also transfers program control back to the calling statement.

Remember: To identify a function form, check whether it has parameters and whether it returns a value.

The return statement and function return values

A return statement stops a function and transfers control back to the calling statement. It can return a value, or it can be written without a value to end a void function. Once return runs, the function ends immediately.

Return statement

return expression/variable;

The expression or variable gives the value returned to the calling statement.

Examples of return statements

  • return(a+b); returns the value of a+b.
  • return(a); returns the value of a.
  • return; ends a function without returning a value.

Function prototypes and return types

Function prototypeReturn type
int sum(int, float)int
float area(float, float)float
char result()char
double fact(int n)double

A function declared as void returns no value. If no return type is explicitly mentioned, the return type is treated as int. A string can also be returned to a calling statement; the example returns “chennai” from display().

Remember: return ends the function and sends control back to the calling statement; a return value is optional.

Recursive functions

Definition

Recursive function
A function that calls itself is a recursive function, and this technique is called recursion.

The factorial example calls factorial(m-1) when m > 1, then multiplies that result by m. When m is not greater than 1, the function returns 1. The program uses a function prototype because factorial() is defined after main().

Worked example

Find the factorial of 5 using the recursive factorial function.

Try it first, then show the solution
  1. The function repeats the calculation with a smaller value using factorial(m-1) while m > 1.
  2. When the value is no longer greater than 1, the function returns 1.
  3. The returned values are multiplied as the function calls finish.

Answer: Factorial of Number 5 = 120

Remember: A recursive function calls itself, and the factorial example stops reducing the value when it reaches the return 1 case.

Variable scope in C++

Definition

Scope
Scope is the accessibility of a variable.

Four types of scope

Scope typeWhere it applies
Local scopeA variable declared inside a block; it can be accessed only within that block.
Function scopeA variable declared within a function; its scope extends through the function block and its sub-blocks.
File scopeA variable declared above all blocks and functions, including main(); it is also called a global variable.
Class scopeA class data member; its scope is within the class.

A block starts and ends with curly braces { }. A local variable is created when execution enters its block and destroyed when execution leaves it. Function scope variables live for the life of the function block, while file scope variables live for the life of the program.

A variable declared inside a block cannot be accessed outside that block. In the scope example, t is local to an if block, so it cannot be accessed from main() outside that block. The function variable m cannot be accessed from main() either.

Class data members represent features or properties of a class. In the student class example, mark1, mark2 and total are data variables whose scope is within the student class.

Scope resolution operator

::

Used to access a global variable when a local variable has the same name.

Worked example

A global variable x has value 45, and a local variable x in main() has value 10. Which values are printed?

Try it first, then show the solution
  1. ::x refers to the global variable.
  2. x inside main() refers to the local variable.

Answer: Value of global x is 45; Value of local x is 10.

Remember: A variable can be accessed only within its scope; :: lets you access the global variable when a local variable has the same name.

Questions students ask

Short, direct answers to what students search for in this chapter.

What is a function in C++?

A function is a small program block that performs a specific task. Functions help divide a large program into smaller parts, making it easier to understand, test, and check for errors.

What is the difference between built-in and user-defined functions?

Built-in functions are provided by the C++ standard library and are ready to use. User-defined functions are created by the programmer for a specific task. The user decides the task and the data needed by a user-defined function.

What do getchar() and putchar() do?

getchar() reads a single character from the keyboard. putchar() displays a character. In the example, getchar() reads T, and putchar(ch) displays T.

What is the difference between isalnum(), isalpha(), and isdigit()?

isalnum() checks whether a character is a letter or a digit. isalpha() checks whether it is a letter. isdigit() checks whether it is a digit. Each function returns 0 when its check is not satisfied.

What is the difference between islower() and isupper()?

islower(char c) checks whether c is a lowercase alphabet and returns a non-zero value if it is, or 0 otherwise. isupper(char c) checks whether c is uppercase and returns 1 if it is, or 0 otherwise.

What do toupper() and tolower() do?

toupper(char c) returns the uppercase equivalent of a character, while tolower(char c) returns its lowercase equivalent. If the character is already in the requested case, it stays the same.

Show 17 more questions

What is the difference between strcpy() and strcat()?

strcpy(Target String, Source String) copies the source string into the target, including its null terminating character. strcat(Target, source) instead adds a copy of the source string to the end of the target string.

Does strlen() count the null character?

No. strlen() returns the length of a null-terminated string but does not include the null (\0) character in that length.

What does strcmp() return when two strings are equal?

strcmp() returns 0 when the two strings are equal. If they differ, it returns a positive or negative value according to the ASCII values of their first differing characters.

What does the sqrt() function do in C++?

The sqrt() function returns the square root of a single non-negative argument. If the argument is negative, a domain error occurs. For example, sqrt(625) returns 25.

What is the difference between formal and actual parameters?

Formal parameters are the variables written in a function definition. Actual parameters are the constants, variables or expressions supplied in a function call. For example, in sum (a, b), a and b are actual arguments, while x and y in sum (int x, int y) are formal parameters.

What is a function prototype in C++?

A function prototype declares a function before it is used. It tells the compiler the function’s return type, name and argument data types. For example, long fact (int, double) declares fact as a function that returns long and takes an int and a double.

How do default arguments work in C++?

A default argument gives a formal parameter a value to use when the function call leaves that argument out. The compiler supplies the default value for each missing argument. Default values must be written from right to left in the parameter list.

What does void fun(void) mean?

void fun(void) tells the compiler that fun() receives no values from the calling program and returns no value. In general, void indicates that a function does not return a value. void can also be used to declare a generic pointer.

What does const mean for a function argument in C++?

const makes a function argument’s value unchangeable inside the function. The argument must be initialized when it is declared. If the function tries to assign a new value to that argument, the compiler reports an error because it is read-only.

What is the difference between call by value and call by reference?

Call by value copies an argument’s value into the function parameter, so changes to that parameter do not affect the original. Call by reference passes the argument’s address, so changes made through the parameter are reflected in the original argument.

What does the ampersand mean in a C++ function parameter?

The & symbol in a parameter declaration means the argument is passed by reference. The parameter and the original argument refer to the same memory location. Therefore, changing the parameter inside the function also changes the original argument.

What is an inline function in C++?

An inline function has its code inserted directly into the calling program. The inline keyword is written in the function header. Inline functions can execute faster and reduce the complexity of using STACKS, but they require more memory space.

What are the four forms of user-defined functions?

The four forms are a function without a return value or parameters, a function with a return value but no parameters, a function without a return value but with parameters, and a function with both a return value and parameters.

What does the return statement do in C++?

The return statement ends the function immediately and transfers control back to the calling statement. It may return a value, which becomes the return value for the caller. A return statement without a value can also be used to end a void function.

What is a recursive function?

A recursive function is a function that calls itself. In the factorial example, the function calls factorial(m-1) while m > 1. When that condition is not true, it returns 1, and the calls multiply their returned values.

What are the four types of variable scope in C++?

The four types are local scope, function scope, file scope and class scope. Local scope belongs to a block. Function scope extends through a function and its sub-blocks. File scope applies to a global variable, and class scope applies within a class.

How do you access a global variable when a local variable has the same name?

Use the scope resolution operator :: before the variable name. For example, if both a global and local variable are named x, ::x refers to the global variable, while x inside the function refers to the local variable.

Book back answers

19 textbook exercises, solved and checked against the book. Questions we could not prove are left out.

SECTION – A Choose the correct answer

  1. Which of the following header file defines the standard I/O predefined functions ?

    • A) stdio.h
    • B) math.h
    • C) string.h
    • D) ctype.h
    Try it, then show the answer

    A) stdio.h

    The chapter identifies stdio.h as the header file containing standard input/output functions.

    From the book: “stdio.h is a header file that contains pre-defined “standard input/ output” functions.”

  2. Which function is used to check whether a character is alphanumeric or not.

    • A) isalpha()
    • B) isdigit()
    • C) isalnum()
    • D) islower()
    Try it, then show the answer

    C) isalnum()

    The chapter says isalnum checks whether a character is alphanumeric.

    From the book: “This function is used to check whether a character is alphanumeric or not.”

  3. Which function begins the program execution ?

    • A) isalpha()
    • B) isdigit()
    • C) main()
    • D) islower()
    Try it, then show the answer

    C) main()

    A C++ program begins execution through its main() function.

    From the book: “But, it must always have only one main() function to begin the program execution.”

  4. Which of the following function is with a return value and without any argument ?

    • A) x=display(int, int)
    • B) x=display()
    • C) y=display(float)
    • D) display(int)
    Try it, then show the answer

    B) x=display()

    This form calls display without arguments and assigns its returned value to x.

    From the book: “3 x = display() calling the function with a return value and without any argument”

All 19 book back answers →

Practice

Question 1 of 6Score 0

Why are functions used to divide a complicated program?

Exam questions

Practice questions with model answers. These are not from an official paper.

Give two reasons why functions are useful in large programs.2 marks

Functions divide complicated programs into manageable parts, making it easier to develop, debug, and test individual parts. They also reduce repeated code and support reuse, which can improve maintenance and reduce program size.

Explain the difference between call by value and call by reference.2 marks

Call by value copies the actual argument's value into the formal parameter, so changes to that parameter do not affect the actual argument. Call by reference passes the actual argument's address, so changes made through the formal parameter are reflected in the actual argument.

What is a recursive function? Give the lesson's example of one.2 marks

A recursive function is one that calls itself. The lesson demonstrates recursion with a function that finds the factorial of a number.

Name the four types of scope described in this lesson.2 marks

The four types are local scope, function scope, file scope, and class scope.

Watch out

  • Do not confuse isalpha(), which checks for an alphabet, with isalnum(), which accepts a letter or a digit.
  • Do not assume call by value changes the original argument; changes are reflected back only with call by reference.

Still stuck on this lesson?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →