C Program To Delete Element of An Array at Specified Position

Write a C program to delete element of an array at user specified position. Show a confirmation message before deleting the element from specified position.

Related Read:
C Program To Shift Elements of An Array by n Position

Example: Expected Input/Output

Enter 5 integer numbers
10
12
14
16
18

Enter the position of the element to be deleted
2

You want to delete element 14 at position 2?
Yes: 1, No: 0
1

Array after deleting the specified element …
10
12
16
18

Visual Representation

delete element of an array at specified position

Video Tutorial: C Program To Delete Element of An Array at Specified Position


[youtube https://www.youtube.com/watch?v=VYGGJnQ1ArE]

YouTube Link: https://www.youtube.com/watch?v=VYGGJnQ1ArE [Watch the Video In Full Screen.]

Source Code: C Program To Delete Element of An Array at Specified Position

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, pos, flag = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    do
    {
        printf("\nEnter the position of the element to be deleted\n");
        scanf("%d", &pos);

        if(pos >= N)
            printf("\nPlease enter position within the range/size of the array\n");
        else
        {
            printf("\nYou want to delete element %d at position %d?\n", a[pos], pos);
            printf("Yes: 1, No: 0\n");
            scanf("%d", &flag);
        }
    }while(flag == 0);

    for(i = pos; i < (N - 1); i++)
        a[i] = a[i + 1];

    printf("\nArray after deleting the specified element ...\n");
    for(i = 0; i < (N - 1); i++)
        printf("%d\n", a[i]);

    printf("\n");

    return 0;
}

Output 1:
Enter 5 integer numbers
1
5
9
7
3

Enter the position of the element to be deleted
4

You want to delete element 3 at position 4?
Yes: 1, No: 0
0

Enter the position of the element to be deleted
2

You want to delete element 9 at position 2?
Yes: 1, No: 0
1

Array after deleting the specified element …
1
5
7
3

Output 2:
Enter 5 integer numbers
1
2
3
4
5

Enter the position of the element to be deleted
15

Please enter position within the range/size of the array

Enter the position of the element to be deleted
0

You want to delete element 1 at position 0?
Yes: 1, No: 0
1

Array after deleting the specified element …
2
3
4
5

Logic To Delete Element of An Array at Specified Position

We ask the user to enter N integer numbers and store it inside array variable a[N]. Next we ask the index position of the element which has to be deleted from the array. Once we’ve these inputs from the user, we show a confirmation message to the user before deleting the specified element. Here user can either choose “1” to delete the element or choose “0” to re-select the element to be deleted.

If user selects “1” and chooses to delete the selected element, then we initialize i to the position of the element to be deleted. We iterate the for loop until i is less than (N – 1), and for each iteration we increment the value of i by 1.

Note: Observe the condition i < (N – 1), which is similar to writing i <= (N – 2). That is because we don’t want to swap/insert the last element of the array with some garbage value present outside the array limit/size.

Inside the for loop
Inside the ‘for loop’ we assign the element present in the next index to the current index element selected by i. i.e,. a[i] is assigned the value present at a[i + 1]. This way the value or the element present at the user selected position is lost, and the index N – 1 and N – 2 will have same elements. While displaying the array elements we leave the last index element, indicating deletion of 1 element from the array – so the array size has been obviously reduced by 1.

Note: Here array variable size isn’t reduced, but we simply do not display the last element of the array and create the illusion of reducing the size of array by 1.

Explanation With Example

If a[5] = {10, 12, 14, 16, 18};
Delete element/number at position: 2
Element at user specified position: 14

    for(i = pos; i < (N - 1); i++)
        a[i] = a[i + 1];

We initialize i to user specified position, which is present in variable pos. Iterate this for loop until i in less than (N – 1), for each iteration increment the value of i by 1.

iposa[i]a[i + 1]a[i] = a[i + 1]
22a[2] = 14a[3] = 16a[2] = 16
32a[3] = 16a[4] = 18a[3] = 18
42a[4] = 18

Now that index i is 4 and the array size is N = 5. So 4 < (5 – 1) is 4 < 4 which returns false, so the control exits the for loop. Using another “for loop” we display the array elements from index 0 to N – 2. i.e., from index i to i < (N – 1) or i <= (N – 2).

So the array elements after execution of above logic:
a[4] = {10, 12, 16, 18};

That’s how we successfully delete a element/number from user specified position 2.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Insert New Element At Specified Position of An Array

Write a C program to insert new element/number at specified position of an array. The array elements need not be in sorted order.

Related Read:
C Program To Shift Elements of An Array by n Position

Example: Expected Input/Output

Enter 10 integer numbers
1
2
3
4
5
6
8
9
10
11
Enter the position where new number has to be inserted
6
Enter a new number to be inserted at position 6
7
Array after inserting 7 at position 6
1
2
3
4
5
6
7
8
9
10
11

