0% found this document useful (0 votes)
4 views

PPS Unit 2-Notes

The document provides an overview of arrays in C programming, detailing their definition, properties, advantages, and disadvantages. It explains one-dimensional arrays, including their syntax, initialization, and how to access and modify their elements, along with examples. Additionally, it covers the concept of linear search, describing the algorithm and providing an example of its implementation.

Uploaded by

aryankondekar15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PPS Unit 2-Notes

The document provides an overview of arrays in C programming, detailing their definition, properties, advantages, and disadvantages. It explains one-dimensional arrays, including their syntax, initialization, and how to access and modify their elements, along with examples. Additionally, it covers the concept of linear search, describing the algorithm and providing an example of its implementation.

Uploaded by

aryankondekar15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Sub : PPS Unit 2 Notes

Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

C array is beneficial when you have to store similar elements. For example, if we want
to store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.

Properties of Array
The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantage of an Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.
Sub : PPS Unit 2 Notes

Disadvantage of Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList
which we will learn later.

One dimensional array in C


Arrays are a fundamental concept in programming, and they come in different
dimensions. One-dimensional arrays, also known as single arrays, are arrays with
only one dimension or a single row. In this article, we'll dive deep into one-dimensional
arrays in C programming language, including their syntax, examples, and output.

Syntax of One-Dimensional Array in C


The syntax of a one-dimensional array in C programming language is as follows:

dataType arrayName[arraySize]; float marks[20]


o dataType specifies the data type of the array. It can be any valid data type in C
programming language, such as int, float, char, double, etc.
o arrayName is the name of the array, which is used to refer to the array in the program.
o arraySize specifies the number of elements in the array. It must be a positive integer
value.
Sub : PPS Unit 2 Notes

We can visualize a one-dimensional array in C as a single row to store the


elements. All the elements are stored at contiguous memory locations. Now, we
will see how to declare, initialize and access array elements.

Example of One-Dimensional Array in C


Let's take a simple example of a one-dimensional array in C programming language
to understand its syntax and usage.

#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
for( int i=0; i<5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}

Output:
Memory mapping in computer
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30 Number
numbers[3] = 40
numbers[4] = 50 0 1 2 3 4

10 20 30 40 50

125677 125681 125685 …….. …….125693


Explanation:

In the above example, we have


number[0] = 10
declared a one-dimensional array of
integers named numbers. The array number[1] = 20
contains five elements, and each number[4] = 50
element is initialized with a value.

We have used a for loop to iterate over the elements of the array and print their values
using the printf function.

Accessing Elements of One-Dimensional Array in C


Sub : PPS Unit 2 Notes

In a one-dimensional array, each element is identified by its index or position in the


array. The index of the first element in the array is 0, and the index of the last element
is arraySize - 1.

To access an element of a one-dimensional array in C programming language, we use


the following syntax:

arrayName[index]

o arrayName is the name of the array.


o index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C

Let's take an example to understand how to access elements of a one-dimensional


array in C programming language.

#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printf("The first element of the array is: %d\n", numbers[0]);
printf("The third element of the array is: %d\n", numbers[2]);

Output:

The first element of the array is: 10


The third element of the array is: 30
return 0;
}

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers. We have accessed the first element of the array using the index
0 and the third element of the array using the index 2.

Accessing Elements of One-Dimensional Arrays


We can access individual elements of a one-dimensional array using their index, which
is an integer value that represents the position of the element in the array. The index
of the first element in the array is 0, and the index of the last element is arraySize-1.

The syntax to access an element of a one-dimensional array in C is as follows:


Sub : PPS Unit 2 Notes

arrayName[index]

o arrayName is the name of the array.


o index is the index of the element we want to access.

Example of Accessing Elements of One-Dimensional Array in C

#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printf("The third element of the array is %d\n", numbers[2]);
return 0;
}

Output:

The third element of the array is 30

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers and initialized it with the values {10, 20, 30, 40, 50}. We have used
the printf function to print the third element of the array, which is accessed using
the index 2.

Modifying Elements of One-Dimensional Arrays


We can modify the value of individual elements of a one-dimensional array using their
index. To modify an element, we simply assign a new value to it using the assignment
operator =.

Example of Modifying Elements of One-Dimensional Array in C :

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50};
Sub : PPS Unit 2 Notes

printf("The third element of the array is %d\n", numbers[2]);


numbers[2] = 35;
printf("The third element of the array is now %d\n", numbers[2]);

return 0;

Output:

The third element of the array is 30


The third element of the array is now 35

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers and initialized it with the values {10, 20, 30, 40, 50}. We have used
the printf function to print the third element of the array, which is accessed using
the index 2.

After that, we modified the value of the third element by assigning a new value
of 35 to it. Finally, we have used the printf function again to print the new value of the
third element.

Declaration of one dimentional Array

Declaration of 1D Array consists of any data type and it can be declared by any
random name or any random variable. Syntax:

int arr[10];

// Here int is the data type of array.


// arr is the name of array.
// 10 is the size of array.

In C programming, a One-Dimensional Array is a variable that can store multiple


values of a single data type, such as int, float, double, char, structure, pointer,
etc., sequentially (means one after another) in computer memory and accessed via
a common name or identifier.

A One-Dimensional Array is also known as 1D Array.


Sub : PPS Unit 2 Notes

Suppose we want to store the age of 10 students. In that case, we have to declare
10 variables in our C program to store the age of 10 students.

Now here comes the use of a one-dimensional array. With the help of 1D Array,
we will declare a single variable in our C program that can store the age of 10
students at a time.

(OR)

Declaration Syntax of a One Dimensional Array in C


datatype variable_name [size];
Copy

Here, size is the number of elements we want to store in the array.


Example
int a[5];

Once we declare the 1D Array, it will look like as shown in the picture
below:

In above image we can see that the name of the one dimensional array
is a and it can store 5 integer numbers. Size of the array is 5. Index of the
array is 0, 1, 2, 3 and 4.

The first index is called Lower Bound, and the last index is called an Upper
Bound. Upper Bound of a one dimensional is always Size – 1.

Initializing One Dimensional Array


In C programming language, we can initialize a one-dimensional array while
declaring it or later in the program. We can initialize a one-dimensional array while
declaring it by using the following syntax:

dataType arrayName[arraySize] = {element1, element2, ..., elementN};


Sub : PPS Unit 2 Notes

- "dataType' specifies the data type of the array.

- "arrayName' is the name of the array.

- "arraySize' specifies the number of elements in the array.

- "{element1, element2, ..., elementN}' specifies the values of the elements in the
array. The number of elements must be equal to "arraySize'.

The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.

1. marks[0]=80; //initialization of array


2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

Example of Initializing One Dimensional Array in C

Let's take an example to understand how to initialize a one-dimensional array in C


programming language.

#include <stdio.h>
int main()
{
int numbers[5] = {10, 20, 30, 40, 50};
for(int i=0; i<5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Sub : PPS Unit 2 Notes

Output of the code:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Explanation:

In the above example, we have declared a one-dimensional array of integers


named numbers and initialized it with the values {10, 20, 30, 40, 50}. We have used
a for loop to iterate over the elements of the array and print their values using
the printf function.

We can also initialize a one-dimensional array later in the program by assigning


values to its elements using the following syntax:

arrayName[index] = value;

- arrayName is the name of the array.

- index is the index of the element we want to assign a value to.

- value is the value we want to assign to the element.

Example of Initializing One Dimensional Array in C

Let's take an example to understand how to initialize a one-dimensional array later in


the program in C programming language.

#include <stdio.h>
int main() {
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
for(int i=0; i<5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
Sub : PPS Unit 2 Notes

return 0;
}

Output of the code:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Explanation:

In the above example, we have declared a one-dimensional array of


integers named numbers. We have initialized the elements of the array later in the
program by assigning values to them. We have used a for loop to iterate over the
elements of the array and print their values using the printf function.

Linear Search
A Linear Search, which is also popularly known as a sequential search, is a
process for finding an item in a list of items. This sort of searching algorithm
checks each element of the list one by one until a match is found or the entire
list is searched.

In worst-case scenarios, the Linear Search takes linear time and performs at
most n comparisons, where n is the list's length.

The following are the steps involved in implementing Linear Search:

1. We must first use a for loop to traverse the array elements.

2. In the process of searching an element in a list of elements, we should start by


comparing the search element with the current list of elements in each iteration of
the loop, and if the elements match, return the index of the relevant array element.

3. If the element we're looking for doesn't match, move on to the next one.

Return -1, if there is no match or the search element is not found in the given array.

Linear search in C is a searching method/algorithm. In the linear search algorithm,


we traverse through the data structure from any one point and traverse until the data
item is found in the data structure.
Sub : PPS Unit 2 Notes

These data structures could be array, string, Linked-List, Stack, Queue, or any other
data structure.

Linear Search Example:


Find the number 34 in the given data structure Array.

Array:
24 56 -1 90 4 12 34 89 37

0 1 2 3 4 5 6 7 8
Solution:
Index Number Working

0 24 24 != 34 * We will continue our search

1 56 56 != 34 *We will continue our search

2 -1 -1 != 34 => We will continue our search

3 90 90 != 34 => We will continue our search

4 4 4 != 34 => We will continue our search

5 12 12 != 34 => We will continue our search

6 34 34 == 34 => As a result, we have ended our search

7 89

8 37
Because 6 is the index of our element (34), our answer is 6 for 0-based indexing arrays
and 7 for 1-based indexing arrays. This is how linear search works in an array.

Linear Search Algorithm

Searching is the method of finding a certain item in a list of items. If the element is
found in the list, the process is considered successful, and the location of that
element is returned; otherwise, the search is considered unsuccessful.

Linear_Search ( Array X, Value i)

1. Set j to 1
2. If j > n, jump to step 7
Sub : PPS Unit 2 Notes

3. If X[j] == i, jump to step 6


4. Then, increment j by 1 i.e. j = j+1
5. Go back to step 2
6. Display the element i which is found at particular index i, then jump to
step 8
7. Display element not found in the set of input elements.
8. Exit/End

C Program to Search an Array Element using LINEAR SEARCH

#include <stdio.h>

int main()

int array[100], search, c, number;

printf("Enter the number of elements in array\n");

scanf("%d",&number); // 10

printf("Enter %d numbers\n", number);

for ( c = 0 ; c < number ; c++ ) //number10

scanf("%d",&array[c]); array[10]

printf("Enter the number to search\n");

scanf("%d",&search);

for ( c = 0 ; c < number ; c++ )

if ( array[c] == search ) /*5 if required element found */

printf("%d is present at location %d.\n", search, c+1);

break;

}
Sub : PPS Unit 2 Notes

if ( c == number )

printf("%d is not present in array.\n", search);

return 0;

OUTPUT:

Enter the number of elements in array


5
Enter 5 numbers
12
23
22
10
45
Enter the number to search
22
22 is present at location 3.

Two Dimensional Array in C (2D Array)


The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database lookalike data
structure. It provides ease of holding the bulk of data at once which can be passed to
any number of functions wherever required.

A 2D array is like a matrix and has a row and a column of elements ( Although in
memory these are stored in contiguous memory locations).

A 1-D array, is a linear list of data and needed only one index to access the element
like a[2]. To access a two-dimensional array we need a pair of indices one for the
row and another for the column like a[1][2].

Similar to a one-dimensional array, we have the same name for all the elements
present in the matrix.

The difference that we have here is that a two-dimensional array is not linear in
nature.

The following figure illustrates the difference between a one-dimensional array and a two-
dimensional array:
Sub : PPS Unit 2 Notes

Fig : 1D array vs 2D array in C

In the above figure, we can clearly see that the 2D array has two dimensions just
like any two-dimensional figure such as a square or a rectangle.

Also, the number of rows and the number of columns in the 2D array are
represented by this format:

2D array format

ArrayVariableName[number of rows] [number of columns]


For the above 2D array we have the number of rows=3 and number of columns=3,
so we represent it as a 3×3 array or a 3×3 matrix.

A matrix can also have specifications like 3×4, 2×1, etc. Let us learn more about
the 2D arrays.

Declaration of two dimensional Array in C

A 2D array needs to be declared so that the compiler gets to know what type of data
is being stored in the array.

Similar to 1D array, a 2D array can also be declared as an int, char, float, double,
etc. Here is how we declare a 2D array(here integer array):

2D array declaration

datatype arrayVariableName[number of rows] [number of columns]


Sub : PPS Unit 2 Notes

int num[10][5];

The ‘int’ specifies that the data stored in the array will be of integer type.
‘num’ is the variable name under which all the data is stored.
[10] refers to the number of rows of the array and
[5] refers to the number of columns of the array.

This is also a static memory allocation, that is, we are allocating the array a size
equal to 10 x 5, that is, in this array, we can store 10 x 5 = 50 number of elements.

The actual size it will occupy in memory will depend on the data type of the
array i.e. (size of array = number of elements it can hold x Size of datatype).

The two brackets i.e. [][] specify that the array is two-dimensional.

Initialization of Two dimensional Arrays


2D array initialization can be done while declaring the array as well. In simple words,
we can store certain elements in the array while writing the program i.e. we know
which values this array will always store.

Here are a few examples of initializing a 2D array:

//or the format given below

int num[3][3]={{25,10,5},{4,6,13},{45,90,78}};
int num[3][3]={{25,10,5}, //row0
{4,6,13}, //row1
{45,90,78} //row2
};
//this format also stores data in the array but results in a loss of readability
int num[2][4]={4,6,8,10,3,5,7,9};
Another important fact is that when initializing a 2D array, specifying the number
of rows of the array is optional but specifying the number of columns of the
array is important and mandatory.

Example :

#include <stdio.h>

int main(void) {
Sub : PPS Unit 2 Notes

int arr[2][3] = {{31, 12, 11}, {81, 91, 110}};

int *p[2];

p[0] = arr[0];

p[1] = arr[1];

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

for (int j = 0; j < 3; j++) {

printf("%d ", p[i][j]);

printf("\n");

return 0;

Output
31 12 11

81 91 110

Binary Search
A binary search program in C is a commonly used search algorithm in computer
programming. It is an efficient algorithm that allows finding a target value within
a sorted array or list by repeatedly dividing the search interval in half. In a binary
search program in C, the algorithm starts by comparing the target value with the
middle element of the array. If the middle element is equal to the target value,
the search is complete. If not, the search interval is divided in half again, and
the search continues in the appropriate subarray until the target value is found
Sub : PPS Unit 2 Notes

or the subarray is empty. The binary search algorithm has a time complexity of
O(log n), making it much faster than linear search for large arrays or lists.

Binary Search Algorithm


1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is the
index of the first array element, 'upper_bound' is the index of the last array element, 'val' is t
he value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit

Working of Binary search


Now, let's see the working of the Binary Search Algorithm.

To understand the working of the Binary search algorithm, let's take a sorted array. It
will be easy to understand the working of Binary search with an example.

There are two methods to implement the binary search algorithm -

o Iterative method
o Recursive method

The recursive method of binary search follows the divide and conquer approach.
Sub : PPS Unit 2 Notes

Let the elements of array are –

Let the element to search is, K = 56

We have to use the below formula to calculate the mid of the array -

1. mid = (beg + end)/2

So, in the given array -

beg = 0

end = 8

mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.


Sub : PPS Unit 2 Notes

Now, the element to search is found. So algorithm will return the index of the element
matched.

Example on Binary Search


#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);
printf("Enter %d integersn", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to findn");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("%d found at location %d.n", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list.n", key);
return 0;
}
Sub : PPS Unit 2 Notes

Linear Search Binary Search

In linear search, input data Whereas, in binary search, input data has to be
doesn’t need to be sorted . sorted according to the order.

It is also referred as
It is also referred to as half-interval search.
sequential search.

The time complexity of the The time complexity of the binary search is
linear search is O(n) 0 (logn)

Multi-dimensional array is A single dimensional array is used for linear


used for linear search. search.

It operates equality
Binary search operates ordering comparisons
comparisons

Linear search is less complex Binary search is more complex and has a fast
and involves a slow process process

// Program to take 5 values from the user and store them in an


array
Sub : PPS Unit 2 Notes

// Print the elements stored in the array

#include <stdio.h>

int main() {

int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);

printf("Displaying integers: ");

// printing elements of an array

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

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

return 0;

}
Enter 5 integers : 1
-3
34
0
3
Displaying integers : 1
Sub : PPS Unit 2 Notes

-3
34
0
3

array example

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }

Output

80
60
70
85
75

You might also like