Monday, December 27, 2010

deleting an element from array using index

/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/

/**
* program for scannign n numbers and deleting an element from that
* using index
*/

#include<stdio.h>
void main()
{


int
n = 0 , i =0 ;

int
no[100];
char
c; // to ask the user whether he wants to continue or noe
int delindex= -1 ; // to store the index no at which the user wants to delete

printf("How many numbers you want to scan ? ");
scanf("%d",&n);
if
(n < 0 || n>100)
{


// if the user enters invalid no of elemtns then we come here
printf("Invalid number. It must be brtween 1 to 100");
}

else

{

// logic for scanning the numbers
for(i = 0 ; i < n ;i++)
{


printf("Enter element %d: ", i);
scanf("%d",&no[i]);
}


c = 'y';
do

{

printf("\nEnter the index no from which you want to delete: ");

scanf("%d",&delindex);

// for error checking
if(delindex < 0 || delindex >= n)
{


printf("Invalid number");
}

else

{

// we come here if the index is in valid range



// the logic for moving the elements
for(i = delindex ; i < n ;i++)
{

// move the elements by one

no[i] = no [i+1];
}


// n-- because one element is delted from it

n--;


printf("\nAfter delting the element at %d the array is:\n", delindex ) ;
// now print the array after deleting the number
for(i = 0 ; i < n ;i++)
{


printf("\nElement at index %d is : %d", i, no[i]);
}



// ask the user whether he/she wants to continue or not
printf("\nDO you want to continue ? (y/n) : ");

fflush(stdin);
scanf("%c",&c);
}
}

while
(c!='n' && c != 'N' );
}


printf("\n");
}

No comments:

Post a Comment