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 Find Size of An Array

Lets write c program to find number of elements present in an array, where the array size is not mentioned explicitly.

Related Read:
Sizeof Operator in C Programming Language

Example: Expected Output

int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23, 56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};
We have 25 no of elements in array.

Video Tutorial: C Program To Find Number of Elements In An Array


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

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

Source Code: C Program To Find Size of An Array

Method 1

#include<stdio.h>

int main()
{
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23,
               56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};

    int count = sizeof(a) / sizeof(int);

    printf("We have %d no of elements in array\n", count);

    return 0;
}

Output:
We have 25 no of elements in array.

We know that array variable name contains base address or the address of first array element. But sizeof(array_name) gives back the number of bytes occupied by the entire array. Now divide this value by the memory occupied by 1 element – this can be determined either by using sizeof() on the data type(as shown in above source code) or any of the element in the array(as shown in below source code).

Method 1

#include<stdio.h>

int main()
{
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23,
               56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};

    int count = sizeof(a) / sizeof(a[0]);

    printf("We have %d no of elements in array\n", count);

    return 0;
}

Output:
We have 25 no of elements in array.

We assume that the array will at least have 1 element, so we find the number of bytes occupied by it. This is the best approach because, this way we’ll not be compelled to change the data type passed to sizeof() operator whenever we need to check the number of elements present in a array of different data type.

Method 3: Using Macros

#include<stdio.h>

#define SIZE(a) ( sizeof(a) / sizeof(a[0]) )

int main()
{
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23,
               56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};

    printf("We have %d no of elements in array.\n", SIZE(a));

    return 0;
}

Output:
We have 25 no of elements in array.

Here we pass the array variable name to macro SIZE(). Again the macro expansion will be replacing the macro template before passing the source code to the compiler.

Related Read:
Macros With Arguments: C Program

Using this method has advantage too. We can calculate size of multiple array variables, of different data type: as shown in below example.

Method 4: Using Macros

#include<stdio.h>

#define SIZE(a) ( sizeof(a) / sizeof(a[0]) )

int main()
{
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23,
               56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};
    char ch[] = {'i', 'P', 'h', 'o', 'n', 'e'};
    double dbl[] = {2.3, 4, 5.2, 6.3, 7.1, 3.4, 1.3};

    printf("Integer variable a[%d].\n", SIZE(a));
    printf("Character variable ch[%d].\n", SIZE(ch));
    printf("Double variable dbl[%d].\n", SIZE(dbl));

    return 0;
}

Output:
Integer variable a[25].
Character variable ch[6].
Double variable dbl[7].

Here we find the number of elements present in array variable a and ch using the same macro SIZE.

Where Is It useful?

Whenever we want to iterate through individual elements of the array and we’ve no idea whats the size of the array or whats the largest designator of that array. In such cases we can’t write condition inside loop.

Using above formula we could easily find the number of elements present in the array and make use of the result in our for loop condition:

#include<stdio.h>

#define SIZE(a) ( sizeof(a) / sizeof(a[0]) )

int main()
{
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2, 23,
               56, 67, 8, 9, 0, 3, 2, 1, 4, 5, 6, 7, 8};
    int count = SIZE(a);

    for(i = 0; i < count; i++)
        printf("%d\n", a[i]);

    return 0;
}

This prints all the elements of the array.

Note: Do not write i < SIZE(a) condition directly inside for loop. This would create unnecessory overhead, as for each iteration SIZE(a) [which will be replaced by ( sizeof(a) / sizeof(a[0]) ) while preprocessing] has to calculate the size of the array. Instead calculate the size of array once and store it inside a variable and then use that variable in your for loop as shown in above source code.

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

Size of Array using Macro and Constant: C Program

In this video tutorial lets see how we can assign size of an array using macros and constants.

Related Read:
For Loop In C Programming Language
Introduction To Arrays: C Programming Language
Keywords, Constants, Variables: C

Disadvantage of Not Using Macro or Constant To Assign Array Size

If requirement of the program/software changes and you need to increase or decrease the array size, then you’ll have to be very careful and scan through the entire source code and make changes at multiple locations. Even if you skip changing the array size information at one place, you’ll start getting wrong results.

And if you have any business logic which makes use of array size, then you’ll have hard time rectifying and debugging the code. It’ll take unnecessary time and effort to make it work correctly once again.

By making use of Macros or constant variables you can handle this very efficiently. You can make the change at one place and it’ll take effect at all the places in your source code.

Watch the video below for demonstration of effectiveness of using macros and constants for assigning size of an array.

Video Tutorial: Assign Size of Array using Macro and Constant: C Program


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

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

Source Code: Size of Array using Macro and Constant: C Program

Without using Macros and/or constants

#include<stdio.h>

