Removal of an element from the array (C Language)
plkraz
-
M3NSONG3 Posted messages 670 Status Membre -
M3NSONG3 Posted messages 670 Status Membre -
Hello
I can't understand the part in bold
#include<stdio.h>
#include<stdlib.h>
int main()
{
int t[100];
int i,j,n,a;
printf("Enter the number of elements in the array:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d:\t",i+1);
scanf("%d",&t[i]);
}
for(i=0;i<n;i++)
printf("%d ",t[i]);
printf("\n");
printf("Enter the element to delete from the array:\n");
scanf("%d",&a);
for(i=0;i<n;i++)
{
if(t[i]==a)
{
for(j=i;j<n-1;j++)
t[j]=t[j+1];
n--;
i--;
}
}
for(i=0;i<n;i++)
printf("%d ",t[i]);
printf("\n");
system("pause");
return 0;
}
what is its purpose?
thank you
I can't understand the part in bold
#include<stdio.h>
#include<stdlib.h>
int main()
{
int t[100];
int i,j,n,a;
printf("Enter the number of elements in the array:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d:\t",i+1);
scanf("%d",&t[i]);
}
for(i=0;i<n;i++)
printf("%d ",t[i]);
printf("\n");
printf("Enter the element to delete from the array:\n");
scanf("%d",&a);
for(i=0;i<n;i++)
{
if(t[i]==a)
{
for(j=i;j<n-1;j++)
t[j]=t[j+1];
n--;
i--;
}
}
for(i=0;i<n;i++)
printf("%d ",t[i]);
printf("\n");
system("pause");
return 0;
}
what is its purpose?
thank you
1 réponse
Hi!
Next time, try to indent your code and use the appropriate tag for... Once the code is indented, everything becomes much clearer:
To answer your question, the part you highlighted literally looks for your value, and once it finds it, it shifts all the subsequent values one position back (which effectively removes your value).
It then updates i and n with one less element for the following display.
Next time, try to indent your code and use the appropriate tag for... Once the code is indented, everything becomes much clearer:
#include<stdio.h> #include<stdlib.h> int main() { int t[100]; int i,j,n,a; printf("Enter the number of elements in the array:\n"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter element %d:\t",i+1); scanf("%d",&t[i]); } for(i=0;i<n;i++) printf("%d ",t[i]); printf("\n"); printf("Enter the element to remove from the array:\n"); scanf("%d",&a); for(i=0;i<n;i++) { if(t[i]==a) { for(j=i;j<n-1;j++) t[j]=t[j+1]; n--; i--; } } for(i=0;i<n;i++) printf("%d ",t[i]); printf("\n"); system("pause"); return 0; } To answer your question, the part you highlighted literally looks for your value, and once it finds it, it shifts all the subsequent values one position back (which effectively removes your value).
It then updates i and n with one less element for the following display.