The Wayback Machine - https://web.archive.org/web/20240819102611/https://www.geeksforgeeks.org/c-program-to-insert-an-element-in-an-array/
Open In App

C program to Insert an element in an Array

Last Updated : 12 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.

An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C.

Follow the below steps to solve the problem:

  • First get the element to be inserted, say x
  • Then get the position at which this element is to be inserted, say pos
  • Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.
  • Insert the element x now at the position pos, as this is now empty.

Below is the implementation of the above approach:
 

C




// C Program to Insert an element
// at a specific position in an Array
 
#include <stdio.h>
 
int main()
{
    int arr[100] = { 0 };
    int i, x, pos, n = 10;
 
    // initial array of size 10
    for (i = 0; i < 10; i++)
        arr[i] = i + 1;
 
    // print the original array
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
 
    // element to be inserted
    x = 50;
 
    // position at which element
    // is to be inserted
    pos = 5;
 
    // increase the size by 1
    n++;
 
    // shift elements forward
    for (i = n - 1; i >= pos; i--)
        arr[i] = arr[i - 1];
 
    // insert x at pos
    arr[pos - 1] = x;
 
    // print the updated array
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
 
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 50 5 6 7 8 9 10 

Time Complexity: O(N), Where N is the number of elements in the array
Auxiliary Space: O(1) 



Similar Reads

What’s difference between “array” and “&amp;array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&amp;array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
C program to detect tokens in a C program
As it is known that Lexical Analysis is the first phase of compiler also known as scanner. It converts the input program into a sequence of Tokens. A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.For Example: 1) Keywords: Examples- for, while, if etc. 2) Identifier Exa
5 min read
C program to print a string without any quote (single or double) in the program
Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console. The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it. C/C++ Code // C program to print a string without // quote in the progr
1 min read
Program to print Sum of even and odd elements in an array
Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index positions and 3 odd index positions in an array Even = 1 +
13 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Jagged Array or Array of Arrays in C with Examples
Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}, {5} }; Below are the methods to implement the j
3 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Output of the program | Dereference, Reference, Dereference, Reference....
Predict the output of below program #include&lt;stdio.h&gt; int main() { char *ptr = &quot;geeksforgeeks&quot;; printf(&quot;%c\n&quot;, *&amp;*&amp;*ptr); getchar(); return 0; } Output: g Explanation: The operator * is used for dereferencing and the operator &amp; is used to get the address. These operators cancel effect of each other when used on
1 min read
Quine - A self-reproducing program
A quine is a program which prints a copy of its own as the only output. A quine takes no input. Quines are named after the American mathematician and logician Willard Van Orman Quine (1908–2000). The interesting thing is you are not allowed to use open and then print file of the program. To the best of our knowledge, below is the shortest quine in
1 min read
C Program to list all files and sub-directories in a directory
#include &lt;stdio.h&gt; #include &lt;dirent.h&gt; int main(void) { struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir(&quot;.&quot;); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf(&quot;Could not open current directory&quot; ); return 0; } // Refer http://pu
1 min read
C Program to print contents of file
fopen() is used to open and fclose() is used to close a file in C #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // For exit() int main() { FILE *fptr; char filename[100], c; printf(&quot;Enter the filename to open \n&quot;); scanf(&quot;%s&quot;, filename); // Open file fptr = fopen(filename, &quot;r&quot;); if (fptr == NULL) { printf(&quot;Ca
1 min read
C program to delete a file
The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the &lt;stdio.h&gt; header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
C Program to display hostname and IP address
Method 1: There are many ways to find Hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using C program. We will be using the following functions :- gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieve
3 min read
Program to print hollow rectangle or square star patterns
Hollow rectangle star pattern : The task is print below hollow pattern of given dimension. ******************** * * * * * * * * ******************** Explanation: Input number of rows and columns.For rows of rectangle run the outer loop from 1 to rows.for (i = 1; i &lt; = rows; i++)For column of rectangle run the inner loop from 1 to columns. for (j
4 min read
C program to copy string without using strcpy() function
strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file. We can use the inbuilt strcpy() function to copy one string to another but here, this program copies the content of one string to another manually without using strcpy() function. Methods to Copy String without using
3 min read
LEX program to add line numbers to a given file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Example: Input: #include&lt;stdio.h> // Driver Code int
2 min read
Splint -- A C program verifier
C compiler is pretty vague in many aspects of checking program correctness, particularly in type checking. Careful use of prototyping of functions can assist modern C compilers in this task. However, there is still no guarantee that once you have successfully compiled your program that it will run correctly. The UNIX Lint tool Secure Programming Li
1 min read
Program error signals
Signals in computers are a way of communication between the process and the OS. When a running program undergoes some serious error then the OS sends a signal to the process and the process further may not execute. Some processes may have a signal handler that does some important tasks before the process leaves the CPU. Signal and interrupt are bas
3 min read
Convert C/C++ program to Preprocessor code
We use g++ compiler to turn provided Cpp code into preprocessor code. To see the preprocessor code generated by the CPP compiler, we can use the “-E” option on the command line: Preprocessor include all the # directives in the code. and also expands MACRO function. Syntax: g++ -E filename.cpp // MACRO named MAX initialism to 10 #define MAX 10 int m
1 min read
Program to Print Mirrored Hollow Parallelogram
Given the length as rows and breadth as cols, the task is to print the mirrored hollow parallelogram.Examples: Input: rows = 5, cols = 8 Output: ******** * * * * * * ******** C/C++ Code // CPP program to print hollow mirrored // parallelogram star pattern series #include &lt;iostream&gt; using namespace std; // function for creating pattern void Pa
5 min read
Program to Convert Hexadecimal to Octal
Given a Hexadecimal number, the task is to convert it into an Octal number.Examples: Input: Hexadecimal = 1AC Output: Binary = 0654 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Grouping in terms of 3: 000 110 101 100 Equivalent octal value of 000: 0 Equivalent octal value of 1
15 min read
Lex program to count the number of lines, spaces and tabs
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Let's the how to count the number of lines, spaces and tabs using Lex. Example: Input: Geeks for Geeks gfg gf
1 min read
C Program to count the Number of Characters in a File
Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is
2 min read
C program to count number of vowels and consonants in a String
Given a string and write a C program to count the number of vowels and consonants in this string. Examples: Input: str = "geeks for geeks" Output: Vowels: 5 Consonants: 8 Input: str = "abcdefghijklmnopqrstuvwxyz" Output: Vowels: 5 Consonants: 21Using For LoopsTake the string as inputTake each character from this string to checkIf this character is
4 min read
Structure of the C Program
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program. Sections of the C Program There are 6 basic sections resp
5 min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
Program to print half Diamond star pattern
Given an integer N, the task is to print half-diamond-star pattern. ************************************ Examples: Input: N = 3 Output: * ** *** ** * Input: N = 6 Output: * ** *** **** ***** ****** ***** **** *** ** * Approach: The idea is to break the pattern into two halves that is upper half and lower half. Then print them separately with the he
4 min read
C Program to sort rows of the Matrix
Given a matrix arr[][] of dimensions N * M, the task is to sort the matrix such that each row is sorted and the first element of each row is greater than or equal to the last element of the previous row. Examples: Input: N = 3, M = 3, arr[][] = {{7, 8, 9}, {5, 6, 4}, {3, 1, 2}}Output:1 2 34 5 67 8 9 Approach: Follow the steps below to solve the pro
3 min read
Article Tags :
three90RightbarBannerImg