0% found this document useful (0 votes)
100 views38 pages

BESCK104E Intro To C Module 3

Module 3 of the C Programming course covers functions and arrays, detailing their definitions, declarations, and usage. It emphasizes the importance of functions in organizing code, enhancing readability, and facilitating testing, while also explaining how to declare and define functions, pass parameters, and utilize return statements. Additionally, the module includes examples to illustrate these concepts in practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views38 pages

BESCK104E Intro To C Module 3

Module 3 of the C Programming course covers functions and arrays, detailing their definitions, declarations, and usage. It emphasizes the importance of functions in organizing code, enhancing readability, and facilitating testing, while also explaining how to declare and define functions, pass parameters, and utilize return statements. Additionally, the module includes examples to illustrate these concepts in practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to C Programming [BESCK104E] Module 3

Module 3: Syllabus:

Functions: Introduction using functions, Function de inition, function declaration,


function call, return statement, passing parameters to functions, scope of variables,
storage classes, recursive functions.

Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays,
Operations on arrays,

3.1 Introduction functions:

C enables programmers to break up a program into segments called functions, which can
be written and tested separately. This allows the programmer to concentrate only on the
particular task that the function will perform. Every function receives some input,
processes it, and then produces a result.

Functions are an important aspect of programming for these reasons:

 Dividing a program into separate, well-de ined functions facilitates each aspect of the
program getting tested separately.
 Functions offer an alternative to continuously writing instructions that need to be
repeated. Instead, these instructions can be placed within a loop.
 Dividing the entire code into smaller sections (or functions) makes the program
easier to understand, code, and test for multiple separate programmers.
 If a particular function needs to be used in other programs, it can be placed in the
new program instead of writing the whole program again.
 Program memory is a serious issue in micro-computers where memory space is
limited. Functions allow programmers to be free to use in their programs.

Figure 3.1 shows how the main() function calls func1.

Figure 3.2 Functions Calling another function

Mohammed Ali, Dept of ECE, MRIT, Mandya. 1


Introduction to C Programming [BESCK104E] Module 3

Figure 3.2 shows how functions can call other functions. The igure uses a top-down
approach, in which the problem is broken down into smaller sub-problems. The sub-
problems are solved by individual functions, which are then combined to solve the main
problem. The functions have been pre-written and pre-tested, so the program is quicker
to develop. Using a top-down approach also makes the program easier to understand and
debug.

Figure 3.3 Top-down approach of solving a problem.

Figure 3.4 () function calls the func1() function twice.

Figure 3.4 shows how the main() function calls the func1() function twice. When a
program executes a set of instructions, these instructions are usually placed within a loop.
However, if those instructions need to be used again, they can be placed inside of a func1()
function wherever required. This is a better approach than writing the instructions again
and again.

3.2 Using Functions:

When using functions in C, there are several key concepts to understand:

Calling Function: When a program uses a function, it's known as a calling function.1 The
main() function is considered the calling function when it calls other functions. When the
main() function calls another function, it suspends execution and passes control to the
called function. When the called function returns some value to the calling function, the
main() function resumes execution.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 2


Introduction to C Programming [BESCK104E] Module 3

Called Function: The function that is called is known as the called function. When a called
function returns a result to the calling function, the program resumes execution in the
calling function.
Function Arguments/ Parameters: The values that are passed from the calling function to
the called function are called arguments or parameters. If a function accepts parameters,
the calling function will pass them.

Function Declaration: A function declaration identi ies a function with its name, a list of
arguments that it accepts, and the type of value it returns.

Function De inition: A function de inition consists of a function header that identi ies the
function, followed by the body of the function containing the executable code for that
function.

3.3 Function Declaration:

Before a C program can use a function, the compiler needs to know certain information
about the function beforehand. This is where the function declaration plays a crucial role.

The function declaration provides the compiler with the essential details about the
function, such as:

 Return Type: The data type of the value the function will return. If the function
doesn't return a value, the return type is speci ied as void.

 Function Name: The name of the function, which follows the same rules as variable
naming in C. The function name should clearly indicate the task it performs.

 Parameters (Arguments): The types and names of variables that the function accepts
as input.

Syntax of a Function Declaration:

return_data_type function_name(data_type variable1, data_type variable2, ...);

Example: Let's consider a function called calculate_sum that takes two integers as input
and returns their sum as an integer value. Its function declaration would be:

int calculate_sum(int num1, int num2);

Table 3.1: Valid function declarations

Mohammed Ali, Dept of ECE, MRIT, Mandya. 3


Introduction to C Programming [BESCK104E] Module 3

Key Points to Note:

 The function declaration must end with a semicolon (;).


 It is generally good practice to place function declarations at the beginning of the
program or in a separate header ile, making them easily accessible and organized.
 The function declaration is global. Therefore, the declared function can be called from
any point in the program.
 Use of argument names in the function declaration statement is optional. So both
declaration statements are valid in C

int func(int, char, loat);

or

int func(int num, char ch, loat fnum);

 A function cannot be declared within the body of another function.


 A function having void as its return type cannot return any value.
 A function having void as its parameter list cannot accept any value. So the function
declared as

void print(void);

Mohammed Ali, Dept of ECE, MRIT, Mandya. 4


Introduction to C Programming [BESCK104E] Module 3

or

void print();

does not accept any input/arguments from the calling function.

 If the function declaration does not specify any return type, then by default, the
function returns an integer value. Therefore, when a function is declared as

sum(int a, int b);

Then the function sum accepts two integer values from the calling function and in turn
returns an integer value to the caller.

 Some compilers make it compulsory to declare the function before its usage while
other compilers make it optional. However, it is a good practice to always declare the
function before its use as it allows error checking on the arguments in the function
call.

3.4 FUNCTION DEFINITION

A function de inition in C programming provides the complete set of instructions that are
executed when a function is called. It includes the function header followed by the
function body enclosed in curly braces. The function body contains the code that performs
the speci ic task of the function.

