How to operate on Array?
You can do following operations on Array.
- Insertion
- Deletion
- Searching
- Sorting
Suppose we have entered 5 elements 10,20,40,50,60 in an array.
And we want to insert one more element 30 at specific position let 3rd i.e. at x[2].
Then we'll have to shift each element from last position to the specific position one by one.
Now,Enter the element at specified position,
Code:
#include<stdio.h> void main() { int x[7]={10,20,40,50,60}; int i,n=5; int ele,pos; for(i=0;i<n;i++) printf("\n%d",x[i]); printf("\nEnter the element to be inserted"); scanf("%d",&ele); printf("\nEnter its position"); scanf("%d",&pos); pos--; for(i=n-1;i>=pos;i--) { x[i+1]=x[i]; } x[pos]=ele; if(pos>n) { printf("\nInsertion outside array"); } n++; printf("\nList of elements after insertion operation"); for(i=0;i<n;i++) { printf("\n%d",x[i]); } getch(); }
Output:
Deletion operation from 1-D array:-
Suppose we have entered 6 elements 10,20,99,30,40,50 in an array.Then we'll have to shift each element from specific position to the last position one by one.
Code:
#include<stdio.h> void main() { int x[7]={10,20,99,30,40,50}; int i,n=6; int ele,pos; for(i=0;i<n;i++) printf("\n%d",x[i]); printf("\nEnter the position of element to delete "); scanf("%d",&pos); pos--; for(i=pos;i<n;i++) { x[i]=x[i+1]; } if(pos>n) { printf("\nDeletion outside array"); } n--; printf("\nList of elements after deletion operation"); for(i=0;i<n;i++) { printf("\n%d",x[i]); } getch(); }
Output:
Different searching and sorting techniques have been discussed in separate posts.












No comments:
Post a Comment