0% found this document useful (0 votes)
0 views8 pages

Unit 3 (Array)

The document provides a comprehensive overview of arrays in C, including their declaration, initialization, and manipulation. It covers operations such as updating elements, calculating sums, searching (linear and binary search), inserting and removing elements, and finding the largest and smallest elements in an array. The document includes example code snippets to illustrate these concepts.

Uploaded by

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

Unit 3 (Array)

The document provides a comprehensive overview of arrays in C, including their declaration, initialization, and manipulation. It covers operations such as updating elements, calculating sums, searching (linear and binary search), inserting and removing elements, and finding the largest and smallest elements in an array. The document includes example code snippets to illustrate these concepts.

Uploaded by

shambushree
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Array:

An array in C is a collection of data items of similar types of data. One or more values same data type,
which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be
stored in an array.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
The size of the array, also called the length of the array, must be specified in the declaration itself. Once
declared, the size of a C array cannot be changed. When an array is declared, the compiler allocates a
continuous block of memory required to store the declared number of elements.

Array Declaration:
Array declaration is the process of specifying the type, name, and size of the array. In C, we have to
declare the array like any other variable before using it.
Arr[5];
It indicates variable name ‘arr’, memory allocation from index 0 to 4 and size of array is 5.

Array Initialization:
When the array is declared or allocated memory, the elements of the array contain some garbage value.
So, we need to initialize the array to some meaningful values.
int arr[5] ={1,2,3,4,5};
it means a[0]=1, a[1]=2, a[2]=3,a[3]=4,a[4]=5;
int arr[5] ={1,2,3};
it means a[0]=1, a[1]=2, a[2]=3, a[3]=0, a[4]=0;
int arr[5]={0};
it means a[0]=0, a[1]=0, a[2]=0, a[0]=4, a[4]=0;
#include <stdio.h>

int main() {

// array declaration and initialization


int arr[5] = {2, 4, 8, 12, 16};

// accessing element at index 2 i.e 3rd element


printf("%d ", arr[2]);

// accessing element at index 4 i.e last element


printf("%d ", arr[4]);

// accessing element at index 0 i.e first element


printf("%d ", arr[0]);
return 0;
}
Output:
Update Array Element
We can update the value of array elements at the given index i in a similar way to accessing an element
by using the array square brackets [] and assignment operator (=).
#include <stdio.h>

int main() {
int arr[5] = {2, 4, 8, 12, 16};

// Update the first value


// of the array
arr[0] = 1;
printf("%d", arr[0]);
return 0;
}

WAP to calculate (sum) the marks of 10 student using array.


#include<stdio.h>
int main()
{
int marks[10]={50,50,60,40,70,80,60,70,60,80};
int i,sum=0;
float avg;
for(i=0;i<10;i++)
{
sum=sum+marks[i];
}
avg=sum/10;
printf(“Average of Marks of Students=%f”,avg)
retrun 0;
}
Getting size of an Array:

In c the compiler allocated a continuous block of memory. The size of the allocated memory depends
on the data types of the array.
int main()
{
int arr[5]={1,2,3,4,5};
printf(“Size of an array=%d”,sizeof(arr));
return 0;
}
The size of operator returns the number of bytes occupied by the variable.
int main()
{
int arr[5]={1,2,3,4,5};
printf(“Size of an array=%d”,sizeof(arr));
return 0;
}

Getting length of an Array:

#include<stdio.h>
int main()
{
int size,length,i;
int num[5]={10,20,30,40,50};
// char num[]="I am Teacher";
for(i=0;i<5;i++)
{
printf("\na[%d]=%d",i,num[i]);
}
num[2]=65; //Replace Value
printf("\n after change");
for(i=0;i<5;i++)
{
printf("\na[%d]=%d",i,num[i]);
}
printf("\nSize of array=%d",sizeof(num));

length=sizeof(num)/sizeof(num[0]);

printf("\nLength=%d",length);
for(i=0;i<length;i++)
{
printf("\na[%d]=%d",i,num[i]);
}
getch();
clrscr();
return 0;
}

Output: Output:
a[0]=10 a[0]=I
a[1]=20 a[1]=
a[2]=30 a[2]=a
a[3]=40 a[3]=m
a[4]=50 a[4]=
after change after change
a[0]=10 a[0]=I
a[1]=20 a[1]=
a[2]=65 a[2]=A
a[3]=40 a[3]=m
a[4]=50 a[4]=
Size of array=20 Size of array=13
Length of array=5 Length of array=13
a[0]=10 a[0]=I
a[1]=20 a[1]=
a[2]=65 a[2]=A
a[3]=40 a[3]=m
a[4]=50 a[4]=
a[5]=T
a[6]=e
a[7]=a
a[8]=c
a[9]=h
a[10]=e
a[11]=r
a[12]=

Array Manipulation Searching


A typical operation in computer programming is looking for a particular element in an array. The
efficiency of your code may be greatly improved by using efficient searching algorithms whether you
are searching for the existence of a certain value locating the index of an element, or verifying if an
element exists. The many methods for searching for elements in an array using the C programming
language will be discussed in this article.

There are mainly two ways to Search an Element in an Array:

