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 Count Number of Positive, Negative and Zeros In An Array

Lets write a C program to count number of positive, negative and zeros in an Array.

Logic

number scale
If input number is greater than 0, then its positive number. If input number is less than 0, then its negative. If its neither greater than 0, nor less than 0, then the input number must be 0.

Related Read:
Number is Positive or Negative or Zero: C Program

Example: Expected Input/Output

Enter 10 integer numbers
-5
-4
-3
-2
-1
0
1
2
3
4

Positive no: 4
Negative no: 5
Zeros: 1

Visual Representation

count positive negative zero in an array

Video Tutorial: C Program To Count Number of Positive, Negative and Zeros In An Array


[youtube https://www.youtube.com/watch?v=Z1mES-0NM-E]

YouTube Link: https://www.youtube.com/watch?v=Z1mES-0NM-E [Watch the Video In Full Screen.]

Source Code: C Program To Count Number of Positive, Negative and Zeros In An Array

Method 1

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, p = 0, n = 0, z = 0;

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

    for(i = 0; i < N; i++)
    {
        if(a[i] > 0)
            p++;
        else if(a[i] < 0)
            n++;
        else
            z++;
    }

    printf("\nPositive no: %d\nNegative no: %d\nZeros: %d\n", p, n, z);

    return 0;
}

Output:
Enter 10 integer numbers
-5
-4
-3
-2
-1
0
1
2
3
4

Positive no: 4
Negative no: 5
Zeros: 1

Logic To Find Number of Positive, Negative and Zeros In An Array

First we initialize 0 to variables p, n and z – which represents positive, negative and zero. We accept 10 integer numbers from the user. Next we iterate through the array using for loop and check if the fetched array element is greater than 0, which means its a positive number, so we increment the value of variable p by one. If fetched array element is less than 0, which means its a negative number, so we increment the value of variable n by one. If both the cases fail, then the number must be zero, so we increment the value of z by 1.

After the completion of for loop execution, variables p, n and z will have the number of positive, negative and zeros present in the array.

Method 2

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, p = 0, n = 0, z = 0;

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

        if(a[i] > 0)
            p++;
        else if(a[i] < 0)
            n++;
        else
            z++;
    }

    printf("\nPositive no: %d\nNegative no: %d\nZeros: %d\n", p, n, z);

    return 0;
}

Output:
Enter 10 integer numbers
1
2
3
4
0
-1
-2
-3
-4
-5

Positive no: 4
Negative no: 5
Zeros: 1

In above source code, once the user inputs a number, we check if the input number is greater than 0 or less than zero or is equal to zero, and increment the values of variable p, n and z accordingly.

This is the best solution for this problem statement, as we only write for loop once and we calculate the result as and when user inputs array elements. Less overhead and more efficient.

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 Count Number of Even, Odd and Zeros In An Array

Lets write a C program to count number of even, odd and zeros in an array.

What are Even and Odd Numbers?

An even number is an integer that is exactly divisible by 2. An odd number is an integer that is not exactly divisible by 2.

Related Read:
Even or Odd Number: C Program

Example: Expected Output

Enter 10 integer numbers
10
15
0
-1
5
20
21
55
69
40

Even Numbers: 3
Odd Numbers: 6
Zeros: 1

Visual Representation

count even odd zero in an array

Video Tutorial: C Program To Count Number of Even, Odd and Zeros In An Array


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

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

Source Code: C Program To Count Number of Even, Odd and Zeros In An Array

Method 1

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, odd = 0, even = 0, zero = 0;

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

    for(i = 0; i < N; i++)
    {
        if(a[i] == 0)
            zero++;
        else if(a[i] % 2 == 0)
            even++;
        else if(a[i] % 2 != 0)
            odd++;
    }

    printf("\nEven Numbers: %d\nOdd Numbers: %d\nZeros: %d\n", even, odd, zero);

    return 0;
}

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

Even Numbers: 4
Odd Numbers: 5
Zeros: 1

Logic To Find Number of Even, Odd and Zeros In An Array

First we ask the user to enter N integer numbers. After that we iterate through the array elements one by one (using a for loop) and check if the fetched number is 0, if true, we’ll increment the value of zero by one. If the fetched element is not zero, then we check if its perfectly divisible by 2, if so, then its even number orelse its odd number – and we increment the values of variable even and odd accordingly.

Note: Make sure to first check if the fetched number is 0. Only after checking this, go further and check for even or odd conditions.

Method 2

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, even = 0, odd = 0, zero = 0;

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

        if(a[i] == 0)
            zero++;
        else if(a[i] % 2 == 0)
            even++;
        else if(a[i] % 2 != 0)
            odd++;
    }

    printf("\nEven No: %d\nOdd No: %d\nZeros: %d\n", even, odd, zero);

    return 0;
}

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

