I have this program where it lets the user input an array of numbers.
For example, I would input an array size of 4 and input the numbers 40, 20, 1, and 8 as the elements in the array.
Input array size: 4
Input array elements: 40 20 1 8
The program also lets the user delete any elements from the array and the output should also show the element that was deleted.
For example, I would delete the number 40 from the elements. The output should be like this:
Enter the position of the element that you would like to delete: 1
The element 40 is completely deleted!
But instead of showing 40, the output goes like this:
Enter the position of the element that you would like to delete: 1
The element 20 is completely deleted!
Here is my source code:
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i )
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition];
if (elementPosition >= arraySize 1)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition; i < arraySize - 1; i )
{
a[i] = a[i 1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}
It would be a very big help if someone can point out where did I go wrong.
CodePudding user response:
Array index starts from 0. This deletedElement = a[elementPosition]; should be changed to deletedElement = a[elementPosition - 1];.
Additionally, you need to make sure that subtracting 1 does not cause deletedElement to become less than 0.
CodePudding user response:
Could you test it, the index begin from 0 the position from 1.
int a[100];
int arraySize, elementPosition;
printf("\n Input Array Size: ");
scanf("%d", &arraySize);
printf("\n Input Array Elements: ");
for(i = 0; i < arraySize; i )
{
scanf("%d, ", &a[i]);
}
printf("\n Enter the position of the element you would like to delete: ");
scanf("%d", &elementPosition);
int deletedElement = a[elementPosition - 1 ];
if (elementPosition >= arraySize)
{
printf("\n \n \t Invalid position! Enter numbers from 1 to %d only.\n", arraySize);
getch();
del();
}
else
{
for (i = elementPosition - 1; i < arraySize - 2; i )
{
a[i] = a[i 1];
}
printf("\n \The element %d is completely deleted!", deletedElement);
arraySize = arraySize - 1;
getch();
}
