BESCK104E Intro To C Module 3
BESCK104E Intro To C Module 3
Module 3: Syllabus:
Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays,
Operations on arrays,
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.
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.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.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.
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.
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.
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.
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:
or
void print(void);
or
void print();
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
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.
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.
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.
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.
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:
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.
function_name: This is the identi ier of the function you want to call.
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.
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.
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int num1, num2, total;
return 0;
}
Output:
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.
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.
Syntax:
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:
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.
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.
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;
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;
}
Inside this function, there are three return statements within different if and else if blocks.
Only one of these return statements will be executed on each call to the function,
depending on the relationship between a and b.
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.
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>
int main() {
int num = 2;
printf("\n The value of num before calling the function = %d", 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:
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.
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.
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>
int main() {
int num = 2;
printf("\n The value of num before calling the function = %d", num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
*n += 10;
printf("\n The value of num in the called function = %d", *n);
Output:
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.
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>
int main() {
int a = 2, b = 4;
printf("\n In main() 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.
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.
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:
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.
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:
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 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:
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.
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.
1. auto:
Syntax: auto data_type variable_name; (The keyword auto is often omitted, as it's the
default for local variables).
Lifetime: Exists only while the block or function is executing. Created when the block is
entered and destroyed when the block exits.
2. extern:
Purpose: Used to declare a variable that is de ined in another source ile, allowing
multiple iles to share the same global variable.
3. register:
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:
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.
Purpose:
Global: To limit the variable's scope to the current source ile, preventing access from
other iles.
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.
Default
Garbage Zero Garbage Zero
value
#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:
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.
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.
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.
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.
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
n! = 1 (if n = 0 or n = 1)
Therefore
5! = 5 * 4 * 3!
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.
#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));
}
From the example, let's analyze the basic steps of a recursive program for calculating the
factorial of a number:
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.
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.
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:
Recursive Implementation:
#include <stdio.h>
int main() {
int num1, num2, result;
return 0;
}
Working Example:
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.
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>
return 0;
}
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.
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.
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;
return 0;
}
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):
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.
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.
int Fact(int n) {
if(n==1)
return 1;
else
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.
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.
The key difference is whether there are pending operations after the recursive call.
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.
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.
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.
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.
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];
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.
C does not allow declaring an array whose size is not known at compile time.
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.
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.
Note that C does not allow declaring an array whose number of elements is not known at
compile time.
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.
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.
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:
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.
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 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.
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.
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:
Example:
Example:
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.
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:
Linear search works on both sorted and unsorted arrays, and involves comparing each
element of the array sequentially with the target value.
Binary Search is more ef icient and works only on sorted arrays by repeatedly dividing
the search interval in half.
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++)
{
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
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.