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 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

C Program To Check Repetition of Digit In A Number using Arrays

Lets write a C program to check if any digit in a user input number appears more than once.

Note: Any positive integer number can be formed using only 0-9 digits. So we take an array with length 10. i.e., 0 to 9

array of size 10

Video Tutorial: C Program To Check Repetition of Digit In A Number using Arrays


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

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

Source Code: C Program To Check Repetition of Digit In A Number using Arrays

#include<stdio.h>

int main()
{
    int a[10] = {0}, num, rem;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    while(num)
    {
        rem = num % 10;

        if(a[rem] == 1)
            break;
        else
            a[rem] = 1;

        num = num / 10;
    }

    if(num)
        printf("There are repetition of digits in the number\n");
    else
        printf("There are no repetition of digits in the number\n");

    return 0;
}

Output 1:
Enter a positive number
123
There are no repetition of digits in the number

array of size 10

Output 2:
Enter a positive number
156
There are no repetition of digits in the number

array of size 10

Output 3:
Enter a positive number
1232
There are repetition of digits in the number

Logic To Check if any digit in user input number repeats or not

1. Since there are 10 digits i.e., 0 to 9 to form any number, we take array size as 10. We initialize all the elements of array to 0.

Related Read:
Basics of Arrays: C Program

2. We ask the user to input a positive number.

3. We iterate through the while loop until num is zero.

Related Read:
while loop in C programming

4. By modulo dividing user input number by 10, we fetch individual digits of number. We make use of this individual digit as index of the array. We over-write the initial value(which is zero) and assign 1 at that index position.

So presence of value 1 at an index specifies that the digit already exists in the number.

Related Read:
Modulus or Modulo Division In C Programming Language

5. So based on the presence of value 1 or 0 at particular index, our program decides if the digit is present more than once in a number or not.

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

Remove Element On Click: Ionic 2

This is a basic example wherein we have a list of company names and once the user clicks on individual name, that name gets removed from the list. We’ve not included the http calls and database in this example to keep things simple and minimalistic.

Related Read:
Basics of Page Component: Ionic 2
ngIf, index, first, last: Ionic 2

Remove Element On Click: Ionic 2


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

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



src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
companies: Array< {}>;
  constructor(public navCtrl: NavController) {
    this.companies = [
      {name: 'Microsoft', code: 1},
      {name: 'Apple', code: 2},
      {name: 'Google', code: 3},
      {name: 'Oracle', code: 4},
      {name: 'IBM', code: 5}
    ];
  }
  remove(no){
    (this.companies).splice(no, 1);
  };
}

Here we have an array variable called companies, which has 5 company names in object format. We also have a method called remove which takes 1 parameter. This parameter is the index number of the item being clicked by the user. Once we get this index number we make use of JavaScript’s splice() method and remove the element from the array. Splice takes 2 arguments, the first one being the index(or the position) of the element to be removed and the second argument is the number of elements to be removed from position of the index received.

src/pages/home/home.html

< ion-list no-lines>
  < ion-item *ngFor="let company of companies; 
                     let i = index;" 
             (click)="remove(i);">
     {{company.name}}
  < /ion-item>
< /ion-list>

Here we assign index value to a variable i. We then pass this value of i to remove method once the user clicks on an item. i.e., we pass the index value of the item being clicked by the user, to the remove method.

Real-time Applications
In real-time applications we’ll pass a unique id of the clicked element to the remove method, which is then passed on to some http calls, which removes the item from the database(usually) and if the remove operation is successful we’ll remove the item from the User Interface using JavaScripts Splice() method. And if the remove operation fails, we’ll display appropriate message to the user.