C program to replace an element in an array with its position

In these example we will learn how to replace or insert new element in an array. 

Ex: Write a C program to replace an element in an array with its position, How to write a C program to replace an element from array, C program to insert and replace element from array.



  Program to replace an element in an array with its position:


#include<stdio.h>
void main()
{
 //Declare array of size 100
 int a[100];
 int i,num,key,pos;
 
 printf("Enter how many elements you want to insert:\n");
 scanf("%d",&key);
 
 
 printf("Enter the elements: \n");
 for(i=0;i<key;i++)
 scanf("%d",&a[i]);
 
 
 printf("Elements in array are:\n");
 for(i=0;i<key;i++)
 printf("%d ",a[i]);
 
 
 printf("\n\nEnter which new element you want to insert: \n");
 scanf("%d",&num);
 
 //Accept position to insert new element
 printf("\nEnter the position to insert new element: \n");
 scanf("%d",&pos);
 
 
 for(i=0;i<key;i++)
 {
  if(i+1==pos)
  {
   a[pos-1]=num;
  }
 }
 
 //Print Output
 printf("Final Output: \n");
 for(i=0;i<key;i++)
 printf("%d ",a[i]);
 

}


Above program will show the following Output:

Enter how many elements you want to insert: 5

Enter the elements:
1
2
3
6
5

Elements in array are:
1 2 3 6 5

Enter which new element you want to insert: 4

Enter the position to insert new element: 4

Final Output: 
1 2 3 4 5




Learn more array examples and other C programming exercises from menu 'C' Exercises option...😉

No comments:

Post a Comment

If you have any doubts, please discuss here...👇