English

Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted.

Advertisements
Advertisements

Question

Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted.

Code Writing
Advertisements

Solution

include <stdio.h>
int main()
{
    int list[100], n, element, position, i;
    // Input number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    // Input list elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &list[i]);
    }
    // Input element to be inserted
    printf("Enter the element to be inserted: ");
    scanf("%d", &element);
    // Input position
    printf("Enter the position at which to insert: ");
    scanf("%d", &position);
    // Shift elements to the right
    for(i = n; i >= position; i--)
    {
        list[i] = list[i - 1];
    }
    // Insert the element
    list[position - 1] = element;
    n++;
    // Display the updated list
    printf("List after insertion:\n");
    for(i = 0; i < n; i++)
    {
        printf("%d ", list[i]);
    }
    return 0;
}

Output:

Enter the number of elements: 5

Enter 5 elements:

10 20 30 40 50

Enter the element to be inserted: 25

Enter the position at which to insert: 3

List after insertion:

10 20 25 30 40 50

shaalaa.com
  Is there an error in this question or solution?
Chapter 4: Working with Lists and Dictionaries - Programming Problems [Page 77]

APPEARS IN

NCERT Informatics Practices [English] Class 11
Chapter 4 Working with Lists and Dictionaries
Programming Problems | Q 6. | Page 77
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×