0% found this document useful (0 votes)
22 views63 pages

Unit 3

The document provides a comprehensive overview of arrays in C programming, including single-dimensional and multi-dimensional arrays. It explains how to create, access, modify, and loop through arrays, as well as how to calculate the memory address of elements in 1D, 2D, and 3D arrays using both row-major and column-major order. Examples are included to illustrate the concepts and formulas for address calculation.

Uploaded by

kavinasingh2307
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views63 pages

Unit 3

The document provides a comprehensive overview of arrays in C programming, including single-dimensional and multi-dimensional arrays. It explains how to create, access, modify, and loop through arrays, as well as how to calculate the memory address of elements in 1D, 2D, and 3D arrays using both row-major and column-major order. Examples are included to illustrate the concepts and formulas for address calculation.

Uploaded by

kavinasingh2307
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To create an array, define the data type (like int) and specify the name of the array followed by square
brackets [].
To insert values to it, use a comma-separated list, inside curly braces:
int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array


To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

// Outputs 25

Change an Array Element


To change the value of a specific element, refer to the index number:
Example
myNumbers[0] = 33;

Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf("%d", myNumbers[0]);

// Now outputs 33 instead of 25


Loop Through an Array
You can loop through the array elements with the for loop.
The following example outputs all elements in the myNumbers array:
Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}

Set Array Size


Another common way to create arrays, is to specify the size of the array, and add elements later:
Example
// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

Using this method, you should know the size of the array, in order for the program to store enough
memory.
You are not able to change the size of the array after creation.
C Multidimensional Arrays
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single dimension arrays. These
are great, and something you will use a lot while programming in C. However, if you want to store data as
a tabular form, like a table with rows and columns, you need to get familiar with multidimensional
arrays.
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. In this chapter, we will introduce the most common; two-
dimensional arrays (2D).

Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers, take a look at the following example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

The first dimension represents the number of rows [2], while the second dimension represents the number
of columns [3]. The values are placed in row-order, and can be visualized like this:

Access the Elements of a 2D Array


To access an element of a two-dimensional array, you must specify the index number of both the row and
column.
This statement accesses the value of the element in the first row (0) and third column (2) of
the matrix array.
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2


Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change Elements in a 2D Array


To change the value of an element, refer to the index number of the element in each of the dimensions:
The following example will change the value of the element in the first row (0) and first column (0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1

Loop Through a 2D Array


To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.
The following example outputs all elements in the matrix array:
Example 1:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d", matrix[i][j]);
}
printf(“\n”);
}
o/p :
142
368

Example 2:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\n", matrix[i][j]);
}
}
o/p:
1
4
2
3
6
8

Example 3:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d", matrix[i][j]);
}
}

o/p:
142368
Calculation of address of element of 1-D, 2-D, and 3-D using row-
major and column-major order

This article focuses on calculating the address of any element in a 1-Dimensional, 2-Dimensional, and 3-
Dimensional array in Row major order and Column major order.
Calculating the address of any element In the 1-D array:
A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its elements
involves a single subscript that can either represent a row or column index.
Example:

1-D array
To find the address of an element in an array the following formula is used-
Address of A[I] = B + W * (I – LB)
I = Subset of element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the size of each
element is 2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Formula used:
Address of A[I] = B + W * (I – LB)
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Calculate the address of any element in the 2-D array:
The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays are organized as
matrices which can be represented as the collection of rows and columns as array[M][N] where M is the
number of rows and N is the number of columns.
Example:
0 seconds of 15 secondsVolume 0%

2-D array
To find the address of any element in a 2-Dimensional array there are the following two ways-
1. Row Major Order
2. Column Major Order
1. Row Major Order:
Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise
fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element
is 1 Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
2. Column Major Order:
If elements of an array are stored in a column-major fashion means moving across the column and then to
the next column then it’s in column-major order. To find the address of the element using column-major
order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.
Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of each
element is 1 Byte in memory find the address of arr[8][6] with the help of column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
From the above examples, it can be observed that for the same position two different address locations are
obtained that’s because in row-major order movement is done across the rows and then down to the next
row, and in column-major order, first move down to the first column and then next column. So both the
answers are right.
So it’s all based on the position of the element whose address is to be found for some cases the same
answers is also obtained with row-major order and column-major order and for some cases, different
answers are obtained.
Calculate the address of any element in the 3-D Array:
A 3-Dimensional array is a collection of 2-Dimensional arrays. It is specified by using three subscripts:
1. Block size
2. Row size
3. Column size
More dimensions in an array mean more data can be stored in that array.
Example:
3-D array
To find the address of any element in 3-Dimensional arrays there are the following two ways-
 Row Major Order
 Column Major Order