Syntax of a Function De inition:

return_data_type function_name(data_type variable1, data_type variable2, ...) {

// statements (the function body)

return(variable);

 return_data_type: This part speci ies the data type of the value that the function will
return to the caller. It could be int, loat, char, void (indicating no return value), or
other valid data types.
 function_name: This is the identi ier by which the function is known and called.
 (data_type variable1, data_type variable2, ...): This section encloses the function's
parameters or arguments.
 statements: This represents the actual code that is executed when the function is
invoked. These statements perform the function's intended operations,
computations, or actions.
 return(variable);: This statement is used to return a value from the function to the
caller.

Let's break down the syntax:

 The function header is the irst line of the de inition, and it is identical to the function
declaration, except that it does not end with a semicolon.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 5


Introduction to C Programming [BESCK104E] Module 3

 The function body is enclosed in curly braces { }. It contains the statements that de ine
what the function does.

 The return statement is used to return a value from the function. The return value
must be of the same data type as speci ied in the function header. If the function does
not return a value, the return type should be void, and the return statement is
optional.

For instance, let's de ine a simple function called add that takes two integers as input and
returns their sum as an integer:

int add(int a, int b) {


int sum = a + b;
return sum;
}

In this example:

 int add(int a, int b) is the function header, indicating that the function named add
takes two integer arguments (a and b) and returns an integer value.
 The function body contains a single statement: int sum = a + b; which calculates the
sum of the two input integers and stores it in the variable sum.
 Finally, return sum; returns the calculated sum to the location where this function
was called.

3.5 FUNCTION CALL

A function call is the mechanism by which a program invokes or executes a function. It


transfers control from the current point in the program to the function being called,
allowing the function's code to be executed. When the function completes its task, control
returns to the point immediately following the function call in the calling program.

Syntax of a Function Call:

function_name(argument1, argument2, ...);

 function_name: This is the identi ier of the function you want to call.

 (argument1, argument2, ...): This is a comma-separated list of arguments that are


passed to the function. Arguments provide the input values that the function needs
to perform its operations.

Points to Remember While Calling Functions:

Function Name: The function name and the number and type of arguments in the
function call must be the same as given in the function de inition. If there is a mismatch,
then the compiler will generate a logical error.

Order of Arguments: The order of arguments in the function call must match the order of
parameters in the function de inition.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 6


Introduction to C Programming [BESCK104E] Module 3

Type of Arguments: If the data type of the argument passed to a function does not match
with the type of parameter in the function de inition, then either garbage value or a
compile time error will be generated.

Returning Values: If a function is not declared as void, then it is expected to return a value.
If no value is returned by the function following the function call, then the behavior of the
program may be unpredictable.

Example: Write a program to add two integers using functions.

#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
int num1, num2, total;

printf("Enter the irst number: ");


scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

// Function call to calculate the sum


total = add(num1, num2);

printf("The sum of %d and %d is: %d\n", num1, num2, total);

return 0;
}

// Function de inition for adding two integers


int add(int a, int b) {
int result = a + b;
return result;
}

Output:

Enter the irst number: 20


Enter the second number: 30
Total 50

The variables declared within the function and its parameters are local to that function.
The programmer may use same names for variables in other functions.

In the sum() function, we have declared a variable result just like any other variable.

Variables declared within a function are called automatic local variables because of two
reasons.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 7


Introduction to C Programming [BESCK104E] Module 3

 First, they are local to the function. So, their effect is limited to the function. Any
change made to these variables is visible only in that function.
 Second, they are automatically created whenever the function is called and cease to
exist after control exits the function.

3.6 return Statement:

The return statement in C programming is used to terminate the execution of a function


and return control back to the calling function.

Syntax:

return expression; // expression is optional

 expression: This is an optional expression that represents the value to be returned to


the calling function. If no expression is provided, the return statement simply
terminates the function.

How the return statement works:

1. Execution Termination: Upon encountering a return statement, the function


immediately halts execution, regardless of whether there are any remaining
statements in the function body.

2. Value Return (Optional): If an expression is included after the return keyword, the
expression is evaluated, and its value is returned to the calling function. The data type
of the expression should match the return type speci ied in the function header.

3. Control Transfer: Control is transferred back to the point in the calling function where
the function call was made. Execution resumes from the statement immediately
following the function call.

Example:

Consider a function calculate_area that calculates the area of a rectangle:

int calculate_area(int length, int width) {


int area = length * width;
return area; // Returns the calculated area
}

In this example:

 The return area; statement returns the value stored in the area variable to the caller.
 If the function was called as result = calculate_area(5, 10);, the value 50 (5 * 10)
would be returned and assigned to the variable result in the calling function.

Important Points about the return Statement:

 Functions with void Return Type: Functions declared with a return type of void do
not return a value. In such cases, the return statement is optional and can be used
solely to exit the function prematurely.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 8


Introduction to C Programming [BESCK104E] Module 3

 Return Type Consistency: The data type of the value returned by the return statement
must be consistent with the return type speci ied in the function header. Mismatches
can lead to compilation errors or unexpected behavior.

 Single Return Value: A function can return only one value at a time using the return
statement.

 Unreachable Code: Any statements appearing after a return statement within the
same block of code become unreachable and will not be executed.

The return statement can appear multiple times within a function, but only one return
statement will be executed each time the function is called. As soon as a return is
encountered, the function stops executing, and control lows back to the location where
the function was called.

#include <stdio.h>
int check_relation(int a, int b);

int main() {
int num1, num2, res;

printf("Enter the irst number: ");


scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

res = check_relation(num1, num2);

if (res == 1) {
printf("%d is greater than %d\n", num1, num2);
} else if (res == -1) {
printf("%d is less than %d\n", num1, num2);
} else {
printf("%d is equal to %d\n", num1, num2);
}
return 0;
}

// Function to check the relation between two integers