Even Numbers: 4
Odd Numbers: 5
Zeros: 1

In above source code, once the user inputs a number, we check if the input number is equal to zero or is perfectly divisible by 2 or it is not perfectly divisible by 2. Based on that we increment the values of variable zero, even and odd accordingly.

This is the best solution for this problem statement, as we only write for loop once and we calculate the result as and when user inputs array elements. So less overhead and more efficient.

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 Merge Two Arrays Alternatively

Lets write a C program to merge two arrays into third array in alternative position.

Example: Expected Output

Enter 5 elements for array a
10
12
14
16
18
Enter 5 elements for array b
11
13
15
17
19

Merging arrays a & b into c in alternate position
Array elements of c is:
10
11
12
13
14
15
16
17
18
19

Visual Representation of arrays a, b and c

Step 1: after first for loop
Copying array a to c
Step 2: after second for loop
Copying array b to c

Video Tutorial: C Program To Merge Two Arrays Alternatively


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

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

Source Code: C Program To Merge Two Arrays Alternatively

Method 1: Array a and b are of same size

#include<stdio.h>

#define N 5
#define M (N * 2)

int main()
{
    int a[N], b[N], c[M], i, k;

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

    printf("Enter %d elements for array b\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &b[i]);

    printf("\nMerging arrays a & b into c in alternate position\n");
    for(i = 0, k = 0; i < N; i++, k += 2)
        c[k] = a[i];

    for(i = 0, k = 1; i < N; i++, k += 2)
        c[k] = b[i];

    printf("Array elements of c is:\n");
    for(i = 0; i < M; i++)
        printf("%d\n", c[i]);

    return 0;
}

Output:
Enter 5 elements for array a
0
2
4
6
8
Enter 5 elements for array b
1
3
5
7
9

Merging arrays a & b into c in alternate position
Array elements of c is:
0
1
2
3
4
5
6
7
8
9

Logic To Merge Arrays a and b into c in Alternate positions

Here array variables a and b have same size. To copy the elements of array variable a to c, we initialize i to 0 and k to o, and start assigning values from a[i] to k[k], we increment the value of i by 1 for each iteration of for loop, but we increment the value of k by 2 for each iteration of first for loop. This way we assign elements of a to the values present at index 0, 2, 4, 6, 8 of array variable c.

In the next for loop, we reset the value of i to 0, and k value is rest to 1. k value keeps incrementing by 2 for each iteration of for loop, while i value increments by 1 for each iteration of the for loop. So the values present at index 0, 1, 2, 3, 4 of variable b are copied to the index places of 1, 3, 5, 7, 9 of array variable c.

Method 2: Array a and b are of different size

#include<stdio.h>

#define N1 3
#define N2 8
#define M  ( (N1 > N2) ? (N1 * 2) : (N2 * 2) )

int main()
{
    int a[N1], b[N2], c[M] = {0}, i, k;

    printf("Enter %d elements for array a\n", N1);
    for(i = 0; i < N1; i++)
        scanf("%d", &a[i]);

    printf("Enter %d elements for array b\n", N2);
    for(i = 0; i < N2; i++)
        scanf("%d", &b[i]);

    printf("\nMerging arrays a & b into c in alternate position\n");
    for(i = 0, k = 0; i < N1; i++, k += 2)
        c[k] = a[i];

    for(i = 0, k = 1; i < N2; i++, k += 2)
        c[k] = b[i];

    printf("Array elements of c is:\n");
    for(i = 0; i < M; i++)
        printf("%d\n", c[i]);

    return 0;
}

Output:
Enter 3 elements for array a
0
2
4
Enter 8 elements for array b
1
3
5
6
7
8
9
10

Merging arrays a & b into c in alternate position
Array elements of c is:
0
1
2
3
4
5
0
6
0
7
0
8
0
9
0
10

Logic To Merge 2 arrays(of different size) Into 3rd Array

As you can see we’re using macros to assign size to the arrays a and b. You can change the size and play around to check different output for different input sizes.

N1 is the size of array a, N2 is the size of array b. Please execute this program and modify the values of N1 to be bigger than N2 and next change N2 to be bigger than N1, and then make both N1 and N2 equal – and check the outputs.

Inside macro M, which is the size of resultant array(c[M]), we store double the size of the biggest array we’re merging into c. We are doing this because, the sizes of the arrays to be merged might be different and the remaining positions will be filled with garbage values. So instead we’ll be pre-filling zeros in the places where there are no elements to fill.

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