1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W *(M * N * (i-x) + N *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution:
Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6

Certainly, let me clarify the calculation of M and N:

M and N represent the number of rows and columns in the 3D array, respectively. In the context of
address calculations for multi-dimensional arrays, these values are determined by the upper and lower
bounds of the array's dimensions.

Here's the calculation for M and N:

1. **For M (rows):** M is calculated as the upper bound minus the lower bound of rows plus one.

M = Upper Bound of Rows - Lower Bound of Rows + 1

In your example, you provided:


- Lower Limit of rows (y) = -4
- Upper Bound of Rows = 1

So, using the formula: M = 1 - (-4) + 1 = 1 + 4 + 1 = 6

This means there are 6 rows in the 3D array.

2. **For N (columns):** N is calculated similarly, but for the columns. It is the upper bound of columns
minus the lower bound of columns plus one.

N = Upper Bound of Columns - Lower Bound of Columns + 1

In your example, you provided:


- Lower Limit of columns (z) = 5
- Upper Bound of Columns = 10

Using the formula: N = 10 - 5 + 1 = 5 + 1 = 6

This means there are 6 columns in the 3D array.

So, in the context of your array `arr[1:9, -4:1, 5:10]`, M is 6, and N is also 6. These values represent the
number of rows and columns in the array, which are crucial for address calculations in a 3D array.
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730
2. Column Major Order:
To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of block (first subscipt)
y = Lower Bound of Row
z = Lower Bound of Column
Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 5 +5 + 1 = 11
N (column)= Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (j-y) + (k – z))
Solution:
Address of arr[3][3][3] = 400 + 4 * ((11*16*(3-1)+11*(3-(-5)+(3-(-10)))
= 400 + 4 * ((176*2 + 11*8 + 13)
= 400 + 4 * (453)
= 400 + 1812
= 2212

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change!
Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on
schedule.

C Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.

Predefined Functions
So it turns out you already know what a function is. You have been using it the whole time while studying
this tutorial!
For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:
Example
int main() {
printf("Hello World!");
return 0;
}
Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by
parentheses () and curly brackets {}:
Syntax
void myFunction() {
// code to be executed
}

Example Explained
 myFunction() is the name of the function
 void means that the function does not have a return value. You will learn more about return values
later in the next chapter
 Inside the function (the body), add code that defines what the function should do

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed
when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


A function can be called multiple times:
Example
void myFunction() {
printf("I just got executed!");
}

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

// I just got executed!


// I just got executed!
// I just got executed!

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters
as you want, just separate them with a comma:

Syntax
returnType functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
The following function that takes a string of characters with name as parameter. When the function is
called, we pass along a name, which is used inside the function to print "Hello" and the name of each
person.

Example
void myFunction(char name[])
{
printf("Hello %s\n", name);
}

int main()
{
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja
When a parameter is passed to the function, it is called an argument. So, from the example above: name is
a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(char name[], int age)
{
printf("Hello %s. You are %d years old.\n", name, age);
}

int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.
Note that when you are working with multiple parameters, the function call must have the same number
of arguments as there are parameters, and the arguments must be passed in the same order.

Pass Arrays as Function Parameters


You can also pass arrays to a function:

Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}

int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops through the
array elements with the for loop.

When the function is called inside main(), we pass along the myNumbers array, which outputs the array
elements.
Note that when you call the function, you only need to use the name of the array when passing it as an
argument myFunction(myNumbers). However, the full declaration of the array is needed in the function
parameter (int myNumbers[5]).

Return Values
The void keyword, used in the previous examples, indicates that the function should not return a value. If
you want the function to return a value, you can use a data type (such as int or float, etc.) instead of void,
and use the return keyword inside the function:

Example
int myFunction(int x) {
return 5 + x;
}

int main() {
printf("Result is: %d", myFunction(3));
return 0;
}

// Outputs 8 (5 + 3)
This example returns the sum of a function with two parameters:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
You can also store the result in a variable:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)

Function Declaration and Definition


you can create and call a function in the following way:
Example
// Create a function
void myFunction()
{
printf("I just got executed!");
}

int main()
{
myFunction(); // call the function
return 0;
}
A function consist of two parts:

Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
For code optimization, it is recommended to separate the declaration and the definition of the function.
You will often see C programs that have function declaration above main(), and function definition below
main(). This will make the code better organized and easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main()
{
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction()
{
printf("I just got executed!");
}
Another Example
If we use the example from the previous regarding function parameters and return values:

Example
int myFunction(int x, int y)
{
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
It is considered good practice to write it like this instead:

Example
// Function declaration
int myFunction(int, int);

// The main method


int main()
{
int result = myFunction(5, 3); // call the function
printf("Result is = %d", result);
return 0;
}
// Function definition
int myFunction(int x, int y)
{
return x + y;
}

Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment
with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the
following example, recursion is used to add a range of numbers together by breaking it down into the
simple task of adding two numbers:

Example
int sum(int k);

int main()
{
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k)
{
if (k > 0) {
return k + sum(k - 1);
}
else
{
return 0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and
returns the result. When k becomes 0, the function just returns 0. When running, the program follows
these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. However, when
written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on
numbers.
To use them, you must include the math.h header file in your program:
#include <math.h>

Square Root
To find the square root of a number, use the sqrt() function:
Example
printf("%f", sqrt(16));

Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a
number downwards to its nearest integer, and returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));

Power
The pow() function returns the value of x to the power of y (xy):
Example
printf("%f", pow(4, 3));

Other Math Functions


A list of other popular math functions (from the <math.h> library) can be found in the table below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

cos(x) Returns the cosine of x

exp(x) Returns the value of Ex

sin(x) Returns the sine of x (x is in radians)

tan(x) Returns the tangent of an angle


Passing array as function argument
If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similarly, you can pass multi-dimensional arrays as formal parameters.

Way-1
Formal parameters as a pointer −

void myFunction(int *param) {


.
.
.
}
Way-2
Formal parameters as a sized array −

void myFunction(int param[10]) {


.
.
.
}
Way-3
Formal parameters as an unsized array −

void myFunction(int param[]) {


.
.
.
}
Example
Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed
through the array as follows −

double getAverage(int arr[], int size) {

int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = sum / size;

return avg;
}
Now, let us call the above function as follows −

#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);
int main () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf( "Average value is: %f ", avg );

return 0;
}
When the above code is compiled together and executed, it produces the following result −

Average value is: 214.400000


As you can see, the length of the array doesn't matter as far as the function is concerned
because C performs no bounds checking for formal parameters.
passing pointer as function argument
Arguments Passing with pointers
A pointer to a function is passed in this example. As an argument, a pointer is passed instead of
a variable and its address is passed instead of its value. As a result, any change made by the
function using the pointer is permanently stored at the address of the passed variable. In C, this
is referred to as call by reference.

Below is the C program to pass arguments to function with pointers:

// C program to swap two values


// without passing pointer to
// swap function.
#include <stdio.h>

void swap(int* a, int* b)


{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}
Output
Values before swap function are: 10, 20
Values after swap function are: 20, 10

passing structure as function argument:


A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the
functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY VALUE:
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can
be accessed from called function. This concept is very useful while writing very big programs in
C.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student *record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(&record);
return 0;
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL IN C:
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a
program. In this scenario, we don’t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Pointers in C:
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable with
the reference operator &:

Example
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)
A pointer is a variable that stores the memory address of another variable as its value.

A pointer variable points to a data type (like int) of the same type, and is created with the *
operator.

The address of the variable you are working with is assigned to the pointer:

Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)


printf("%p\n", ptr);
Example explained
Create a pointer variable with the name ptr, that points to an int variable (myAge). Note that
the type of the pointer has to match the type of the variable you're working with (int in our
example).