int check_relation(int a, int b) {


if (a > b) {
return 1; // a is greater than b
} else if (a < b) {
return -1; // a is less than b
} else {
return 0; // a is equal to b
}
}

Mohammed Ali, Dept of ECE, MRIT, Mandya. 9


Introduction to C Programming [BESCK104E] Module 3

Inside this function, there are three return statements within different if and else if blocks.

 If a is greater than b, the function returns 1.


 If a is less than b, the function returns -1.
 If a is equal to b, the function returns 0.

Only one of these return statements will be executed on each call to the function,
depending on the relationship between a and b.

3.7 PASSING PARAMETERS TO FUNCTIONS

When a function is called, you can pass values to it. These values are called arguments or
parameters, and they provide the function with the information it needs to perform its
task. There are two main ways to pass parameters to a function in C: call by value and call
by reference.

3.7.1 Call by Value

In call by value, a copy of the actual value of an argument is passed to the function.
Changes made to the parameter inside the function do not affect the original variable in
the calling function. This is because the function works with a copy of the data. This is the
default mechanism in C for passing arguments.

Example:

#include <stdio.h>

void add(int n); // Function declaration

int main() {
int num = 2;
printf("\n The value of num before calling the function = %d", num);

add(num); //Passing the value of num

printf("\n The value of num after calling the function = %d", num);
return 0;
}

