Skip to study material
CodeBhavya

Programming for Problem Solving

AR25 · I Year I Semester · 2025–2026 · Unit III: Functions and Program Structure

← Unit III questions

QUESTION 01 · Functions

What is a user-defined function?

2 marks

Answer

A user-defined function is a named block of code written by the programmer to perform a task.

  • It can receive values through parameters.
  • It can return a result to its caller.

Related Unit III exam questions →

QUESTION 02 · Functions

Explain user-defined functions and their advantages.

5 marks

Answer in brief

A function groups statements that perform a particular task. A program can call the function whenever that task is needed.

Main parts

  1. A declaration tells the compiler the function name, return type and parameter types.
  2. A definition contains the function body.
  3. A call requests execution of the function with the required arguments.

Example explanation

The example defines add to receive two integers and return their sum. main calls add(4, 6). The function receives the values in a and b, calculates 10 and returns it. printf then displays the returned result. The function definition appears before main, so it also provides the required declaration before the call.

Advantages

  1. Reusability: the same task can be called several times without copying its statements.
  2. Readability: a meaningful name, such as calculate_total, explains the purpose of a block.
  3. Testing: a small function is easier to check with selected inputs.
  4. Maintenance: changing one function can update all places that call it.
  5. Teamwork: different functions can be developed separately when their interfaces are agreed.

Important points

Keep each function focused on a clear task. Its parameter and return types form its interface: they describe how values enter and leave it. A function is not executed merely because it is defined; a call is needed. For the fixed integer addition shown here, time and extra working space are both O(1).

Flowchart