Use the & operator to store the memory address of the myAge variable, and assign it to the
pointer.

Now, ptr holds the value of myAge's memory address.

Dereference
In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).

You can also get the value of the variable the pointer points to, by using the * operator (the
dereference operator):

Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)


printf("%d\n", *ptr);
Note that the * sign can be confusing here, as it does two different things in our code:

When used in declaration (int* ptr), it creates a pointer variable.


When not used in declaration, it act as a dereference operator.

There are two ways to declare pointer variables in C:


int* myNum;
int *myNum;

Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages, like
Python and Java.
They are important in C, because they allow us to manipulate the data in the computer's
memory. This can reduce the code and improve the performance. If you are familiar with data
structures like lists, trees and graphs, you should know that pointers are especially useful for
implementing those. And sometimes you even have to use pointers, for example when working
with files.
But be careful; pointers must be handled with care, since it is possible to damage data stored in
other memory addresses.
Pointers & Arrays
You can also use pointers to access arrays.
Consider the following array of integers:

Example
int myNumbers[4] = {25, 50, 75, 100};
You learned from the arrays chapter that you can loop through the array elements with a for
loop:

Example
int myNumbers[4] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}
Result:
25
50
75
100
Instead of printing the value of each array element, let's print the memory address of each array
element:

Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%p\n", &myNumbers[i]);
}
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc

Note that the last number of each of the elements' memory address is different, with an
addition of 4.

It is because the size of an int type is typically 4 bytes, remember:

Example
// Create an int variable
int myInt;

// Get the memory size of an int


printf("%lu", sizeof(myInt));
Result:

4
So from the "memory address example" above, you can see that the compiler reserves 4 bytes
of memory for each array element, which means that the entire array takes up 16 bytes (4 * 4)
of memory storage:

Example
int myNumbers[4] = {25, 50, 75, 100};

// Get the size of the myNumbers array


printf("%lu", sizeof(myNumbers));
Result:

16
How Are Pointers Related to Arrays
Ok, so what's the relationship between pointers and arrays? Well, in C, the name of an array, is
actually a pointer to the first element of the array.

Confused? Let's try to understand this better, and use our "memory address example" above
again.

The memory address of the first element is the same as the name of the array:

Example
int myNumbers[4] = {25, 50, 75, 100};

// Get the memory address of the myNumbers array


printf("%p\n", myNumbers);

// Get the memory address of the first array element


printf("%p\n", &myNumbers[0]);
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
This basically means that we can work with arrays through pointers!
How? Since myNumbers is a pointer to the first element in myNumbers, you can use the *
operator to access it:

Example
int myNumbers[4] = {25, 50, 75, 100};

// Get the value of the first element in myNumbers


printf("%d", *myNumbers);
Result:
25
To access the rest of the elements in myNumbers, you can increment the pointer/array (+1, +2,
etc):

Example
int myNumbers[4] = {25, 50, 75, 100};

// Get the value of the second element in myNumbers


printf("%d\n", *(myNumbers + 1));

// Get the value of the third element in myNumbers


printf("%d", *(myNumbers + 2));

// and so on..
Result:
50
75
Or loop through it:

Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", *(ptr + i));
}
Result:
25
50
75
100
It is also possible to change the value of array elements with pointers:

Example
int myNumbers[4] = {25, 50, 75, 100};

// Change the value of the first element to 13


*myNumbers = 13;

// Change the value of the second element to 17


*(myNumbers +1) = 17;

// Get the value of the first element


printf("%d\n", *myNumbers);

// Get the value of the second element


printf("%d\n", *(myNumbers + 1));
Result:
13
17

This way of working with arrays might seem a bit excessive. Especially with simple arrays like in
the examples above. However, for large arrays, it can be much more efficient to access and
manipulate arrays with pointers.
It is also considered faster and easier to access two-dimensional arrays with pointers.
And since strings are actually arrays, you can also use pointers to access strings.
For now, it's great that you know how this works. But like we specified in the previous chapter;
pointers must be handled with care, since it is possible to overwrite other data stored in
memory.

Pointer Operations& pointers arithmetic:


Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers.
The pointer variables store the memory address of another variable. It doesn’t store any value.

Hence, there are only a few operations that are allowed to perform on Pointers in C language.
The C pointer arithmetic operations are slightly different from the ones that we generally use
for mathematical calculations. These operations are:

Increment/Decrement of a Pointer
Addition of integer to a pointer
Subtraction of integer to a pointer
Subtracting two pointers of the same type
Comparison of pointers
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it
actually increments by the number equal to the size of the data type for which it is a pointer.

For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of
an int), and the new address will point to 1004. While if a float type pointer is incremented then
it will increment by 4(size of a float) and the new address will be 1004.

Decrement: It is a condition that also comes under subtraction. When a pointer is decremented,
it actually decrements by the number equal to the size of the data type for which it is a pointer.

For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size
of an int), and the new address will point to 996. While if a float type pointer is decremented
then it will decrement by 4(size of a float) and the new address will be 996.
pointer increment and decrement
Note: It is assumed here that the architecture is 64-bit and all the data types are sized
accordingly. For example, integer is of 4 bytes.

Example of Pointer Increment and Decrement


Below is the program to illustrate pointer increment/decrement:

#include <stdio.h>
// pointer increment and decrement
//pointers are incremented and decremented by the size of the data type they point to
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value

float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value
char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value

return 0;
}
Output
p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791
Note: Pointers can be outputted using %p, since, most of the computers store the address value
in hexadecimal form using %p gives the value in that form. But for simplicity and understanding
we can also use %u to get the value in Unsigned int form.

