/****************************
* 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");
}
Showing posts with label array. Show all posts
Showing posts with label array. Show all posts
Monday, December 27, 2010
deleting an element from array using index
Labels:
array,
C program,
D.S,
data structure,
delete element,
delete element using idex,
DS,
using index
sorting array in descending order
/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/
/**
* program for scannign n numbers and sorting them in descending order
*/
#include<stdio.h>
void main()
{
int n = 0 , i =0 , j = 0;
int no[100];
int temp; // for swapping the number
printf("How many numbers you want to scan ? ");
scanf("%d",&n);
if(n < 0 || n>100)
{
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]);
}
// the logic for sorting the numbers
for(i = 0 ; i < n ;i++)
{
for(j = 0 ; j < n ; j++ )
{
if(no[i] > no[j])
{
// if the number at index i is greater than the number at index j then swap the numbers
temp = no[i];
no[i] = no[j];
no[j] = temp;
}
}
}
for(i = 0 ; i < n ;i++)
{
printf("\nnumber at index %d is %d ", i , no[i]);
}
}
printf("\n");
}
Labels:
array,
C program,
D.S,
data structure,
descending,
DS,
sort in ascending,
sort in descending
Subscribe to:
Posts (Atom)