Control flow for function-call with labelled true and false paths.
Explain user-defined functions and their advantages. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int add(int a, int b)
{
    return a + b;
}
int main(void)
{
    printf("Sum = %d\n", add(4, 6));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Sum = 10

Related exam questions

Related questions in the function declarations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(h) · 1 marks

    Define function signature.

    Paper P05 · page 1
  • September 2023 · Q1(h) · 1 marks

    What is the signature of a function?

    Paper P06 · page 1

View this category in the exam question bank →

QUESTION 03 · Functions

What is a function prototype?

2 marks

Answer

A function prototype declares a function and specifies the types of its parameters.

  • Example: int add(int a, int b);
  • The compiler uses it to check calls and apply the required argument conversions.

Related Unit III exam questions →

QUESTION 04 · Functions

Distinguish a function declaration, definition and call with an example.

5 marks

Answer in brief

A declaration describes a function, a definition supplies its body, and a call executes it.

Declaration or prototype

int square(int number);

Meaning of the prototype

int before the name is the return type. square is the function name. int number specifies one integer parameter; the parameter name is optional in a prototype. The semicolon ends the declaration. A prototype does not contain the function body.

Definition

int square(int number)
{
    return number * number;
}

Function call

In square(5), the value 5 is supplied as an argument. Control enters the definition, number receives 5 and the expression number * number produces 25. return sends the value back to the caller. The example declares the function before main and defines it afterwards.

Important rules

  1. Declare the function before its first call. Modern C does not provide an implicit function declaration.
  2. Keep declarations and the definition compatible, including the return type and parameter types.
  3. A prototype alone is not a definition; a used non-library function still needs a definition.
  4. In C11, write f(void) to declare no parameters. A declaration f() does not specify the parameter types.

Why prototypes are useful

The compiler can detect many wrong argument counts and incompatible types when a prototype is visible. A prototype does not prove the function computes the right answer; the body must still be tested. The sample square value is deliberately small enough for int arithmetic.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int square(int number);
int main(void)
{
    printf("Square = %d\n", square(5));
    return 0;
}
int square(int number)
{
    return number * number;
}

Sample input and output

This example uses values already written in the program.

Output

Square = 25

Related exam questions

Related questions in the function declarations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(h) · 1 marks

    Define function signature.

    Paper P05 · page 1
  • September 2023 · Q1(h) · 1 marks

    What is the signature of a function?

    Paper P06 · page 1

View this category in the exam question bank →

QUESTION 05 · Functions

List the four categories of functions based on arguments and return values.

2 marks

Answer

Functions may have no arguments and no value, arguments and no value, no arguments and a value, or arguments and a value.

  • void is used as the return type when no value is returned.
  • In a C11 prototype, (void) specifies that the function has no parameters.

Related Unit III exam questions →

QUESTION 06 · Functions

Explain the four categories of functions based on arguments and return values.

5 marks

Answer in brief

Functions are commonly classified by whether they receive arguments and whether they return a value.

No arguments and no return value

void greet(void)
{
    puts("Welcome");
}

Arguments and no return value

A function such as void show_square(int n) receives a number and displays its square. The caller supplies the input through an argument, but the function does not return a value. Displaying a result is an output action, not a returned value.

No arguments and a return value

A function such as int fixed_limit(void) can return a fixed limit without receiving arguments. It might instead obtain a value from another permitted source, but that is separate from the parameter list. The caller can store or use its returned value.

Arguments and a return value

A function such as int add(int a, int b) receives two numbers and returns their sum. This is useful when the caller should decide whether to print the result, store it or use it in another calculation.

Choosing a category

Choose the interface according to the task. Passing values as arguments makes a function easier to reuse than making every function read directly from the keyboard. Returning a calculated value often makes testing easier. A void function may still change an object through a pointer parameter or display output; void only says there is no returned value.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void greet(void) { puts("Welcome"); }
void show_square(int n) { printf("Square = %d\n", n * n); }
int fixed_limit(void) { return 10; }
int add(int a, int b) { return a + b; }
int main(void)
{
    greet();
    show_square(3);
    printf("Limit = %d\n", fixed_limit());
    printf("Sum = %d\n", add(4, 6));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Welcome
Square = 9
Limit = 10
Sum = 10

Related exam questions

Related questions in the function categories category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q8(a) · 5 marks

    Discuss types of functions based on parameters and return type.

    Paper P02 · page 2
  • March/April 2023 · Q9(a) · 5 marks

    Explain differences between user-defined and library functions.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 07 · Functions

Distinguish actual arguments and formal parameters.

2 marks

Answer

Actual arguments are expressions supplied in a call. Formal parameters are the variables declared in the function definition to receive their values.

  • In add(x, 5), x and 5 are argument expressions.
  • In int add(int a, int b), a and b are parameters.

Related Unit III exam questions →

QUESTION 08 · Functions

Explain actual arguments, formal parameters and communication between functions.

5 marks

Answer in brief

Functions communicate by receiving argument values, returning a value and, when appropriate, accessing objects through pointers or shared declarations.

Actual arguments

An argument is an expression written in the call. In add(x, 5), the value of x and the value 5 are supplied. An argument can be a constant, variable or a more complex expression, provided its type and use are suitable for the function.

Formal parameters

Parameters are declared in the function definition. In int add(int a, int b), a and b are separate local parameter objects for each call. Their names need not be the same as the caller’s variable names. C passes values: changes to a or b alone do not change the caller’s ordinary integer variables.

Return communication

return expression; supplies one result value to the caller for a non-void function. The caller can assign that result to a variable, print it or use it in another expression. The return type describes the kind of result.

Example trace

If x contains 4, add(x, 5) supplies 4 and 5. The parameter objects receive those values. The function returns 9. If the caller writes result = add(x, 5);, result becomes 9 while x remains 4.

Important points

Use a visible prototype and compatible types. C does not generally specify the order in which different argument expressions are evaluated. Avoid calls that update the same variable in conflicting argument expressions. Prefer clear, independent arguments. Pointer-based output is introduced separately; the pointer value is still passed by value.

Related exam questions

Related questions in the function declarations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(h) · 1 marks

    Define function signature.

    Paper P05 · page 1
  • September 2023 · Q1(h) · 1 marks

    What is the signature of a function?

    Paper P06 · page 1

View this category in the exam question bank →

QUESTION 09 · Functions

What does return do in a function?

2 marks

Answer

It ends the current function call and transfers control back to the caller.

  • A non-void function can return a value with return expression;.
  • A void function can use return; without an expression.

Related Unit III exam questions →

QUESTION 10 · Functions

Explain the return statement and return types in C functions.

5 marks

Answer in brief

The return statement finishes the current function call. For a non-void function, it can also send a result value to the caller.

Syntax

return expression;  /* value-returning function */
return;             /* void function */

Return type

The type written before the function name specifies its result type. In double half(int n), the function returns a double. The expression n / 2.0 uses floating-point arithmetic, so half(7) returns 3.5. Returning a value can involve conversion to the declared return type.

Execution

When return is reached, later statements on that path in the same call do not execute. A function can contain several return statements for different conditions, but a particular call completes through only one return path. The caller resumes after the call with the returned result when there is one.

Important rules

  1. Use return; in a void function, rather than returning an ordinary value.
  2. Ensure every needed path of a value-returning function supplies a valid result. Falling off its end and then using the missing value has undefined behaviour, with the special main rule discussed separately.
  3. In a hosted program, returning 0 from main reports successful completion. Reaching the closing brace of main also returns 0.
  4. Do not return a pointer to an ordinary automatic local object: that object no longer exists after the call ends.

Example purpose

The sample separates calculation from display. half performs the calculation; main decides the output format. This allows the result to be used in a later calculation without changing half.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
double half(int n)
{
    return n / 2.0;
}
int main(void)
{
    printf("Half = %.1f\n", half(7));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Half = 3.5

Related exam questions

Related questions in the function declarations category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(h) · 1 marks

    Define function signature.

    Paper P05 · page 1
  • September 2023 · Q1(h) · 1 marks

    What is the signature of a function?

    Paper P06 · page 1

View this category in the exam question bank →

QUESTION 11 · Function Communication

Does changing an integer parameter change the caller’s variable?

2 marks

Answer

No. C passes its value into a separate parameter object.

  • The parameter can be changed without changing the original integer variable.
  • To request a change to a caller’s object, a suitable pointer can be passed.

Related Unit III exam questions →

QUESTION 12 · Function Communication

Explain call by value in C with an example.

5 marks

Answer in brief

C uses pass by value: each parameter receives a value supplied by the corresponding argument. An ordinary integer parameter is a separate object from the caller’s integer variable.

Working

  1. The caller evaluates the argument expression.
  2. The resulting value is used for the parameter according to the declared type.
  3. The function works with its parameter object. Assigning a new value to that parameter does not assign to the caller’s variable.

Example trace

main starts with number = 10 and calls change(number). The parameter n receives 10. Inside change, n = 25 changes only n, so the first line prints 25. After the function returns, number in main still contains 10. This shows the difference between a copied value and the original object.

Advantages

A function can use and update a working parameter without unintentionally replacing the caller’s ordinary value. This helps keep calculations separate. For example, a digit-processing function can repeatedly divide its local copy while the original input remains available to main.

Pointer clarification

Passing an address does not change C into pass by reference. The address is a pointer value, and that value is copied into a pointer parameter. The function can use the copied pointer to access the same caller-owned object. Changing the pointer parameter itself is different from changing the object to which it points.

Complexity

The fixed-size integer example uses constant work and a fixed number of objects, so time and extra space are O(1). The copying cost of an argument depends on its type; do not assume every possible argument is a single small integer.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void change(int n)
{
    n = 25;
    printf("Inside = %d\n", n);
}
int main(void)
{
    int number = 10;
    change(number);
    printf("Outside = %d\n", number);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Inside = 25
Outside = 10

Related exam questions

Related questions in the function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(g) · 2 marks

    Define formal arguments.

    Paper P02 · page 1
  • March/April 2023 · Q8(b) · 5 marks

    Write a C program using functions to swap two numbers using global variables and the call-by-reference concept.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 13 · Function Communication

How can a function modify an integer belonging to its caller?

2 marks

Answer

Pass the integer’s address to an int * parameter and assign through that pointer.

  • &x obtains the address of x.
  • *p accesses the object identified by a valid pointer p.

Related Unit III exam questions →

QUESTION 14 · Function Communication

Show how a function can change caller variables using pointer arguments.

5 marks

Answer in brief

A function can modify a caller’s object when it receives a valid pointer to that writable object and assigns through the pointer.

Required notation

  1. int *p declares a parameter that can hold the address of an int.
  2. &x obtains the address of x.
  3. *p accesses the int identified by p. An assignment such as *p = 20 changes that object.

Swap algorithm

  1. Save the value of *a in a temporary integer.
  2. Copy *b into *a.
  3. Copy the temporary value into *b.

Example trace

main starts with x = 4 and y = 9. swap(&x, &y) passes their addresses. The parameter a identifies x and b identifies y. temporary receives 4, *a becomes 9 and *b becomes 4. After the call, the original objects in main contain the swapped values.

Important distinction

This is often called call by address in introductory courses. C itself still passes arguments by value: the pointer values are copied. Assigning a different address to the local parameter a would not change a caller pointer variable. Assigning to *a changes the object reached through the copied pointer.

Validity and complexity

Both pointers must identify suitable live, writable int objects before they are dereferenced. The example always passes addresses of local variables that remain alive during the call. There are three fixed assignments and one temporary integer, so the swap takes O(1) time and O(1) auxiliary space. Full pointer details belong to Unit V.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void swap(int *a, int *b)
{
    int temporary = *a;
    *a = *b;
    *b = temporary;
}
int main(void)
{
    int x = 4, y = 9;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

x = 9, y = 4

Why assigning to the parameter is different from assigning through it

Suppose main contains int x = 4; and int *p = &x;. A function called with p receives a copy of the address stored in p. Call that local parameter q. Inside the function, suppose another local integer is declared as int other = 9;.

↔ Scroll horizontally on a small screen
A copied pointer and the object it identifies
Statement inside the functionEffect inside the functionEffect visible to main
*q = 20;Write to the int identified by qx becomes 20
q = &other;Make q identify other insteadp still identifies x; x is unchanged by this assignment

The first statement changes an integer. The second changes only the function’s local pointer variable. A pointer is a value that can be copied, just like an integer; copying it does not create a new copy of the pointed-to object.

Trace the swap in the existing program

  1. temporary = *a saves 4 before x is overwritten.
  2. *a = *b places 9 in x. At this point x and y both contain 9.
  3. *b = temporary places the saved 4 in y.

Without the temporary value, the original 4 would be lost after the second step. Calling swap(&x, &x) is also valid for this implementation: each assignment uses the same live integer and its value stays unchanged. Passing a null pointer is invalid because the function dereferences both parameters.

Related exam questions

Related questions in the function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q1(g) · 2 marks

    Define formal arguments.

    Paper P02 · page 1
  • March/April 2023 · Q8(b) · 5 marks

    Write a C program using functions to swap two numbers using global variables and the call-by-reference concept.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 15 · Scope and Lifetime

What is the scope of a variable name?

2 marks

Answer

Scope is the part of the source program in which a name can be used to refer to its declaration.

  • A variable declared inside a block normally has block scope.
  • A name declared outside functions can have file scope.

Related Unit III exam questions →

QUESTION 16 · Scope and Lifetime

Explain local scope, file scope and variable hiding with an example.

5 marks

Answer in brief

Scope determines where a name is visible in the source program. It does not by itself determine how long the associated object exists.

Block scope

A local variable declared in a block can normally be used from its declaration to the end of that block. Nested blocks can use a visible outer name unless an inner declaration hides it. Function parameters in a definition are available within that function body.

File scope

An object declared outside every function has file scope. Its name is visible from its declaration to the end of the translation unit, subject to hiding. A translation unit is roughly a source file after preprocessing, including text brought in from headers. Linkage determines whether declarations can refer to the same entity across translation units.

Example trace

The file-scope value is 10. Inside main, a local value is declared as 20, hiding that file-scope name. A nested block declares another value as 30, which hides the outer local name inside that block. The lines therefore print 20, 30 and 20. The object with value 20 was not changed by declaring the inner object.

Other scopes and good practice

C also has function scope for labels and function-prototype scope for parameter names in prototypes. Use descriptive names and avoid unnecessary hiding, because similar names can confuse readers. A local static object has block scope but lasts throughout execution; this is why scope and lifetime must be studied separately.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int value = 10;
int main(void)
{
    int value = 20;
    printf("Outer = %d\n", value);
    {
        int value = 30;
        printf("Inner = %d\n", value);
    }
    printf("Outer again = %d\n", value);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Outer = 20
Inner = 30
Outer again = 20

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 17 · Scope and Lifetime

Distinguish scope and lifetime.

2 marks

Answer

Scope tells where a name is visible; lifetime tells when its object exists during execution.

  • A block-local name can refer to an automatic object that exists during one block execution.
  • A block-local static object exists throughout program execution.

Related Unit III exam questions →

QUESTION 18 · Scope and Lifetime

Distinguish scope, lifetime and linkage.

5 marks

Answer in brief

Scope, lifetime and linkage answer three different questions about a declaration and its associated object.

Scope: where a name is visible

A name declared inside a block generally has block scope. Outside that scope, the same spelling cannot be used to reach that declaration. Scope is a source-code rule about names, rather than a count of seconds or function calls.

Lifetime: when an object exists

An ordinary automatic local object is associated with a particular execution of its block. A static-duration object exists throughout program execution. A function call can end the lifetime of an ordinary automatic local object while a local static object continues to exist. Allocated objects have a different lifetime managed through memory allocation, covered in Unit V.

Linkage: whether declarations identify the same entity

External linkage can connect declarations across translation units. Internal linkage connects declarations within one translation unit. A typical local variable has no linkage. Linkage is not the same as visibility: a file-scope static object has internal linkage, while a block-local static object has no linkage.

Example

In void count(void) { static int total = 0; ++total; }, the name total has block scope. Its object has static storage duration, so the value can remain after count returns. A later call uses the same object. Scope is local, but the lifetime is not limited to one call.

Why the distinction matters

Do not return a pointer to an ordinary local object that stops existing when the call ends. Do not assume that a local name always describes temporary storage. State scope, storage duration and linkage separately when comparing storage classes.

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 19 · Storage Classes

What is the default storage duration of an ordinary block-local variable?

2 marks

Answer

It has automatic storage duration unless another relevant declaration changes that rule.

  • auto can be written explicitly in C11, as in auto int count = 0;.
  • It does not provide a guaranteed zero value when an automatic object is left uninitialised.

Related Unit III exam questions →

QUESTION 20 · Storage Classes

Explain the auto storage class with an example.

5 marks

Answer in brief

In C11, auto explicitly declares an automatic block-local object. Ordinary local variables usually have the same storage duration without writing auto.

Declaration

auto int count = 0;
int other_count = 0; /* also automatic here */

Main properties

  1. Scope is normally the enclosing block, from the declaration onwards.
  2. The local object has no linkage.
  3. A new block execution has its own automatic object.
  4. An initialiser is applied when the declaration is reached. Without a suitable initialisation, an ordinary automatic object does not have a useful guaranteed starting value.

Example trace

Each call to show creates its automatic count and initialises it to zero. The increment makes it 1, so three separate calls print 1, 1 and 1. The value is not saved for the next call. A local static counter behaves differently because it refers to one lasting object.

Uses

Automatic variables are suitable for temporary calculations, counters and intermediate results that belong to one call. Recursive calls can each have their own automatic parameter and local values. This helps one call avoid overwriting another call’s ordinary locals.

Important points

Initialise before reading. Avoid returning the address of an ordinary automatic local object because its lifetime ends when its block execution ends. auto does not mean that the compiler should infer the type in the C11 examples used here; the keyword must be understood in the selected language version.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void show(void)
{
    auto int count = 0;
    ++count;
    printf("%d\n", count);
}
int main(void)
{
    show(); show(); show();
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1
1
1

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 21 · Storage Classes

Does register guarantee that a variable is stored in a CPU register?

2 marks

Answer

No. In C11 it is a suggestion that the object may be accessed frequently.

  • The implementation decides how the object is stored.
  • The address-of operator cannot be applied to a register object in C11.

Related Unit III exam questions →

QUESTION 22 · Storage Classes

Explain the register storage class and its restrictions.

5 marks

Answer in brief

The register storage-class specifier suggests that a variable may be accessed frequently. It does not guarantee a particular hardware location or faster execution.

Declaration

register int i;

Main properties

  1. A register object at block scope has automatic storage duration.
  2. Its name has block scope and no linkage.
  3. It needs a valid value before it is read, just like an ordinary automatic local object.
  4. C11 does not permit taking its address with &.

Example explanation

The sample uses i as a small loop counter. It starts at 1, and each iteration adds i to sum. After i = 3 is processed, sum is 6. The loop would calculate the same result if register were omitted. A modern optimiser can choose efficient storage for ordinary variables too.

Restrictions and limitations

Do not write &i for a C11 register object. Consequently, a register int cannot directly be supplied to scanf as &i. The keyword is not a request for persistent storage and does not preserve a value across calls. It is also not a way to make shared updates safe between threads.

Complexity

The example performs one addition for each value from 1 through n in its general form, so the loop takes O(n) time and O(1) auxiliary space. Adding register does not change that growth rate. Optimisation of a particular build and algorithm complexity are separate matters.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int sum = 0;
    for (register int i = 1; i <= 3; ++i) { sum += i; }
    printf("Sum = %d\n", sum);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Sum = 6

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 23 · Storage Classes

What happens to a local static variable between function calls?

2 marks

Answer

Its object continues to exist and retains its stored value.

  • Its name still has block scope.
  • Without an explicit initialiser, an arithmetic object with static storage duration is initialised to zero.

Related Unit III exam questions →

QUESTION 24 · Storage Classes

Explain local static variables and file-scope static declarations.

5 marks

Answer in brief

The meaning of static depends on where it is used. A local static object keeps its value across calls; a file-scope static declaration gives internal linkage.

Local static object

In static int count = 0; inside a function, count has block scope and static storage duration. It is not recreated on every call. In these C examples its initial value is established before program startup, and later calls use the same object. If no initialiser is supplied, an arithmetic static-duration object is initialised to zero.

Example trace

The first call to visit increments count from 0 to 1. The second increments the same object to 2, and the third to 3. The output is therefore 1, 2 and 3. Contrast this with an automatic count initialised to zero on every call, which would print 1 each time.

File-scope static

At file scope, static int total; defines a static-duration object with internal linkage. Other translation units cannot connect an external declaration to that entity. A static function at file scope also has internal linkage. This helps keep implementation details within one translation unit.

Uses and limitations

  1. Local static objects can store a call count or a small amount of lasting state.
  2. File-scope static helps avoid exporting names that other source files do not need.
  3. Persistent shared state can make testing and repeated calls depend on earlier calls.
  4. static does not automatically make an update thread-safe.

Important distinction

A local static object has no linkage; a file-scope static object has internal linkage. Both have static storage duration, but their scopes are different.

Flowchart

Control flow for static-counter with labelled true and false paths.
Explain local static variables and file-scope static declarations. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void visit(void)
{
    static int count = 0;
    ++count;
    printf("%d\n", count);
}
int main(void)
{
    visit(); visit(); visit();
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1
2
3

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 25 · Storage Classes

What does extern int total; declare?

2 marks

Answer

It declares an int named total, normally referring to a definition supplied elsewhere.

  • It does not by itself supply a new definition when written without an initialiser in this form.
  • A definition must exist when the program requires that object.

Related Unit III exam questions →

QUESTION 26 · Storage Classes

Explain extern declarations with an example.

5 marks

Answer in brief

extern is commonly used to declare an object or function whose definition is supplied elsewhere, possibly in another source file.

Declaration and definition

extern int total; /* declaration */
int total = 10;   /* definition at file scope */

Working

The declaration tells the compiler the name and type. The definition supplies the object. When compatible declarations have external linkage, they can refer to the same object across translation units. A header can contain an extern declaration while one source file contains the definition.

Example explanation

In the complete single-file example, total is declared before main and defined after main. The earlier declaration makes the name available when main is compiled. The definition gives total the initial value 10, which main prints. The order is chosen to show the difference clearly.

Important rules

  1. Keep the declared type compatible with the definition.
  2. Provide one required external definition rather than putting an ordinary initialised definition in every included header.
  3. Do not assume extern makes a previously hidden name visible automatically: a declaration must appear in an appropriate scope.
  4. An extern declaration with an initialiser at file scope is a definition, so the initialiser changes the situation.

Linkage and storage duration

An object declared with external linkage has static storage duration. However, extern is not simply another word for global: a block-scope extern declaration can refer to an object defined outside that block. Linkage also depends on prior visible declarations, so avoid the oversimplification that extern always overrides an earlier static declaration.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
extern int total;
int main(void)
{
    printf("Total = %d\n", total);
    return 0;
}
int total = 10;

Sample input and output

This example uses values already written in the program.

Output

Total = 10

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 27 · Storage Classes

Which two local storage classes have automatic storage duration?

2 marks

Answer

Ordinary auto and register local objects have automatic storage duration.

  • Their values are not retained automatically between separate calls.
  • Local static objects instead have static storage duration.

Related Unit III exam questions →

QUESTION 28 · Storage Classes

Compare auto, register, static and extern in C11.

5 marks

Answer in brief

Storage-class specifiers help describe how declarations relate to storage duration and linkage. Their scope depends on where the declaration appears.

Auto

A block-local auto object has automatic storage duration and no linkage. It is normally created for an execution of its block. Without a valid initialisation, an ordinary automatic scalar does not have a useful guaranteed starting value.

Register

A block-local register object is also automatic and has no linkage. It suggests frequent access, but the compiler does not have to place it in a hardware register. In C11, its address cannot be taken with &.

Static

A local static object has block scope, no linkage and a lifetime covering program execution. It retains its value across calls. A file-scope static object instead has file scope and internal linkage. Arithmetic objects with static storage duration are initialised to zero if no explicit initialiser is given.

Extern

A common extern declaration refers to an object defined elsewhere. That object can be shared across source files through compatible external-linkage declarations. A declaration without an initialiser does not ordinarily create a separate new object.

Example and important distinction

Use an automatic temporary for a calculation needed only during one call. Use a local static counter when lasting state is intentional. Use an extern declaration when referring to a shared definition. Do not choose a class solely by a simplified memory-location table: C does not require automatic objects to occupy a particular physical stack or register. State scope, duration and linkage separately.

Comparison table

↔ Scroll horizontally on a small screen
Storage classes in C11
DeclarationScopeDurationLinkage / main rule
Block autoBlockAutomaticNone; initialise before reading
Block registerBlockAutomaticNone; address cannot be taken in C11
Block staticBlockStaticNone; retains value
File staticFileStaticInternal
Typical extern declarationAt declaration scopeStatic for referred external objectRefers to compatible shared definition

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →

QUESTION 29 · Qualifiers and Preprocessor

What does const mean for an object?

2 marks

Answer

It prevents modification through a const-qualified access to that object.

  • For example, const int limit = 10; cannot be assigned a new value through limit.
  • const is a type qualifier, not a storage-class specifier.

QUESTION 30 · Qualifiers and Preprocessor

Explain const, volatile and restrict type qualifiers.

5 marks

Answer in brief

Type qualifiers add properties to a type. The main introductory qualifiers are const, volatile and restrict; C11 also includes _Atomic with separate atomic-operation rules.

Const

const int limit = 10; declares an object that cannot be assigned a new value through limit. A pointer to const can be used to allow reading without allowing modification through that pointer. const does not automatically make a C object an integer constant expression. Casting away const does not make an originally const-defined object safely writable.

Volatile

volatile tells the implementation that accesses to an object have significance beyond ordinary calculations. It is used in implementation-specific hardware interfaces and suitable signal-handling situations. It does not guarantee atomic updates, mutual exclusion or thread synchronisation. A variable changing between threads needs the appropriate atomic or locking rules.

Restrict

restrict is mainly used with pointer types. It expresses an access promise about the objects reached through pointers during the relevant execution. This can help optimisation when the promise is valid. It does not check the promise at runtime; violating the required access rules can cause undefined behaviour. Full pointer examples are deferred to Unit V.

Simple example

The program declares a const rate and uses it to compute an amount. The rate can be read, but an assignment such as rate = 0.10 is not allowed through that name. The program does not contain that invalid assignment.

Important distinction

Qualifiers are not storage classes. A const object can still be an automatic local or have static storage duration, depending on its declaration. Qualifying a type does not by itself select a hardware memory location.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    const double rate = 0.05;
    double amount = 200.0 * rate;
    printf("Amount = %.2f\n", amount);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Amount = 10.00

QUESTION 31 · Qualifiers and Preprocessor

What is the purpose of the C preprocessor?

2 marks

Answer

It handles preprocessing directives and macro replacement before the later translation stages.

  • #include brings in header contents.
  • #define defines a macro; #if and related directives select text for compilation.

Related Unit III exam questions →

QUESTION 32 · Qualifiers and Preprocessor

Explain the C preprocessor and its main directives.

5 marks

Answer in brief

The preprocessor handles directives and macro replacement as part of translating C source. A directive normally begins with # after any leading whitespace.

Main directives

  1. #include makes header contents available for preprocessing.
  2. #define creates an object-like or function-like macro.
  3. #undef removes a macro definition.
  4. #if, #ifdef, #ifndef, #elif, #else and #endif control which source text is included.
  5. #error requests a diagnostic when a required configuration is missing or invalid.

Header inclusion

Use #include <stdio.h> for the standard input/output declarations. Quoted inclusion, such as #include "settings.h", is commonly used for project headers. The implementation defines the precise search rules. Including a header is not the same as copying the compiled implementation of every library function into the program.

Example explanation

The sample defines LIMIT as 3. During preprocessing, uses of the macro name are replaced by its replacement tokens. The resulting loop prints 1, 2 and 3. The macro is not an ordinary int variable and does not have a separate object storing 3.

Why it is useful

Headers support shared declarations. Macros can name configuration values, and conditional compilation can choose platform or debug code. These operations affect the translated source; an ordinary runtime if instead makes a decision while the program is running.

Important points

Do not put a semicolon after a simple numeric macro unless a semicolon is intentionally part of the replacement. Macros are not checked like typed function parameters. Inspect expanded expressions carefully, especially when arithmetic operators or repeated arguments are involved.

Flowchart

Control flow for translation with labelled true and false paths.
Explain the C preprocessor and its main directives. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define LIMIT 3
int main(void)
{
    for (int i = 1; i <= LIMIT; ++i) { printf("%d\n", i); }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1
2
3

Related exam questions

Related questions in the preprocessor category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q3(b) · 8 marks

    What is the use of preprocessor directives? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q1(e) · 2 marks

    Differentiate #undef and #ifndef.

    Paper P02 · page 1

View this category in the exam question bank →

QUESTION 33 · Qualifiers and Preprocessor

Why should macro parameters be parenthesised?

2 marks

Answer

Parentheses help preserve the intended grouping after token replacement.

  • Write #define SQUARE(x) ((x) * (x)) rather than x * x.
  • Parentheses do not prevent repeated evaluation of an argument.

Related Unit III exam questions →

QUESTION 34 · Qualifiers and Preprocessor

Explain object-like and function-like macros with precautions.

5 marks

Answer in brief

A macro is a name with replacement tokens processed by the preprocessor. It may be object-like or function-like.

Object-like macro

#define LIMIT 100

Function-like macro

#define SQUARE(x) ((x) * (x))

Expansion example

SQUARE(2 + 3) expands to ((2 + 3) * (2 + 3)), giving 25. Without the parameter parentheses, an expansion such as 2 + 3 * 2 + 3 would give 11. The outer parentheses also protect the full result when it is placed inside another expression.

Repeated evaluation

The parameter x occurs twice in SQUARE. Therefore its argument expression also appears twice after replacement. Do not write SQUARE(i++): the resulting expression modifies i without the ordering required by C and has undefined behaviour. Parentheses do not solve that problem. A typed function such as int square(int x) evaluates an argument once before using its parameter.

Comparison with functions

A function has a declared interface, parameter objects and a return type. A macro is token replacement and does not provide the same parameter type checking. A compiler may inline a real function, so do not assume a macro must be faster. Prefer a function for ordinary calculations unless a macro is specifically useful.

Other points

There must be no space between a function-like macro name and the opening parenthesis in its definition. #undef SQUARE removes the definition for later source. Avoid an accidental trailing semicolon in a simple expression macro.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main(void)
{
    printf("Square = %d\n", SQUARE(2 + 3));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Square = 25

Related exam questions

Related questions in the preprocessor category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q3(b) · 8 marks

    What is the use of preprocessor directives? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q1(e) · 2 marks

    Differentiate #undef and #ifndef.

    Paper P02 · page 1

View this category in the exam question bank →

QUESTION 35 · Qualifiers and Preprocessor

Distinguish #if and an ordinary if statement.

2 marks

Answer

#if selects source text during preprocessing. An ordinary if selects a path during program execution.

  • #ifdef NAME checks whether a macro is defined, even if its value is zero.
  • #if NAME tests its value as part of a permitted preprocessing expression.

Related Unit III exam questions →

QUESTION 36 · Qualifiers and Preprocessor

Explain conditional compilation and header guards.

5 marks

Answer in brief

Conditional compilation includes or excludes source text according to preprocessing conditions.

Common directives

  1. #if tests a permitted preprocessing constant expression.
  2. #ifdef NAME checks whether NAME is defined.
  3. #ifndef NAME checks whether NAME is not defined.
  4. #elif and #else select alternative groups.
  5. #endif ends the conditional group.

Example explanation

The sample sets DEBUG to 1. #if DEBUG includes the debug message in the translated source, followed by the Ready message. If DEBUG were defined as 0, that debug line would be excluded. In contrast, #ifdef DEBUG would still succeed because the macro would remain defined.

Header guard

#ifndef CODEBHAVYA_SETTINGS_H
#define CODEBHAVYA_SETTINGS_H
/* declarations */
#endif

Why a guard is needed

The first inclusion defines the guard macro and includes the guarded contents. If the same header is included again in that translation unit, the macro already exists, so the contents are skipped. This prevents many repeated declarations or definitions from being processed incorrectly. It does not make an ordinary shared object definition safe to place in every source file; use suitable extern declarations.

Uses and precautions

Conditional compilation can select debug messages, optional features or platform-specific code. Use meaningful project-prefixed macro names and correctly pair each group with #endif. Do not use a runtime variable as though its value were available during preprocessing. A C const int object is not automatically a preprocessing macro or a permitted #if value.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#define DEBUG 1
int main(void)
{
#if DEBUG
    puts("Debug enabled");
#endif
    puts("Ready");
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Debug enabled
Ready

Related exam questions

Related questions in the preprocessor category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q3(b) · 8 marks

    What is the use of preprocessor directives? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q1(e) · 2 marks

    Differentiate #undef and #ifndef.

    Paper P02 · page 1

View this category in the exam question bank →

QUESTION 37 · Recursion

What are the two essential parts of a terminating recursive solution?

2 marks

Answer

A base case supplies an answer without another recursive call; a recursive case reduces the problem towards that base case.

  • Each call must receive suitable input and make progress.
  • A missing or unreachable base case can cause uncontrolled calls.

Related Unit III exam questions →

QUESTION 38 · Recursion

Explain recursion, its base case and recursive case.

5 marks

Answer in brief

Recursion occurs when a function calls itself directly or through other functions. A useful recursive solution solves a smaller related problem and eventually reaches a base case.

Base case

The base case is a condition whose answer is known without another recursive call. In a countdown, n <= 0 can be the stopping case. In factorial, n <= 1 returns 1 for the supported non-negative inputs.

Recursive case

The recursive case calls the function with a smaller or otherwise simpler input. countdown(n - 1) moves a positive integer closer to zero. Merely writing a self-call is not enough: it must move towards termination for every supported input.

Example trace

countdown(3) prints 3 and calls countdown(2). That call prints 2 and calls countdown(1). The next call prints 1 and calls countdown(0). At zero the function returns immediately. The earlier calls then finish in reverse order. Each call has its own parameter object.

Advantages and limitations

  1. It can express naturally recursive problems clearly, such as tree traversal and divide-and-conquer algorithms.
  2. The base case and smaller subproblem can make the reasoning easy to state.
  3. Active calls require execution resources; very deep recursion can exhaust the available call capacity.
  4. Repeatedly solving the same subproblem can make a naive recursive algorithm slow.

Complexity

For a countdown from n, there are n printing calls and one base-case call. Time is O(n). With the usual model of one active call record per unfinished call, auxiliary space is O(n). C does not guarantee tail-call optimisation, so do not assume it removes the call depth.

Flowchart

Control flow for recursion with labelled true and false paths.
Explain recursion, its base case and recursive case. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void countdown(int n)
{
    if (n <= 0) { return; }
    printf("%d\n", n);
    countdown(n - 1);
}
int main(void)
{
    countdown(3);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

3
2
1

Related exam questions

Related questions in the recursion category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q8(a) · 7 marks

    Explain recursion with an example program.

    Paper P01 · page 1
  • March/April 2023 · Q9(b) · 5 marks

    What is recursion? State its advantages and disadvantages.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 39 · Recursion

State the recursive definition of factorial.

2 marks

Answer

For non-negative n, factorial(0) = 1 and factorial(n) = n × factorial(n - 1) when n > 0.

  • The zero case stops further recursive calls.
  • Each positive call reduces n by one.

Related Unit III exam questions →

QUESTION 40 · Recursion

Write and explain a recursive C program to find factorial.

5 marks

Answer in brief

Recursive factorial uses the relationship n! = n × (n - 1)!, with 0! = 1.

Algorithm

  1. Read n and accept values from 0 through 20.
  2. If n <= 1, return 1.
  3. Otherwise, return n multiplied by factorial(n - 1).
  4. Display the returned result.

Call and return trace

For n = 4, the calls ask for factorial(4), factorial(3), factorial(2) and factorial(1). The final call returns 1. The pending multiplications then produce 2 × 1 = 2, 3 × 2 = 6 and 4 × 6 = 24. The original call returns 24 to main.

Why it stops

Every recursive call decreases a supported positive n by one. It eventually reaches 1, which is a base case. Input zero is also handled by the base case. main rejects negative input before converting it to unsigned, preventing an unintended very large unsigned value.

Input and type limits

The result uses unsigned long long and the matching output format %llu. The supported limit 20 ensures that 20! fits the minimum range guaranteed for that type. A wider integer still has a finite range, so recursion cannot calculate arbitrary factorials accurately with this fixed type.

Time complexity

There is one smaller recursive call per level, with constant work apart from the call. The number of levels grows in proportion to n, giving O(n) time in the fixed-width model.

Space complexity

Pending calls wait for smaller results before multiplying. There are O(n) active calls in the usual call-record model, so auxiliary space is O(n). An iterative factorial can perform the same number of multiplications with O(1) auxiliary space.

Flowchart

Control flow for factorial with labelled true and false paths.
Write and explain a recursive C program to find factorial. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
unsigned long long factorial(unsigned int n)
{
    if (n <= 1U) { return 1ULL; }
    return n * factorial(n - 1U);
}
int main(void)
{
    int n;
    if (scanf("%d", &n) != 1 || n < 0 || n > 20) {
        puts("Unsupported input"); return 1;
    }
    printf("Factorial = %llu\n", factorial((unsigned int)n));
    return 0;
}

Sample input and output

Input

4

Output

Factorial = 24

Related exam questions

Related questions in the recursion category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q8(a) · 7 marks

    Explain recursion with an example program.

    Paper P01 · page 1
  • March/April 2023 · Q9(b) · 5 marks

    What is recursion? State its advantages and disadvantages.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 41 · Recursion

State the base case in recursive Euclid’s GCD algorithm.

2 marks

Answer

When b is zero, return a.

  • For b non-zero, use gcd(b, a % b).
  • Use supported non-negative inputs and reject the pair 0, 0 in this example.

Related Unit III exam questions →

QUESTION 42 · Recursion

Write a recursive C program to find the greatest common divisor using Euclid’s method.

5 marks

Answer in brief

Euclid’s method finds the greatest common divisor by repeatedly replacing a pair with the second value and the remainder.

Recursive rule

gcd(a, b) = a                 when b == 0
gcd(a, b) = gcd(b, a % b)     otherwise

Algorithm

  1. Read two non-negative integers within the supported range. Reject the pair 0, 0.
  2. If b is zero, return a.
  3. Otherwise, call gcd with b and a % b.
  4. Return the smaller call’s result and display it.

Worked trace

For 48 and 18, the first remainder is 12, so the next pair is (18, 12). The next remainder is 6, giving (12, 6). The next remainder is zero, giving (6, 0). The base case returns 6. Earlier calls return the same value, so the greatest common divisor is 6.

Why the rule works

Replacing a by a - q × b does not change the common divisors of a and b. The remainder a % b is exactly that difference for the integer quotient q. Thus the common divisors remain the same while the values become smaller. For positive b, the non-negative remainder is less than b, ensuring progress.

Boundary cases

gcd(a, 0) returns a for positive a; gcd(0, b) returns b for positive b. This program rejects (0, 0) rather than assigning it an elementary greatest-positive-divisor result.

Complexity

For positive inputs, Euclid’s algorithm uses O(log min(a, b)) remainder steps; more precisely the boundary cases can be expressed using 1 + min(a, b). Each one or two steps substantially reduces the smaller positive value. Recursive auxiliary space follows the number of active calls. Zero-input cases finish in constant work. This analysis treats fixed-width arithmetic operations as constant time.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
unsigned int gcd(unsigned int a, unsigned int b)
{
    if (b == 0U) { return a; }
    return gcd(b, a % b);
}
int main(void)
{
    int a, b;
    if (scanf("%d%d", &a, &b) != 2 || a < 0 || b < 0 ||
        a > 10000 || b > 10000 || (a == 0 && b == 0)) {
        puts("Unsupported input"); return 1;
    }
    printf("GCD = %u\n", gcd((unsigned int)a, (unsigned int)b));
    return 0;
}

Sample input and output

Input

48 18

Output

GCD = 6

Related exam questions

Related questions in the recursion category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q8(a) · 7 marks

    Explain recursion with an example program.

    Paper P01 · page 1
  • March/April 2023 · Q9(b) · 5 marks

    What is recursion? State its advantages and disadvantages.

    Paper P02 · page 2

View this category in the exam question bank →

QUESTION 43 · Recursion

How do recursion and iteration repeat work?

2 marks

Answer

Recursion repeats through function calls; iteration repeats through loops.

  • Recursion needs a base case and progress towards it.
  • A loop needs a suitable stopping condition and progress towards it.

Related Unit III exam questions →

QUESTION 44 · Recursion

Compare recursion and iteration with reference to factorial.

5 marks

Answer in brief

Recursion solves repeated work through calls to smaller problems. Iteration performs repeated work using a loop.

Recursion

Recursive factorial returns 1 at its base case and otherwise returns n × factorial(n - 1). Each active call waits for the smaller result. The definition closely follows the mathematical relationship. With n levels it takes O(n) time and O(n) auxiliary space in the usual call-record model.

Iteration

Iterative factorial starts result at 1 and multiplies it by each value from 2 through n. There is no chain of pending recursive calls. It also takes O(n) time, because the number of multiplications grows linearly. Only a counter and result are needed, giving O(1) auxiliary space.

Comparison

  1. Stopping: recursion uses a base case; iteration uses a loop condition or an explicit exit.
  2. Stored state: recursion can keep separate state in active calls; iteration uses explicit variables.
  3. Readability: recursive problems such as tree traversal may be easier to describe recursively.
  4. Limits: deep recursion can exhaust call resources; a loop can still be wrong or non-terminating if its progress rule is faulty.

Which should be chosen?

For a simple factorial, iteration usually avoids unnecessary call depth. For naturally recursive structures, recursion can be clearer. Neither form is always faster or always better. Count the actual work and stored state. C does not guarantee tail-call optimisation, so it cannot be assumed to reduce every recursive function to constant extra space.

Correctness

Both forms must handle 0! = 1, reject unsupported negative input and avoid overflowing the result type. Changing recursion to a loop does not remove arithmetic limits.

Comparison table

↔ Scroll horizontally on a small screen
Factorial: recursion and iteration
FeatureRecursionIteration
RepetitionSmaller function callsLoop iterations
StoppingBase caseLoop condition
TimeO(n)O(n)
Auxiliary spaceO(n) active callsO(1) variables

Related exam questions

Related questions in the recursion category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q8(a) · 7 marks

    Explain recursion with an example program.

    Paper P01 · page 1
  • March/April 2023 · Q9(b) · 5 marks

    What is recursion? State its advantages and disadvantages.

    Paper P02 · page 2

View this category in the exam question bank →