2. Addition of Integer to Pointer


When a pointer is added with an integer value, the value is first multiplied by the size of the
data type and then added to the pointer.
For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address
stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

pointer addition

Example of Addition of Integer to Pointer

// C program to illustrate pointer Addition


#include <stdio.h>

// Driver Code
int main()
{
// Integer variable
int N = 4;

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;

printf("Pointer ptr2 before Addition: ");


printf("%p \n", ptr2);

// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);

return 0;
}
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
3. Subtraction of Integer to Pointer
When a pointer is subtracted with an integer value, the value is first multiplied by the size of the
data type and then subtracted from the pointer similar to addition.

For Example:
Consider the same example as above where the ptr is an integer pointer that stores 1000 as an
address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final
address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

pointer substraction

Example of Subtraction of Integer from Pointer


Below is the program to illustrate pointer Subtraction:

// C program to illustrate pointer Subtraction


#include <stdio.h>

// Driver Code
int main()
{
// Integer variable
int N = 4;

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;

printf("Pointer ptr2 before Subtraction: ");


printf("%p \n", ptr2);

// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p \n", ptr2);

return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
4. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The result
is generated by calculating the difference between the addresses of the two pointers and
calculating how many bits of data it is according to the pointer data type. The subtraction of two
pointers gives the increments between the two pointers.
For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The
difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the increment
between ptr1 and ptr2 is given by (4/4) = 1.

Example of Subtraction of Two Pointer


Below is the implementation to illustrate the Subtraction of Two Pointers:

// C program to illustrate Subtraction


// of two pointers
#include <stdio.h>

// Driver Code
int main()
{
int x = 6; // Integer variable declaration
int N = 4;

// Pointer declaration
int *ptr1, *ptr2;

ptr1 = &N; // stores address of N


ptr2 = &x; // stores address of x

printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);


// %p gives an hexa-decimal value,
// We convert it into an unsigned int value by using %u
// Subtraction of ptr2 and ptr1
x = ptr1 - ptr2;

// Print x to get the Increment


// between ptr1 and ptr2
printf("Subtraction of ptr1 "
"& ptr2 is %d\n",
x);

return 0;
}
Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. Comparison of Pointers
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and
returns false for the unsatisfied condition.

Step 1: Initialize the integer values and point these integer values to the pointer.
Step 2: Now, check the condition by using comparison or relational operators on pointer
variables.
Step 3: Display the output.
Example of Pointer Comparision

// C Program to illustrare pointer comparision


#include <stdio.h>
int main()
{
// declaring array
int arr[5];

// declaring pointer to array name


int* ptr1 = &arr;
// declaring pointer to first element
int* ptr2 = &arr[0];

if (ptr1 == ptr2) {
printf("Pointer to Array Name and First Element "
"are Equal.");
}
else {
printf("Pointer to Array Name and First Element "
"are not Equal.");
}

return 0;
}
Output
Pointer to Array Name and First Element are Equal.
Comparison to NULL
A pointer can be compared or assigned a NULL value irrespective of what is the pointer type.
Such pointers are called NULL pointers and are used in various pointer-related error-handling
methods.
// C Program to demonstrate the pointer comparison with NULL
// value
#include <stdio.h>

int main()
{

int* ptr = NULL;

if (ptr == NULL) {
printf("The pointer is NULL");
}
else {
printf("The pointer is not NULL");
}
return 0;
}
Output
The pointer is NULL
Comparison operators on Pointers using an array
In the below approach, it results in the count of odd numbers and even numbers in an array. We
are going to implement this by using a pointer.

Step 1: First, declare the length of an array and array elements.


Step 2: Declare the pointer variable and point it to the first element of an array.
Step 3: Initialize the count_even and count_odd. Iterate the for loop and check the conditions
for the number of odd elements and even elements in an array
Step 4: Increment the pointer location ptr++ to the next element in an array for further
iteration.
Step 5: Print the result.
Example of Pointer Comparison in Array

// Pointer Comparision in Array


#include <stdio.h>