void add(int n) {

n += 10;
printf("\n The value of num in the called function = %d", n);

Output:

The value of num before calling the function = 2


The value of num in the called function = 12
The value of num after calling the function = 2

Mohammed Ali, Dept of ECE, MRIT, Mandya. 10


Introduction to C Programming [BESCK104E] Module 3

In this example, the value of num (which is 2) is passed to the add function. Inside add, n
(which is a copy of num) is incremented by 10. However, this change does not affect the
original num variable in the main function.

Advantages of Call by Value:

 The original variables in the calling function are protected from unintentional
modi ications.
 It enhances code readability and makes it easier to reason about the behavior of
functions, as you know that the original data won't be altered.

3.7.2 Call by Reference

In call by reference, the function receives a reference or a pointer to the actual variable.
This allows the function to directly access and modify the original variable. To pass
parameters by reference, you need to use pointers.

Example:

#include <stdio.h>

void add(int *n); // Function declaration

int main() {
int num = 2;
printf("\n The value of num before calling the function = %d", num);

add(&num); //Passing address of num

printf("\n The value of num after calling the function = %d", num);
return 0;
}

void add(int *n) {

*n += 10;
printf("\n The value of num in the called function = %d", *n);

Output:

The value of num before calling the function = 2


The value of num in the called function = 12
The value of num after calling the function = 12

In this example, the address of num is passed to the add function. Inside add, the value at
the address pointed to by n (which is the original num) is incremented by 10. This change
directly affects the num variable in the main function.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 11


Introduction to C Programming [BESCK104E] Module 3

Advantages of Call by Reference:

 Ef icient Data Modi ication: It provides a direct way to modify the original variables
in the calling function, eliminating the need to copy large amounts of data.
 Multiple Return Values: You can effectively return multiple values from a function by
modifying variables passed by reference.
When to Use Call by Value and Call by Reference

 Call by Value: Use when you don't want the function to modify the original variables.
This is suitable for situations where you are passing data to the function for
computation or processing without altering the original source.
 Call by Reference: Use when you need the function to directly modify the original
variables. This is often used for tasks like swapping values, modifying arrays, or
returning multiple values from a function.

Example: Write a function to swap the value of two variables using call by value and call
by reference.

#include <stdio.h>

void swap_by_value(int a, int b);


void swap_by_reference(int *a, int *b) ;

int main() {
int a = 2, b = 4;
printf("\n In main() a = %d and b = %d", a, b);

swap_by_value(a, b); // Call the swap function using call by value


printf("\n In main() a = %d and b = %d", a, b);

swap_by_reference(&a, &b); // Call the swap function using call by reference


printf("\n In main() a = %d and b = %d", a, b);
return 0;
}

// Function to swap the values of two variables using call by value

void swap_by_value(int a, int b) {


int temp = a;
a = b;
b = temp;
printf("\n In swap_by_value (Call By Value Method) a = %d and b = %d", a, b);
}

// Function to swap the values of two variables using call by reference

void swap_by_reference(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;

Mohammed Ali, Dept of ECE, MRIT, Mandya. 12


Introduction to C Programming [BESCK104E] Module 3

printf("\n In swap_by_reference (Call By Reference Method) a = %d and b = %d", *a,


*b);
}

Explanation:

This program demonstrates both call by value and call by reference in a single program
using two functions: swap_by_value and swap_by_reference.

swap_by_value Function (Call by Value):

 This function takes two integer arguments, a and b, but it receives copies of their
values.
 Inside the function, the values are swapped using a temporary variable temp.
 However, these changes only affect the local copies within the swap_by_value
function, leaving the original variables in the main function unchanged.

swap_by_reference Function (Call by Reference):

 This function takes two pointers (*a and *b) as arguments, which are the memory
addresses of the variables to be swapped.
 By using pointers, the function directly accesses and modi ies the original variables
in the main function.
 A temporary variable temp is used to facilitate the swapping process.

main Function:

 Two integer variables, a and b, are declared and initialized.


 swap_by_value is called irst, passing a and b by value. Observe that the values of a
and b remain unchanged in the main function after this call.
 swap_by_reference is then called, passing the addresses of a and b using the &
operator. This call successfully swaps the values of a and b in the main function.

This example clearly illustrates the difference between call by value and call by reference:
call by value protects the original variables, while call by reference allows functions to
directly modify the variables passed to them.

3.8 Scope of a Variable

The scope of a variable in C refers to the region of the program where that variable is
visible and can be accessed. There are four main types of scope in C:

1. Block Scope:

 A variable with block scope is declared inside a block (a section of code enclosed by
curly braces {}).
 These variables are only accessible within the block they are de ined in.
 Once the execution low exits the block, the variable is no longer accessible.

2. Function Scope:

Mohammed Ali, Dept of ECE, MRIT, Mandya. 13


Introduction to C Programming [BESCK104E] Module 3

 Variables with function scope are declared inside a function.


 These variables are local to the function and can be accessed from anywhere within
that function.
 They are not visible or accessible outside of the function.
 Function scope only applies to goto label names.
 The use of goto statements is generally discouraged as it can make code harder to
understand and maintain.

3. Program Scope (Global Scope):

 Variables with program scope are also known as global variables.


 They are declared outside of any function, typically at the beginning of the program
ile.
 Global variables are accessible from any part of the program, including all functions.
 Their lifetime extends throughout the entire program execution.

4. File Scope:

 Variables with ile scope are declared outside any function, but their visibility is
limited to the ile in which they are de ined.
 To allow a global variable to have ile scope, it needs to be declared with the static
keyword.
 Other source iles cannot directly access these variables.
 File scope is particularly useful when you want to limit the accessibility of a global
variable to a speci ic ile, preventing potential con licts with variables of the same
name in other iles.

Example: It illustrates name con licts between local and global variables:

#include <stdio.h>

int x = 10; // Global Variable

int main() {
int x = 2; // Local Variable
printf("\n The value of x in the main() = %d", x);
print();
return 0;
}

void print() {
int x = 40; // Local Variable
printf("\n The value of x in the print() = %d", x);
}

Output:

The value of x in the main() = 2


The value of x in the print() = 40

Mohammed Ali, Dept of ECE, MRIT, Mandya. 14


Introduction to C Programming [BESCK104E] Module 3

In this example, the variable x is declared in three different places:

1. Globally: int x = 10; This variable has program scope and is accessible throughout the
entire program.
2. Locally in main: int x = 2; This variable has block scope within the main function,
overriding the global x variable within the main function.
3. Locally in print: int x = 40; This variable also has block scope, limited to the print
function, and overrides the global x within the print function.

Key Points:

 Local variables take precedence over global variables with the same name. When a
local variable is declared with the same name as a global variable, the local variable
will be used within its scope.

 Using global variables extensively can lead to issues as programs become larger and
more complex. It's often recommended to minimize the use of global variables and
instead pass data between functions using parameters.

3.9 Storage classes

Storage classes in C determine the following characteristics of a variable:

 Scope: Where the variable can be accessed (its visibility within the program).
 Lifetime: How long the variable exists in memory during program execution.
 Initial Value: The default value assigned to the variable when it is declared.

C has four main storage classes:

1. auto:

Syntax: auto data_type variable_name; (The keyword auto is often omitted, as it's the
default for local variables).

Scope: Local (within the block or function where it's declared).

Lifetime: Exists only while the block or function is executing. Created when the block is
entered and destroyed when the block exits.

Initial Value: Garbage (unpredictable value).

2. extern:

Syntax: extern data_type variable_name;

Scope: Global (accessible from all source iles in the program).

Lifetime: Exists throughout the entire program execution.

Initial Value: Zero.

Purpose: Used to declare a variable that is de ined in another source ile, allowing
multiple iles to share the same global variable.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 15


Introduction to C Programming [BESCK104E] Module 3

3. register:

Syntax: register data_type variable_name;

Scope: Local (within the block or function where it's declared).

Lifetime: Exists only while the block or function is executing.

Initial Value: Garbage (unpredictable value).

Purpose: A request to the compiler to store the variable in a CPU register for faster access.
The compiler may not always honor this request due to register availability constraints.

4. static:

Syntax: static data_type variable_name;

Scope:

Local: If declared inside a function, it's accessible only within that function.

Global: If declared outside any function, it's accessible only within the source ile where
it's declared.

Lifetime: Exists throughout the entire program execution.

Initial Value: Zero.

Purpose:

Local: To retain the variable's value between function calls.

Global: To limit the variable's scope to the current source ile, preventing access from
other iles.

Table 3.2 Features of different storage classes in C:

auto Storage extern register Storage


FEATURE static Storage Class
Class Storage Class Class

Local: Accessible
within the
Accessible block/function in
Accessible
within all the Accessible within which it is
within the
Accessibility functions that the block in which declared.Global:
function where Accessible only within
are part of the it is declared.
it's declared. the source ile in which
program.
it is declared.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 16


Introduction to C Programming [BESCK104E] Module 3

Exists when the


Exists when function is
the function is entered; ceases to Local: Retains value
entered; ceases Exists exist when the between function
Existence to exist when throughout control returns calls.Global: Preserves
the control the program. from the function value in program
returns from or when the block memory.
the function. in which it was
declared exits.

Default
Garbage Zero Garbage Zero
value

Example demonstrating the static storage class:

#include <stdio.h>

void print() {
static int x = 0; // Static variable initialized once
x++;
printf("\n Static integer variable, x = %d", x);
int y = 0; // Automatic variable
y++;
printf("\n Integer variable, y = %d", y);
}

int main() {
print();
print();
print();
return 0;
}

Output:

Static integer variable, x = 1


Integer variable, y = 1
Static integer variable, x = 2
Integer variable, y = 1
Static integer variable, x = 3
Integer variable, y = 1

In this example:

 x is a static variable inside the print function. It is initialized only once (to 0) and
retains its value between multiple calls to the print function. Therefore, x increments
with each call.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 17


Introduction to C Programming [BESCK104E] Module 3

 y is an automatic variable. It is re-initialized to 0 each time the print function is called.


Hence, its value is always printed as 1.

Key Points:

 Default Storage Class: The auto storage class is implicit for local variables. You can
use the auto keyword explicitly, but it's often omitted.

 Importance of Storage Classes: Understanding storage classes is crucial for managing


variables effectively, controlling their visibility, and ensuring their appropriate
lifetime and initialization. This knowledge helps in writing more ef icient and well-
structured C programs.

3.10 Recursive functions

Recursive functions are de ined as functions that call themselves within their own
de inition. This technique is bene icial for breaking down problems into smaller, similar
subproblems. Every recursive function must have a base case which is a condition to stop
the recursion. The function would call itself in initely without a base case and lead to a
stack over low error.

Every recursive function must have:

 Base case: to stop the recursion.


 Recursive case: to call the function recursively with a modi ied input to bring it closer
to the base case.

The basic steps of a recursive program are:

1. Specify the base case. This is the condition that will stop the recursion.

2. Check to see whether the current value being processed matches with the value of
the base case.

3. If it matches, the recursion stops. If not, divide the problem into smaller or simpler
sub-problems.

4. Recursively call the function with the sub-problems.

5. Combine the results of the sub-problems.

6. Return the result of the entire problem.

Example: The factorial of a number can be calculated recursively. The factorial of n is the
product of all positive integers less than or equal to n. For example, the factorial of 5
(written as 5!) is:

5! = 5 * 4 * 3 * 2 * 1 = 120

The factorial of a number can be de ined recursively as follows:

 n! = 1 (if n = 0 or n = 1)

 n! = n * (n-1)! (if n > 1)

Mohammed Ali, Dept of ECE, MRIT, Mandya. 18


Introduction to C Programming [BESCK104E] Module 3

This can be written as 5! = 5 * 4! where 4! = 4 * 3

Therefore

5! = 5 * 4 * 3!

Similarly, we can also write. 5! = 5 * 4 * 3 * 2!

Expanding further

5! = 5 * 4 * 3 * 2 * 1!

We know, 1! = 1

Therefore, the series of problems and solutions can be given as shown in Figure 11.6.

Above igure illustrates problems and solutions for recursion. It shows how a problem (in
this case, calculating the factorial of a number) can be broken down into smaller sub-
problems, and how the results of the sub-problems can be combined to solve the original
problem.

Example: Calculate the factorial of a number recursively.

#include <stdio.h>
int Fact(int);

int main()
{
int num, factorial;
printf("\n Enter the number: ");
scanf("%d", &num);
factorial Fact(num);
printf("\n Factorial of Xd = %d", num, factorial);
return 0;
}

int Fact(int n)
{
if (n==1)
return 1;
else
return (n * Fact(n-1));
}

Mohammed Ali, Dept of ECE, MRIT, Mandya. 19


Introduction to C Programming [BESCK104E] Module 3

From the example, let's analyze the basic steps of a recursive program for calculating the
factorial of a number:

1. Specify the base case: The base case is when n is equal to 1.

2. Check to see whether the current value being processed matches with the value of
the base case: The if statement checks if n is equal to 1.

3. If it matches, the recursion stops: If n is equal to 1, the function returns 1.

4. If not, divide the problem into smaller or simpler sub-problems: If n is not equal to 1,
the function calls itself with the value of n-1. This is the recursive step.

5. Combine the results of the sub-problems: The result of the recursive call Fact(n-1) is
multiplied by n to calculate the factorial of n.

6. Return the result of the entire problem: The result of the multiplication is returned
by the function.

3.10.1 Greatest Common Divisor (GCD)

The greatest common divisor (GCD) of two integers is the largest integer that divides both
numbers without leaving a remainder. The GCD can be calculated using Euclid's
algorithm, which can be implemented recursively.

Euclid's Algorithm:

The algorithm states that the GCD of two numbers, a and b, where a > b, can be found as
follows:

 If b is 0, then the GCD is a.


 Otherwise, the GCD of a and b is the same as the GCD of b and the remainder of a
divided by b (denoted as a % b).

Recursive Implementation:

#include <stdio.h>

int GCD(int x, int y);

int main() {
int num1, num2, result;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

result = GCD(num1, num2);

printf("GCD of %d and %d = %d\n", num1, num2, result);

return 0;
}

Mohammed Ali, Dept of ECE, MRIT, Mandya. 20


Introduction to C Programming [BESCK104E] Module 3

int GCD(int x, int y) {


if (y == 0)
return x;
else
return GCD(y, x % y);
}

Working Example:

Let's calculate the GCD of 62 and 8:

1. GCD(62, 8): 8 is not 0, so we calculate GCD(8, 62 % 8), which is GCD(8, 6).


2. GCD(8, 6): 6 is not 0, so we calculate GCD(6, 8 % 6), which is GCD(6, 2).
3. GCD(6, 2): 2 is not 0, so we calculate GCD(2, 6 % 2), which is GCD(2, 0).
4. GCD(2, 0): Now, b is 0, so the GCD is a, which is 2.

Therefore, the GCD of 62 and 8 is 2. The provided C program implements this recursive
logic to compute the GCD of any two input integers.

3.10.2 Finding Exponents

Calculate exponents using recursion. The task is to ind the value of x raised to the power
of y (xy). This can be achieved through repeated multiplication.

Working:

The base case is when y is 0, in which case the result is always 1 (x0 = 1).
For other values of y, we can recursively de ine the problem as: xy = x * xy-1

C Program:

#include <stdio.h>

int exp_rec(int x, int y) ;


int main() {
int num1, num2, result;

printf("Enter the two numbers: ");


scanf("%d %d", &num1, &num2);

result = exp_rec(num1, num2);

printf("%d to the power of %d = %d\n", num1, num2, result);

Mohammed Ali, Dept of ECE, MRIT, Mandya. 21


Introduction to C Programming [BESCK104E] Module 3

return 0;
}

int exp_rec(int x, int y) {


if (y == 0)
return 1;
else
return x * exp_rec(x, y - 1);
}

Explanation:

1. Base Case: The if (y == 0) statement checks for the base case. When the exponent y
is 0, the function returns 1.

2. Recursive Step: The else block implements the recursive step. It multiplies x with the
result of calling exp_rec with x and y-1. This effectively reduces the exponent by 1 in
each recursive call, moving closer to the base case.

This recursive approach effectively calculates the exponent by breaking it down into
smaller, self-similar subproblems, making the computation easier to manage.

3.10.3 Fibonacci series

The Fibonacci series is a sequence of numbers where each number is the sum of the two
preceding numbers. The series typically starts with 0 and 1.

The Fibonacci series can be mathematically de ined as follows:

 Fib(0) = 0
 Fib(1) = 1
 Fib(n) = Fib(n - 1) + Fib(n - 2) for n > 1

Recursive Program:
#include <stdio.h>

int Fibonacci(int n) ;

int main() {
int n, i;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci series: ");


for (i = 0; i < n; i++) {
printf("%d ", Fibonacci(i));
}

return 0;
}

Mohammed Ali, Dept of ECE, MRIT, Mandya. 22


Introduction to C Programming [BESCK104E] Module 3

int Fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (Fibonacci(n - 1) + Fibonacci(n - 2));
}

Explanation:

 Base Cases: The if and else if statements handle the base cases for Fib(0) and Fib(1),
returning 0 and 1, respectively.

 Recursive Step: The else block implements the recursive step. It calculates the
Fibonacci number at position n by adding the results of Fibonacci(n - 1) and
Fibonacci(n - 2).

 Loop for Output: The for loop in the main function iterates n times, calling the
Fibonacci function for each value of i and printing the result.

Working:

Let's break down how the program calculates the irst ive Fibonacci numbers (n = 5):

1. Fibonacci(0): Returns 0 (base case).


2. Fibonacci(1): Returns 1 (base case).
3. Fibonacci(2): Calls Fibonacci(1) (returns 1) + Fibonacci(0) (returns 0) = 1.
4. Fibonacci(3): Calls Fibonacci(2) (returns 1) + Fibonacci(1) (returns 1) = 2.
5. Fibonacci(4): Calls Fibonacci(3) (returns 2) + Fibonacci(2) (returns 1) = 3.

The output of the program for n = 5 would be:

Fibonacci series: 0 1 1 2 3

Each call to Fibonacci(n) with n > 1 triggers two more recursive calls, creating a tree-like
structure of computations. This process continues until the base cases are reached, and
the results are combined back up the call stack to produce the inal Fibonacci number.

3.11 Types of Recursion

1. Direct Recursion

A function is said to be directly recursive if it explicitly calls itself within its de inition.
This is the most common type of recursion.

Example: The factorial function:

int Fact(int n) {
if(n==1)
return 1;
else

Mohammed Ali, Dept of ECE, MRIT, Mandya. 23


Introduction to C Programming [BESCK104E] Module 3

return n * Fact(n-1);
}

In this example, the function Fact(n) directly calls itself with a modi ied input (n-1).

2. Indirect Recursion

Indirect recursion occurs when a function calls another function, which eventually leads
back to the original function being called again. This can form a chain of function calls that
ultimately result in the initial function being executed recursively.

Example: Let's say we have two functions:

 Function A calls function B.

 Function B calls function A.

This creates an indirect recursion where A is indirectly called again through the execution
of B.

3. Tail Recursion

Tail recursion is a special case of recursion where the recursive call is the last operation
performed in the function. In other words, there are no pending operations to be executed
after the recursive call returns.

Figure (a) non-tail-recursive function Figure (b) tail-recursive function.

The key difference is whether there are pending operations after the recursive call.

 Non-tail-recursive: The function Fact(n) performs a multiplication operation (n *


Fact(n-1)) after the recursive call (Fact(n-1)). This means the result of the recursive
call must be remembered and used for further computation.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 24


Introduction to C Programming [BESCK104E] Module 3

 Tail-recursive: The function Fact(n, res) directly returns the result of the recursive
call (Fact(n-1, n * res)) without any further operations. The multiplication is
performed before the recursive call, and the result is directly passed as an argument.

Tail recursion is often preferred for its ef iciency. Compilers can optimize tail-recursive
functions by transforming them into iterative loops, eliminating the overhead of multiple
function calls and preventing potential stack over low issues.

4. Linear Recursion and Tree Recursion.

In linear recursion, each recursive call makes at most one additional recursive call. This
results in a linear chain of function calls. The factorial function is an example of linear
recursion because each call to Fact(n) only leads to one more recursive call Fact(n-1).

In tree recursion, each recursive call can lead to multiple recursive calls, resulting in a
tree-like structure of function calls. The Fibonacci sequence is a classic example of tree
recursion. When calculating Fibonacci(n), the function makes two recursive calls:
Fibonacci(n-1) and Fibonacci(n-2).

Above program depicts the tree structure formed by the recursive calls in the Fibonacci
function. Each node represents a call to the function with a speci ic value of n. The
branching indicates that each call (except for the base cases) triggers two further
recursive calls.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 25


Introduction to C Programming [BESCK104E] Module 3

3.12 Arrays

Introduction:

An array is a data structure that stores a collection of similar elements. These elements
are stored in consecutive memory locations and are referenced by an index (also known
as the subscript). The index of the irst element in an array is 0.

For example: If 20 students in a class take a test, the 20 marks for each student can be
stored in an array. The marks of the irst student would be stored at index 0, the marks of
the second student at index 1, and so on.

Arrays can be used in many everyday applications, including:

 Storing the marks of students in a class.


 Storing the names of employees in a company.
 Storing the days of the month.
 Storing the names of customers.

3.13 Declaration of Arrays

Before using an array, the array variable must be declared. Declaring an array means
specifying three things:

 Data_type: The kind of values it can store, for example int, char, loat, double.
 Name: The name of the array.
 Size: The maximum number of values that the array can hold.

Arrays are declared using the following syntax:

Data_type name[size];

Example: To declare an array of integers with the name marks and a size of 10, the
declaration would be:

int marks[10];

Figure 3.5 Memory representation of an array of 10 elements.

In the declaration above,

 int speci ies the data type, indicating the array will hold integer values.
 marks is the chosen name for the array.
 10 speci ies the size, meaning the array can store up to 10 integer values.

Important points to remember about arrays

 C does not allow declaring an array whose size is not known at compile time.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 26


Introduction to C Programming [BESCK104E] Module 3

 For example, the following declarations are illegal in C:

 It is good programming practice to de ine the size of an array as a symbolic constant.


This makes your code more readable and easier to modify.
 For example, the following code de ines a symbolic constant N with a value of 100
and then uses it to declare an array named arr :

 The size of the array can be speci ied using an expression, but the components of the
expression must be available for evaluation at compile time. The following array
declarations are valid in C:

 C array indices start from 0. So for an array with N elements, the index of the last
element is N-1.
 C never checks the validity of the array index — neither at compile time nor at run
time. This means that if you try to access an element outside of the bounds of the
array, your program may crash or produce unexpected results. For example, if you
declare an array of size 10, and try to access the 11th element as marks, the C
compiler will not raise any error. However, the result of running such code is
unpredictable and may lead to errors.

3.14 Accessing the elements of an array:

To access individual elements of an array, you must use the array name with the subscript.
The subscript is an integral value or an expression that indicates the relative position of
the element in the array. C array indices start from 0. So for an array with N elements, the
index of the last element is N - 1.

int i;
for(i = 0; i <= 9; i++)
marks[i] = -1;

In the above code, the irst element of the array, marks, is set to -1. The value of the index
(1) is incremented, and the next value, marks, is set to -1. This continues until all 10
elements of the array are set to -1.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 27


Introduction to C Programming [BESCK104E] Module 3

Note that C does not allow declaring an array whose number of elements is not known at
compile time.

3.15 Calculating the Address of an Element

The address of an array name is the symbolic reference to the address of the irst byte of
the array. When you use the subscript of the array, you are actually referring to the offset
from the beginning of the array to the element being referenced.

Since an array stores all its elements in consecutive memory locations, storing data in the
ith element requires i memory locations after the base address. So the address of the ith
element can simply be calculated using the base address. The formula for doing this
calculation is: Address of ith element = (Base Address) + (i * Size of one element)

Example: Given an array int marks[ ] = {99, 67, 78, 56, 88, 90, 78, 85, 56, 80}. Calculate
the address of marks[4] if base address is 1000.

Solution: We know that storing an integer value requires 2 bytes. Therefore,

Address(Marks) = 1000 + (4 * 2) = 1008

Note that when writing arr[i], the compiler interprets it as the contents of memory slot
which is i slots away from the beginning of the array.

3.16 Calculating the Length of an Array

The length of the array is given by the number of elements stored in it. The general
formula to calculate the length of the array is:

Length = upper_bound - lower_bound + 1

where, upper_bound is the index of the last element in the array.


lower_bound is the index of the irst element in the array.

Usually, lower_bound is zero but this is not compulsory as we can have an array whose
index may start from any non-zero value.

Example: Let Age[ ] be an array of integers such that Age[0] = 2 Age[1] = 5 Age[2] = 3
Age[3] = 1 Age[4] = 7. Show the memory representation of the array and calculate its
length.

Solution:

Lower_bound = 1

Upper_bound = 5

Therefore, length = 5 - 1 + 1 = 5

3.17 Storing values in Array: There are three ways to store values in an array: during the
declaration, by inputting values from the keyboard and assign values to the individual
elements.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 28


Introduction to C Programming [BESCK104E] Module 3

Figure 12.4 Storing values in an array.

3.17.1 Initializing Arrays during Declaration

Elements of an array can be


initialized at the time of declaration
by providing values for every
element in the array. The number of
values that can be provided should
not be more than the number of
elements in the array. If the number
of values speci ied is less than the
size of the array, the remaining
elements are illed with zeroes.

Figure shows an example of array


initialization.

3.17.2 Inputting Values from the Keyboard

An array can be illed by inputting values from the keyboard in this method. The scanf()
function can be used in a loop, typically a for loop or a while loop to read values from the
keyboard and assign them to the elements of the array.

The example shows how to


initialize an array by reading
input values from the user using
the scanf() function.

3.17.3 Assigning Values to Individual Elements

The third way is to assign values to individual elements of the array by using the
assignment operator. Any value that is compatible with the data type of the array can be
assigned to an individual element. This method involves directly assigning values to
speci ic array elements using the assignment operator.

Example: marks [3]= 100;

Mohammed Ali, Dept of ECE, MRIT, Mandya. 29


Introduction to C Programming [BESCK104E] Module 3

This statement assigns the value 100 to the fourth element of the array marks. Note that
since arrays in C are zero-indexed, marks refers to the fourth element. You cannot assign
one array to another array, even if the data type and size of both arrays are the same. In
such cases, you must copy the value of every element of the irst array into the element of
the second array.

3.18 Operations on Arrays

Traversing an Array: Traversing an array means accessing each element in the array for a
speci ic purpose, like displaying elements, calculating the sum or average, or counting the
total number of elements.

Algorithm:

Step 1. Initialization: SET i = lower_bound


Step 2. Repeat Steps 3 to 4 While i <= upper_bound
Step 3. Process element at index i
Step 4. SET i = i + 1
Step 5. END OF LOOP

Mohammed Ali, Dept of ECE, MRIT, Mandya. 30


Introduction to C Programming [BESCK104E] Module 3

Inserting an Element: Inserting an element in an array means adding a new element to an


existing array. Inserting an element at the end of an array is straightforward. Inserting an
element into the middle of an array requires shifting existing elements to create space for
the new element.

Algorithm to Append an Element:

Step 1. Set upper_bound = upper_bound + 1


Step 2. Set a[upper_bound] = val

Algorithm to Insert an Element in the Middle of an Array:

Example:

Figure illustrates inserting the value 100


into an existing array at a speci ied position.
To do this, the existing elements are shifted
to the right to make space for the new
element.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 31


Introduction to C Programming [BESCK104E] Module 3

Deleting an Element: Deleting an element from an array means removing an existing


element. Deleting an element from the end of an array is a simple process. Deleting an
element from the middle of an array requires shifting the remaining elements to ill the
gap created by the deleted element.

Algorithm to Delete an Element From the End of an Array:

Step 1. SET upper_bound = upper_bound - 1

Algorithm to Delete an Element from the Middle of an Array:

Example:

Figure illustrates the process of deleting an


element from an array and shifting the
remaining elements to ill the space. The igure
shows an array named Data with six values: 45,
23, 34, 12, 56, and 20.

The goal is to delete the value 34, which is


located at index 2 (Data).

Step (a): The initial state of the array is shown.

Step (b): The element to be deleted, 34, is


indicated.

Step (c): The element 34 is removed from the


array.

Step (d): The element 12, which was originally at index 3, is shifted to index 2 to occupy
the space vacated by the deleted element.

Step (e): Similarly, the element 56 is shifted from index 4 to index 3, and the element 20
is shifted from index 5 to index 4.

The inal state of the array shows the remaining elements shifted to the left to ill the gap
created by the deleted element. The array now contains ive values: 45, 23, 12, 56, and 20.

Merging Two Arrays: Merging two arrays means combining the elements of two arrays
into a third array. If the arrays are unsorted, the merging process involves simply copying
the elements of the irst array followed by the elements of the second array into the third
array. However, if the arrays are sorted, a speci ic algorithm is required to ensure that the
resulting merged array is also sorted.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 32


Introduction to C Programming [BESCK104E] Module 3

Algorithm to Merge Two


Unsorted Arrays:

1. Copy all the elements of the


irst array to the third array.
2. Copy all the elements of the
second array into the third array, starting at the next available position.

Algorithm to Merge Two Sorted Arrays:

1. Compare the irst elements


of both input arrays.

2. Copy the smaller element to


the merged array.

3. Increment the index of the array from which the element was copied.

4. Repeat steps 1-3 until all elements from both input arrays have been copied into the
merged array.

Example:

Mohammed Ali, Dept of ECE, MRIT, Mandya. 33


Introduction to C Programming [BESCK104E] Module 3

Searching for an Element in an Array: Searching for an element in an array involves


inding the position of a particular value within the array. There are two common methods
for searching an array: Linear Search and Binary Search.

Linear search works on both sorted and unsorted arrays, and involves comparing each
element of the array sequentially with the target value.

Linear Search Algorithm:

Step 1. INITIALIZE: SET POS = -1


Step 2. Repeat Steps 3 and 4 While i < N
Step 3. IF a[i] = VAL then SET POS = i Go To Step 5
Step 4. SET i = i + 1
Step 5. END OF LOOP

Mohammed Ali, Dept of ECE, MRIT, Mandya. 34


Introduction to C Programming [BESCK104E] Module 3

Step 6. IF POS = -1 then Print “VALUE IS NOT


PRESENT” ELSE Print “VALUE IS PRESENT AT
POSITION”, POS

Binary Search is more ef icient and works only on sorted arrays by repeatedly dividing
the search interval in half.

Binary Search Algorithm:

1. INITIALIZE: SET BEG = lower_bound, END = upper_bound, POS = -1


2. Repeat Step 3 While BEG <= END
3. SET MID = (BEG + END)/2
4. IF a[MID] = VAL, then POS = MID, Go to Step 6
5. ELSE IF VAL < a[MID], then END = MID - 1 ELSE BEG = MID + 1
6. END OF LOOP

Mohammed Ali, Dept of ECE, MRIT, Mandya. 35


Introduction to C Programming [BESCK104E] Module 3

7. IF POS = -1, then PRINT “VALUE IS NOT PRESENT IN THE ARRAY” ELSE PRINT “VALUE
IS PRESENT AT POSITION”, POS

Sorting an Array: Sorting an array means arranging the elements of an array in a speci ic
order, such as ascending or descending order. There are many different sorting
algorithms, including bubble sort, insertion sort, selection sort, merge sort, and quicksort.
The choice of algorithm depends on factors such as the size of the array and the desired
ef iciency.

Example:

A simple example of sorting is arranging the elements of an array in ascending order. For
instance, if the initial array is {5, 2, 8, 1, 9}, the sorted array would be {1, 2, 5, 8, 9}.

int main(void)
{
int iNum, i, j, iaArr[10], iTemp;
printf("\n Enter no of elements\n");
scanf("%d", &iNum);
printf("\n Enter the elements\n");
for(i=0;i<iNum;i++)
scanf("%d", &iaArr[i]);
for(i=0;i<iNum;i++)
{
for(j=0;j<iNum-i-1;j++)

Mohammed Ali, Dept of ECE, MRIT, Mandya. 36


Introduction to C Programming [BESCK104E] Module 3

{
if(iaArr[j] > iaArr[j+1])
{
iTemp = iaArr[j];
iaArr[j] = iaArr[j+1];
iaArr[j+1] = iTemp;
}
}
}
printf("\nThe Sorted array is \n");
for(i=0;i<iNum;i++)
printf("%d\t",iaArr[i]);
printf("\n");
return 0;
}

Output:

Enter no of elements
5
Enter the elements
21657
The Sorted array is
12567

3.19 Passing array to function:

Passing data in C to functions can be either by passing individual array elements or by


passing the entire array.

Passing Individual Elements:

Passing Data Values: The individual elements of an


array can be passed in the same manner as other
data types. The only condition is that the data type
of the function parameter must match with the data
type of the array element.

Figure shows an example of passing the value of


array elements to a called function.

Passing Addresses: You can pass the address of an individual array element by preceding
the indexed array element with the address operator (&).

Passing the Entire Array: To pass the entire array to a function, we can simply pass the
name of the array to the function.

Figure illustrates the code in which we pass the entire array to the calling function.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 37


Introduction to C Programming [BESCK104E] Module 3

If a function receives an array that does not change


it, then the array should be received as a constant
array by adding the keyword const before the data
type of the array.

Mohammed Ali, Dept of ECE, MRIT, Mandya. 38

You might also like