Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Practical C Programming

You're reading from   Practical C Programming Solutions for modern C developers to create efficient and well-structured programs

Arrow left icon
Product type Paperback
Published in Feb 2020
Publisher Packt
ISBN-13 9781838641108
Length 616 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
B. M. Harwani B. M. Harwani
Author Profile Icon B. M. Harwani
B. M. Harwani
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Working with Arrays 2. Managing Strings FREE CHAPTER 3. Exploring Functions 4. Preprocessing and Compilation 5. Deep Dive into Pointers 6. File Handling 7. Implementing Concurrency 8. Networking and Inter-Process Communication 9. Sorting and Searching 10. Working with Graphs 11. Advanced Data Structures and Algorithms 12. Creativity with Graphics 13. Using MySQL Database 14. General-Purpose Utilities 15. Improving the Performance of Your Code 16. Low-Level Programming 17. Embedded Software and IoT 18. Applying Security in Coding 19. Other Books You May Enjoy

Inserting an element in an array

In this recipe, we will learn how to insert an element in-between an array. You can define the length of the array and also specify the location where you want the new value to be inserted. The program will display the array after the value has been inserted.

How to do it…

1. Let's assume that there is an array, p, with five elements, as follows:

Figure 1.1

Now, suppose you want to enter a value, say 99, at the third position. We will write a C program that will give the following output:

Figure 1.2

Here are the steps to follow to insert an element in an array:

  1. Define a macro called max and initialize it to a value of 100:
#define max 100
  1. Define an array p of size max elements:
int p[max]
  1. Enter the length of the array when prompted. The length you enter will be assigned to a variable n:
printf("Enter length of array:");
scanf("%d",&n);
  1. A for loop will be executed prompting you to enter the elements of the array:
for(i=0;i<=n-1;i++ )
scanf("%d",&p[i]);
  1. Specify the position in the array where the new value has to be inserted:
printf("\nEnter position where to insert:");
scanf("%d",&k);
  1. Because the arrays in C are zero-based, the position you enter is decremented by 1:
k--;
  1. To create space for the new element at the specified index location, all the elements are shifted one position down:
for(j=n-1;j>=k;j--)
p[j+1]=p[j];
  1. Enter the new value which will be inserted at the vacated index location:
printf("\nEnter the value to insert:");
scanf("%d",&p[k]);

Here is the insertintoarray.c program for inserting an element in between an array:

#include<stdio.h>
#define max 100
void main()
{
int p[max], n,i,k,j;
printf("Enter length of array:");
scanf("%d",&n);
printf("Enter %d elements of array\n",n);
for(i=0;i<=n-1;i++ )
scanf("%d",&p[i]);
printf("\nThe array is:\n");
for(i = 0;i<=n-1;i++)
printf("%d\n",p[i]);
printf("\nEnter position where to insert:");
scanf("%d",&k);
k--;/*The position is always one value higher than the subscript, so it is decremented by one*/
for(j=n-1;j>=k;j--)
p[j+1]=p[j];
/* Shifting all the elements of the array one position down from the location of insertion */
printf("\nEnter the value to insert:");
scanf("%d",&p[k]);
printf("\nArray after insertion of element: \n");
for(i=0;i<=n;i++)
printf("%d\n",p[i]);
}

Now, let's go behind the scenes to understand the code better.

How it works...

Because we want to specify the length of the array, we will first define a macro called max and initialize it to a value of 100. I have defined the value of max as 100 because I assume that I will not need to enter more than 100 values in an array, but it can be any value as desired. An array, p, is defined of size max elements. You will be prompted to specify the length of the array. Let's specify the length of the array as 5. We will assign the value 5 to the variable n. Using a for loop, you will be asked to enter the elements of the array.

Let's say you enter the values in the array, as shown in Figure 1.1 given earlier:

In the preceding diagram, the numbers, 0, 1, 2, and so on are known as index or subscript and are used for assigning and retrieving values from an array. Next, you will be asked to specify the position in the array where the new value has to be inserted. Suppose, you enter 3, which is assigned to the variable k. This means that you want to insert a new value at location 3 in the array.

Because the arrays in C are zero-based, position 3 means that you want to insert a new value at index location 2, which is p[2]. Hence, the position entered in k is decremented by 1.

To create space for the new element at index location p[2], all the elements are shifted one position down. This means that the element at p[4] is moved to index location p[5], the one at p[3] is moved to p[4], and the element at p[2] is moved to p[3], as follows:

Figure 1.3

Once the element from the target index location is safely copied to the next location, you will be asked to enter the new value. Suppose you enter the new value as 99; that value will be inserted at index location p[2], as shown in Figure 1.2, given earlier:

Let’s use GCC to compile the insertintoarray.c program, as shown in this statement:

D:\CBook>gcc insertintoarray.c -o insertintoarray

Now, let’s run the generated executable file, insertintoarray.exe, to see the program output:

D:\CBook>./insertintoarray
Enter length of array:5
Enter 5 elements of array
10
20
30
40
50

The array is:
10
20
30
40
50

Enter target position to insert:3
Enter the value to insert:99
Array after insertion of element:
10
20
99
30
40
50

Voilà! We've successfully inserted an element in an array. 

There's more...

What if we want to delete an element from an array? The procedure is simply the reverse; in other words, all the elements from the bottom of the array will be copied one place up to replace the element that was deleted.

Let's assume array p has the following five elements (Figure 1.1):

Suppose, we want to delete the third element, in other words, the one at p[2], from this array. To do so, the element at p[3] will be copied to p[2], the element at p[4] will be copied to p[3], and the last element, which here is at p[4], will stay as it is:

Figure 1.4

The deletefromarray.c program for deleting the array is as follows:

#include<stdio.h>
void main()
{
int p[100],i,n,a;
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter %d elements of the array \n",n);
for(i=0;i<=n-1;i++)
scanf("%d",&p[i]);
printf("\nThe array is:\n");\
for(i=0;i<=n-1;i++)
printf("%d\n",p[i]);
printf("Enter the position/location to delete: ");
scanf("%d",&a);
a--;
for(i=a;i<=n-2;i++)
{
p[i]=p[i+1];
/* All values from the bottom of the array are shifted up till
the location of the element to be deleted */
}
p[n-1]=0;
/* The vacant position created at the bottom of the array is set to
0 */
printf("Array after deleting the element is\n");
for(i=0;i<= n-2;i++)
printf("%d\n",p[i]);
}

Now, let's move on to the next recipe!

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image