int main()
{
int n = 10; // length of an array

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int* ptr; // Declaration of pointer variable

ptr = arr; // Pointer points the first (0th index)


// element in an array
int count_even = 0;
int count_odd = 0;

for (int i = 0; i < n; i++) {

if (*ptr % 2 == 0) {
count_even++;
}
if (*ptr % 2 != 0) {
count_odd++;
}
ptr++; // Pointing to the next element in an array
}
printf("No of even elements in an array is : %d",
count_even);
printf("\nNo of odd elements in an array is : %d",
count_odd);
}
Output
No of even elements in an array is : 5
No of odd elements in an array is : 5
Pointer Arithmetic on Arrays
Pointers contain addresses. Adding two addresses makes no sense because there is no idea
what it would point to. Subtracting two addresses lets you compute the offset between the two
addresses. An array name acts like a pointer constant. The value of this pointer constant is the
address of the first element.

For Example: if an array is named arr then arr and &arr[0] can be used to reference the array as
a pointer.

Below is the program to illustrate the Pointer Arithmetic on arrays:

Program 1:

// C program to illustrate the array


// traversal using pointers
#include <stdio.h>

// Driver Code
int main()
{

int N = 5;

// An array
int arr[] = { 1, 2, 3, 4, 5 };

// Declare pointer variable


int* ptr;

// Point the pointer to first


// element in array arr[]
ptr = arr;

// Traverse array using ptr


for (int i = 0; i < N; i++) {

// Print element at which


// ptr points
printf("%d ", ptr[0]);
ptr++;
}
}
Output
12345
Program 2:

// C program to illustrate the array


// traversal using pointers in 2D array
#include <stdio.h>

// Function to traverse 2D array


// using pointers
void traverseArr(int* arr, int N, int M)
{

int i, j;

// Traverse rows of 2D matrix


for (i = 0; i < N; i++) {

// Traverse columns of 2D matrix


for (j = 0; j < M; j++) {

// Print the element


printf("%d ", *((arr + i * M) + j));
}
printf("\n");
}
}

// Driver Code
int main()
{

int N = 3, M = 2;

// A 2D array
int arr[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

// Function Call
traverseArr((int*)arr, N, M);
return 0;
}
Output
12
34
56

Comparison between call by value and call by reference.


Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are
generally differentiated by the type of values passed to them as parameters.
The parameters passed to the function are called actual parameters whereas the parameters
received by the function are called formal parameters.

Call By Value
In call by value method of parameter passing, the values of actual parameters are copied to the
function’s formal parameters.

There are two copies of parameters stored in different memory locations.


One is the original copy and the other is the function copy.
Any changes made inside functions are not reflected in the actual parameters of the caller.
Example of Call by Value
The following example demonstrates the call-by-value method of parameter passing

// C program to illustrate call by value


#include <stdio.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b); // Actual Parameters
printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y) // Formal Parameters
{
int t;

t = x;
x = y;
y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);


}
Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20
Thus actual values of a and b remain unchanged even after exchanging the values of x and y in
the function.

Call by Reference
In call by reference method of parameter passing, the address of the actual parameters is
passed to the function as the formal parameters.

Both the actual and formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the actual parameters of the
caller.
Example of Call by Reference
The following C program is an example of a call-by-reference method.

// C program to illustrate Call by Reference


#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;
}
// Function to swap two variables
// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}
Output
Inside the Function:
x = 20 y = 10
Inside the Caller:
a = 20 b = 10
Thus actual values of a and b get changed after exchanging values of x and y.
Difference between the Call by Value and Call by Reference
The following table lists the differences between the call-by-value and call-by-reference
methods of parameter passing.

Call By Value Call By Reference

While calling a function, instead of passing the


While calling a function, we pass the
values of variables, we pass the address of
values of variables to it. Such functions
variables(location of variables) to the function
are known as “Call By Values”.
known as “Call By References.
Call By Value Call By Reference

In this method, the value of each variable


In this method, the address of actual variables
in the calling function is copied into
in the calling function is copied into the dummy
corresponding dummy variables of the
variables of the called function.
called function.

With this method, the changes made to


With this method, using addresses we would
the dummy variables in the called
have access to the actual variables and hence
function have no effect on the values of
we would be able to manipulate them.
actual variables in the calling function.

In call-by-values, we cannot alter the


In call by reference, we can alter the values of
values of actual variables through
variables through function calls.
function calls.

Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.

This method is preferred when we have to


This method is preferred when we have to pass
pass some small values that should not
a large amount of data to the function.
change.

Note: In C, we use pointers to achieve call-by-reference. In C++, we can either use pointers
or references for pass-by-reference. In Java, primitive types are passed as values and non-
primitive types are always references.

82 84 13 78 30 3 65 22 39 47 9 42 36 68 53 74 16 73 60 8 38 79 23 61 27 2 57 58 75 37 21 70 76
43 49 19 71 41 55 18 77 14 34 32

You might also like