1. Linear Search
2. Binary Search.
1. Linear Search
A straightforward search strategy used to locate a given element in an array or list is called linear
search, sometimes referred to as sequential search. It operates by comparing each array member to the
target value to find a match or traverse the full array iteratively.
The fundamental steps in linear search are as follows:
1. Start with the array's topmost elements.
2. The target value should be compared to the current element.
3. The search is successful if the current element matches the requested value, and then the
algorithm can return the element's index or any other desired output.
4. Go to the following element in the array if the current element does not match the desired
value.
5. Until a match is made or the end of the array is reached, repeat steps 2-4.

Program: break;
}
#include<stdio.h> }
int main() if(count==0)
{ {
int arr[5]={10,20,30,40,50}; printf("Array element is not in
int val,i,count=0; the list");
printf("Enter the element value that you }
want to search:"); getch();
scanf("%d",val); clrscr();
for(i=0;i<5;i++) return 0;
{ }
if(val==arr[i]) Output:
{ Enter the element value that you want to
printf("Position of the search:40
Array Element=%d",++i); Position of the Array Element=4
count=1;

2. Binary Search
The binary search technique is utilized to quickly locate a specific element in a sorted array or list. It
uses a divide-and-conquer strategy, periodically cutting the search area in half until the target element
is located or found to be absent.

#include <stdio.h> int mid = low + (high - low) / 2;

int binarySearch(int arr[], int target, int low, int if (arr[mid] == target)
high) { return mid;

// Repeat until the pointers low and if (arr[mid] < target)


// high meet each other low = mid + 1;
while (low <= high) { else
high = mid - 1; int target = 7;
} int low = 0;
return -1; int high = n;
} int index = binarySearch(arr, target, low,
high);
int main() { printf("%d\n", index);
int arr[] = {2, 3, 4, 7, 9,10}; return 0;
int n = sizeof(arr) / sizeof(arr[0]); }

Insert element in array


Step by step descriptive logic to insert element in array.
1. Input size and elements in array. Store it in some variable say size and arr.
2. Input new element and position to insert in array. Store it in some variable say num and pos.

3. To insert new element in array, shift elements from the given insert position to one position right.
Hence, run a loop in descending order from size to pos to insert. The loop structure should look
like for(i=size; i>=pos; i--).
Inside the loop copy previous element to current element by arr[i] = arr[i - 1];.
Read more – C program to copy array element

4. Finally, after performing shift operation. Copy the new element at its specified position i.e. arr[pos
- 1] = num;.

Program: {
printf("%d\t",arr[i]);
#include<stdio.h> }
int main () printf("\nArray Element that you want
{ to store:");
int arr[]={10,20,30,40,50}; scanf("%d",&ele);
int n,pos,i,ele; printf("\n Enter the position of the
n=sizeof(arr)/sizeof(arr[0]); element:");
printf("Size =%d",n); scanf("%d",&pos);
printf("\nBefore Insert array Element\n"); for(i=n;i>=pos;i--)
for(i=0;i<5;i++) {
arr[i]=arr[i-1]; }
} getch();
arr[pos-1]=ele; clrscr();
n++; return 0;
printf("\nAfter Insertion Element"); }
for(i=0;i<n;i++)
{ Output:
printf("\n%d",arr[i]);

Remove an element from an array in C

To delete a specific element from an array, a user must define the position from which the array's
element should be removed. The deletion of the element does not affect the size of an array.
Furthermore, we should also check whether the deletion is possible or not in an array.
Steps to remove an element from an array
Following is the steps to remove a particular element from an array in C programming.
Step 1: Input the size of the array arr[] using num, and then declare the pos variable to define the
position, and i represent the counter value.
Step 2: Use a loop to insert the elements in an array until (i < num) is satisfied.
Step 3: Now, input the position of the particular element that the user or programmer wants to delete
from an array.
Step 4: Compare the position of an element (pos) from the total no. of elements (num+1). If the pos is
greater than the num+1, the deletion of the element is not possible and jump to step 7.
Step 5: Else removes the particular element and shift the rest elements' position to the left side in an
array.
Step 6: Display the resultant array after deletion or removal of the element from an array.
Step 7: Terminate or exit from the program.

Program: {
#include <stdio.h> scanf("%d", &Array[i]);
int main() }
{ printf("\n Please Enter a Valid Index
int Array[10], Position, i, Size; Position of a Element that you want to Delete :
");
printf("\n Please Enter Number of scanf("%d", &Position);
elements in an array : "); if(Position < 0 || Position >= Size)
scanf("%d", &Size); {
printf("\n Please Enter a Valid
printf("\n Please Enter %d elements of Index Position between 0 and %d", Size-1);
an Array \n", Size); }
for (i = 0; i < Size; i++) else
{ for (i = 0; i < Size; i++)
for (i = Position; i < Size; i++) {
{ printf("%d\t", Array[i]);
Array[i] = Array[i + 1]; }
} getch();
Size--; clrscr();
} return 0;
printf("\n Final Array after Deleting an
Array Element is:\n");
}
Finding the largest/smallest element in an array
Program:
#include <stdio.h>
int main() {
int n,i;
int arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%d", &arr[i]);
}
// storing the largest number to arr[0]
for (i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
printf("Largest element = %d", arr[0]);

// storing the smallest number to arr[0]


for (i = 1; i < n; ++i) {
if (arr[0] > arr[i]) {
arr[0] = arr[i];
}
}
printf("Smallest element = %d", arr[0]);

return 0;
}

You might also like