Visual Representation

insert element at specified position of an array

Video Tutorial: C Program To Insert New Element At Specified Position of An Array


[youtube https://www.youtube.com/watch?v=oT31byliQPE]

YouTube Link: https://www.youtube.com/watch?v=oT31byliQPE [Watch the Video In Full Screen.]

Source Code: C Program To Insert New Element At Specified Position of An Array

#include<stdio.h>
#define N 11

int main()
{
    int a[N], i, pos, num;

    printf("Enter %d integer numbers\n", (N - 1));
    for(i = 0; i < (N -1); i++)
        scanf("%d", &a[i]);

    printf("Enter the position where new number has to be inserted\n");
    scanf("%d", &pos);

    if(pos < N)
    {
        printf("Enter a new number to be inserted at position %d\n", pos);
        scanf("%d", &num);
        for(i = N - 1; i > pos; i--)
                a[i] = a[i - 1];

        a[pos] = num;

        printf("Array after inserting %d at position %d\n", num, pos);
        for(i = 0; i < N; i++)
            printf("%d\n", a[i]);
    }
    else
    {
        printf("Please enter a position within the range/size of the array!\n");
    }

    printf("\n");

    return 0;
}

Output:
Enter 10 integer numbers
11
25
52
36
98
92
45
69
59
2
Enter the position where new number has to be inserted
5
Enter a new number to be inserted at position 5
100
Array after inserting 100 at position 5
11
25
52
36
98
100
92
45
69
59
2

Logic To Insert New Element At Specified Position of An Array

We ask the user to enter (N – 1) number of elements and store it inside array variable a[N]. We leave the last index position empty(technically it’ll automatically have zero as the element). Now we ask the user to enter the position where he or she wants to insert new number/element. Next we ask the user to input the new number to be inserted at the specified position. Once we get the position and the new number, we start the “for loop”.

We initialize i with last index of the array, which is N – 1. We iterate the array until i is greater than the user entered position.

Note: We iterate the for loop only until i is greater than user specified position because, we need to shift the elements to right by 1 position only after the position/index indicated by the user. We won’t move any elements above the user specified position.

Inside for loop
Inside for loop we move the elements by 1 position to the bottom or right. Ex: if i value is 5, then a[5] will be assigned whatever the value is present in it’s previous index a[4].

        for(i = N - 1; i > pos; i--)
                a[i] = a[i - 1];

        a[pos] = num;

Once all the elements from user input position move 1 position right/down, we insert the new element/number at user specified position.

Explanation With Example

If a[6] = {5, 7, 3, 2, 1};
Position to insert new element/number: 2
New number to be inserted: 9

        for(i = N - 1; i > pos; i--)
                a[i] = a[i - 1];

        a[pos] = num;

We initialize i to last index of the array, which is N – 1. Since N is 6 in this case, 6 -1 is 5. So i is initialized to 5. We’ve not assigned any element/value to a[5]. Technically it’ll have 0.

iposa[i]a[i – 1]a[i] = a[i – 1]
52a[5] = 0a[4] = 1a[5] = 1
42a[4] = 1a[3] = 2a[4] = 2
32a[3] = 2a[2] = 3a[3] = 3
22

Now that index i is 2 and user input position is also 2. So 2 > 2 returns false, so the control exits the for loop. Outside for loop we’ve a[pos] = num. So the position is 2 and the new number to be inserted is 9. i.e., a[2] = 9.

So the array elements after execution of above logic:
a[6] = {5, 7, 9, 3, 2, 1};

That’s how we successfully inserted new element/number 9 at position 2.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Shift Elements of An Array by n Position

Write a C program to shift elements of an array by n positions or rotate the array elements n times.

Example: Expected Input/Output

Input/Output
Enter 5 integer numbers
1
2
3
4
5
Enter the number of positions to shift
1
Enter the direction of shifting …
LEFT: 1 and RIGHT: 0
1
Array after shift operation …
2
3
4
5
1

Visual Representation

Shifting elements of an array

Video Tutorial: C Program To Shift Elements of An Array by n Position


[youtube https://www.youtube.com/watch?v=Fz-oyhu9Ccc]

YouTube Link: https://www.youtube.com/watch?v=Fz-oyhu9Ccc [Watch the Video In Full Screen.]

Source Code: C Program To Shift Elements of An Array by n Position

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, temp, pos, dir;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Enter the number of positions to shift\n");
    scanf("%d", &pos);

    printf("Enter the direction of shifting ...\n");
    printf("LEFT: 1 and RIGHT: 0\n");
    scanf("%d", &dir);

    while(pos)
    {
        if(dir)
        {
            temp = a[0];
            for(i = 0; i < N - 1; i++)
                a[i] = a[i + 1];

            a[N - 1] = temp;
        }
        else
        {
            temp = a[N - 1];
            for(i = N - 1; i > 0; i--)
                a[i] = a[i - 1];

            a[0] = temp;
        }

        pos--;
    }

    printf("Array after shift operation ...\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    printf("\n");

    return 0;
}

Output 1:
Enter 5 integer numbers
1
2
3
4
5
Enter the number of positions to shift
2
Enter the direction of shifting …
LEFT: 1 and RIGHT: 0
0
Array after shift operation …
4
5
1
2
3
Output 2:
Enter 5 integer numbers
1
2
3
4
5
Enter the number of positions to shift
2
Enter the direction of shifting …
LEFT: 1 and RIGHT: 0
1
Array after shift operation …
3
4
5
1
2

Logic To Shift Elements of An Array by n Position

First we ask the user to input N integer numbers and store it inside array variable a[N]. We then ask the user to input the number of positions to shift the elements of the array, and then the direction of shifting. If user inputs 1, then its LEFT shift, if user inputs 0, then its RIGHT shift operation.

Left Shift Operation

            temp = a[0];
            for(i = 0; i < N - 1; i++)
                a[i] = a[i + 1];

            a[N - 1] = temp;

If elements are shifted to left by 1 position, the first element which is present at a[0] will be lost. So we preserve it by transferring value present at a[0] to temp. Next we write a for loop.

We initialize 0 to i and iterate the “for loop” until i is less than (N – 1). Less than (N – 1) means it excludes the last element of the array present at index (N – 1) and that is because we’ll be storing the value present in variable temp to a[N – 1], after the execution of “for loop” completes.

Inside for loop, we transfer the value present at a[i + 1] to a[i]. That way we will be shifting elements of array to left by one position.

Right Shift Operation

            temp = a[N - 1];
            for(i = N - 1; i > 0; i--)
                a[i] = a[i - 1];

            a[0] = temp;

If elements are shifted to right by 1 position, the last element which is present at a[N – 1] will be lost. So we preserve it by transferring value present at a[N – 1] to temp. Next we write a for loop.

We initialize i to (N – 1) and iterate the “for loop” until i is greater than 0 and for each iteration we decrement the value of i by 1. Inside the “for loop” we assign a[i – 1] to a[i]. That is, we keep assigning the value backwards by 1 position. After completion of “for loop” execution, we assign the value of temp to the first index, which is a[0].

In “for loop” condition, we’re checking until i is greater than 0. That means, we’re not checking for i is equal to 0. That is because, at the end of “for loop” we assign the value present in temp to a[0].

While Loop
We put the whole logic of moving the elements to right and left inside of a while loop. While loop executes until variable pos is not equal to zero. Inside “while loop” we keep decrementing the value of i by 1 for each iteration. This way, we keep shifting the elements of the array by 1 position for every iteration of “while loop”. So if user wants to shift the elements to left by 2 positions, the entire “left shifting code/logic” will execute twice – moving the elements of the array 2 positions left.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Re-arrange Even and Odd Elements of An Array

Lets write a C program to re-arrange even and odd elements of an array.

Note: We need to arrange EVEN numbers at the top and ODD numbers to the bottom of the same array.

Example: Expected Input/Output

Enter 5 integer numbers
11
10
13
12
15

After re-arranging even and odd elements …
10
12
13
11
15

Visual Representation

Rearranging even and odd elements of an array

Video Tutorial: C Program To Re-arrange Even and Odd Elements of An Array


[youtube https://www.youtube.com/watch?v=RfAdoYetz3M]

YouTube Link: https://www.youtube.com/watch?v=RfAdoYetz3M [Watch the Video In Full Screen.]

Source Code: C Program To Re-arrange Even and Odd Elements of An Array

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, j = N, temp;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i <= j; i++)
    {
        if(a[i] % 2 != 0)
        {
            while(j > i)
            {
                j--;
                if(a[j] % 2 == 0)
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    break;
                }
            }
        }
    }

    printf("\nAfter re-arranging even and odd elements ...\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 10 integer numbers
1
2
3
4
5
6
7
8
9
10

After re-arranging even and odd elements …
10
2
8
4
6
5
7
3
9
1

Logic To Re-arrange Even and Odd Elements of An Array

First we accept N integer numbers from the user and store it inside a[N]. Using “for loop” we iterate through the array elements one by one.

Inside For Loop
We initialize i to 0, which is the first index of any array. We iterate through this “for loop” until i is less than or equal to j. j represents the number of elements already sorted from bottom(N – 1) of the array. i.e., from index j to (N – 1) all the elements are already odd numbers. For each iteration of the for loop we increment the value of i by 1.

First if condition – inside for loop
Aim of our C program is to move all the even elements to top and odd elements to the bottom. So if the “for loop” selected element, which is present in a[i] already has a even number then we let that number stay there itself, and increment the value of i by one. If the “for loop” selected number, which is present in a[i] has odd number, then we start searching for a even number from the bottom of the same array to swap it with a[i].

Inside While loop
Assume that a[i] has a odd number. Now lets initialize j to the size of array, which is N. “While loop” executes until j is greater than i. Here i represents the number of elements already sorted from the top. i.e., from index 0 to i all the elements are already even numbers.

This “while loop” executes until j is greater than i. The value of i is set by “for loop”. It’s the index of the element which is selected by the “for loop”, which has ODD number. i.e., if the control has entered “while loop” that means a[i] has ODD number. “While Loop” checks for EVEN element from the bottom of the array to swap it with the ODD number present at a[i].

Second if condition – inside while loop
As soon as control enters the while loop we reduce the value of j by 1. So now j is (N – 1), which is the last element of any array. Next, if the “while loop” selected element, which is present at a[j] has EVEN number, then we swap that number with the ODD number present in a[i], and break out of the while loop.

For each iteration of “while loop” we decrement the value of j by 1. And we do not reset the value of j for each iteration of “for loop”.

Printing re-arranged array elements
Once control exits “for loop” we print the array elements from 0 to N -1 and it’ll have all EVEN numbers at the top and ODD numbers at the bottom.

Explanation With Example

If int a[5] = {11, 10, 13, 12, 15};
ODD: a[i] % 2 != 0
EVEN: a[j] % 2 == 0

    j = N;
    for(i = 0; i <= j; i++)
    {
        if(a[i] % 2 != 0)
        {
            while(j > i)
            {
                j--;
                if(a[j] % 2 == 0)
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    break;
                }
            }
        }
    }
ia[i]ODDja[j]EVENSwap
011TRUE415FALSENO
011TRUE312TRUEYES
110FALSE213FALSENO

As you can see from above table swapping occurs at a[0] and a[3]. a[0] has integer number 11 and a[3] has integer number 12. So after swapping these numbers a[5] will be: {12, 10, 13, 11, 15}; So a[0], a[1] has EVEN numbers and a[2], a[3], a[4] has ODD numbers.

Important Note: i always represents the number of elements sorted from top(EVEN numbers), and j represents the index from (N – 1) which are sorted from bottom(ODD numbers).

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Divide/Split An Array Into Two At Specified Position

Lets write a C program to split or divide an array into two arrays at specified position.

Example: Expected Input/Output

Enter 10 integer numbers
-5
-4
-3
-2
-1
0
1
2
3
4
Enter position to split the array in to Two
4

Elements of First Array -> arr1[4]
-5
-4
-3
-2

Elements of Second Array -> arr2[6]
-1
0
1
2
3
4

Visual Representation

Split array at specified position

Video Tutorial: C Program To Divide/Split An Array Into Two At Specified Position


[youtube https://www.youtube.com/watch?v=L4xLWpUmNvw]

YouTube Link: https://www.youtube.com/watch?v=L4xLWpUmNvw [Watch the Video In Full Screen.]

Source Code: C Program To Divide/Split An Array Into Two At Specified Position

#include<stdio.h>

#define N 10

int main()
{
    int a[N], arr1[N], arr2[N], i, pos, k1 = 0, k2 = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    printf("Enter position to split the array in to Two\n");
    scanf("%d", &pos);

    for(i = 0; i < N; i++)
    {
        if(i < pos)
            arr1[k1++] = a[i];
        else
            arr2[k2++] = a[i];
    }

    printf("\nElements of First Array -> arr1[%d]\n", k1);
    for(i = 0; i < k1; i++)
        printf("%d\n", arr1[i]);

    printf("\nElements of Second Array -> arr2[%d]\n", k2);
    for(i = 0; i < k2; i++)
        printf("%d\n", arr2[i]);

    printf("\n");

    return 0;
}

Output:
Enter 10 integer numbers
1
2
3
4
5
6
7
8
9
1
Enter position to split the array in to Two
3

Elements of First Array -> arr1[3]
1
2
3

Elements of Second Array -> arr2[7]
4
5
6
7
8
9
1

Logic To Divide/Split An Array Into Two At Specified Position

We accept N integer numbers from the user and store it inside array variable a[N]. Now we ask the user to input the position at which we need to split the array and create two separate arrays. Next, we iterate through array elements of a, using for loop(loop counter variable i is initialized to 0 and for loop executes until i < N and for each iteration of for loop i value increments by 1) and transfer all the elements of array a to array variable arr1 until i is less than user input position. Once i is greater than or equal to user input position, we transfer elements of a to array variable arr2.

Note: We’ve initialized k1 and k2 to 0, as index starts from 0. Whenever we push / insert values inside arr1 and arr2, we increment the index value of k1 and k2 respectively.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert