Knowee
Questions
Features
Study Tools

write c program to insert the values at the specific index in the array without using functions

Question

Write a C program to insert the values at the specific index in the array without using functions

🧐 Not the exact question you are looking for?Go ask a question

Solution

Here's a simple C program that allows you to insert values at a specific index in an array without using functions.

#include <stdio.h>

int main() {
    int n, index, value, i;

    // Define the size of the array
    printf("Enter size of the array: ");
    scanf("%d", &n);
    
    int array[n + 1]; // Increase size by 1 to accommodate new element

    // Input existing elements into the array
    printf("Enter the elements of the array:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &array[i]);
    }

    // Input index and value to be inserted
    printf("Enter the index where you want to insert: ");
    scanf("%d", &index);
    printf("Enter the value to insert: ");
    scanf("%d", &value);

    // Validate the index
    if (index < 0 || index > n) {
        printf("Invalid index!\n");
    } else {
        // Shift elements to the right to create space for the new element
        for (i = n; i > index; i--) {
            array[i] = array[i - 1];
        }
        // Insert the new value
        array[index] = value;

        // Print the updated array
        printf("Array after insertion:\n");
        for (i = 0; i <= n; i++) {
            printf("%d ", array[i]);
        }
    }

    return 0;
}

Explanation:

  1. The program first asks for the size of the array and then initializes an array of size n + 1 to accommodate the new value.
  2. It then takes input for the existing elements in the array.
  3. The user is prompted to enter an index and a value to insert.
  4. It checks if the index is valid and shifts elements to the right to make space for the new element.
  5. Finally, the new array is printed with the inserted value.

This problem has been solved

Similar Questions

What is the correct way to declare and initialize a one-dimensional array in C?

The output of the code will be ____. int i=5; printf(“%d %d %d”, i, i++, ++i); in c

Using pointers write a program to swap two numbers using a user definedfunction(Call by reference)

The output of the code will be ____. int i=5; printf(“%d %d %d”, i, i++, ++i); ans. 7 6 5 7 6 6 5 5 7 7 6 7

What is wrong with the following code?int n = 0;int array[5];int i = 3;array[n] = i;

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.