int main()
{
    int a[5], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Here we have a array variable with size 5. We enter 5 integer variables and we display those elements using for loop. In for loop condition we mention the number of times it has to iterate.

Now assume that the requirement changes and we need to increase the size of array from 5 to 7:

#include<stdio.h>

int main()
{
    int a[7], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < 7; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

As you can see we made edits at 4 places. Its a very simple program and even in that we had to make 4 edits. What if the program is huge and the requirement changes?

Macros

Assign Array size using Macros

#include<stdio.h>

#define N 5

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Observe the changes we’ve made in the source code. We’re defining a macro here. Macro template is N and macro expansion is 5. We replace the value 5 inside main method by macro name N.

#include<stdio.h>

#define N 7

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the macro expansion from 5 to 7, and it starts working as intended.

Constants

Assign Array size using Constants

#include<stdio.h>

int main()
{
    const int N = 5;
    int a[N], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Observe the changes we’ve made in the source code. We’ve declared and initialized a constant variable N. Constant variable name is N and its value is 5. We replace the value 5 inside main method by constant variable N.

#include<stdio.h>

int main()
{
    const int N = 7;
    int a[N], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the value of constant variable N from 5 to 7, and the program works as intended.

Note: It’s always considered best practice to either use macros or constant variables to assign array size. This practice will prove to be very advantageous while writing big programs.

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

Basics of Arrays: C Program

Lets look at basics of arrays in C programming language. We’ve already covered a lot of stuffs about arrays in Introduction To Arrays: C Programming Language. In this video tutorial we’ll look at some specific things about arrays which we use often.

Related Read:
For Loop In C Programming Language
Sizeof Operator in C Programming Language

Declaring Array Variable

Syntax:

Data_type variable_name[array_size];

Ex: int a[5];

Here array variable is a, it can hold upto 5 integer values.

Index of array starts from zero, and it ends at N-1. N being the size of the array.

For Ex:
int a[N];
Here the first element of array a is at a[0] and the last element is at a[N-1].

Definition of Array

An array is a collection of data items, of same data type, accessed using a common name.

Video Tutorial: Basics of Arrays: C Program


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

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

Source Code: Basics of Arrays: C Program

Printing all the elements of an array

#include<stdio.h>

int main()
{
    int a[5] = {1, 2, 3, 4, 5}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
1
2
3
4
5

This prints all the elements of an array. In this program we’re declaring and initializing array variable simultaneously.

Empty curly braces for Array Variable

#include<stdio.h>

int main()
{
    int a[5] = {}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
0
0
0
0
0

Compiler will insert zero in all the empty spots.

Un-initialized Array Variable

#include<stdio.h>

int main()
{
    int a[5], i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
6356864
4200750
4200656
46
8

If array variable is left un-initialized it’ll have garbage values inside it.

Array Variable Not fully initialized Manually

#include<stdio.h>

int main()
{
    int a[5] = {3, 2}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
3
2
0
0
0

Whenever we assign less values than the array size, the remaining elements will get assigned to 0.

Expression As Array Size

#include<stdio.h>

int main()
{
    int a[2+3] = {3, 2, 1, 0, 5}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
3
2
1
0
5

Any valid expression which ultimately resolves to a positive integer is valid inside square brackets.

Negative Integer Number As Array Size

#include<stdio.h>

int main()
{
    int a[-5] = {3, 2, 1, 0, 5}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
error: size of array ‘a’ is negative
warning: excess elements in array initializer

You can only have positive integer as size of an array and nothing else.

Trying To Assign More Values Than The Array Size

#include<stdio.h>

int main()
{
    int a[5] = {1, 2, 3, 4, 5, 6, 7}, i;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
warning: excess elements in array initializer

You can’t assign more values than the array size.

Overwrite values present at an index: Array

#include<stdio.h>

int main()
{
    int a[5] = {1, 2, 3, 4, 5}, i;

    a[3]  = 100;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
1
2
3
100
5

Here the previous value present at index 3(which can be access using a[3]), is overwritten by value 100.

Garbage Values In Empty Spots: Array

#include<stdio.h>

int main()
{
    int a[5], i;

    a[3]  = 100;

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Array elements are:
6356864
4200766
4200672
100
8

As you can see, the element at index 3 has 100, and all other elements value is just garbage values.

Array Size In Memory

#include<stdio.h>

int main()
{
    int    a[5];
    float  b[5];
    char   c[5];
    double d[5];

    printf("Int    Array: %d\n", 5 * sizeof(int));
    printf("Float  Array: %d\n", 5 * sizeof(float));
    printf("Char   Array: %d\n", 5 * sizeof(char));
    printf("Double Array: %d\n", 5 * sizeof(double));

    return 0;
}

Output:
Int Array: 20
Float Array: 20
Char Array: 5
Double Array: 40

Each cell in array occupies memory space depending upon its data type. Int and float occupies 4 bytes. Char occupies 1 byte. Double occupies 8 bytes. Also remember, size of data type is machine dependent.

Initializing and Accessing Array Elements

#include<stdio.h>

int main()
{
    int a[5], i;

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

    printf("Array elements are: \n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

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