I am still a beginner in C and am currently having trouble with if and else statements.
I kept getting an element in the array deleted despite the input not being found in that array.
The output:
Before deletion:
B D Z X W M O S P H G E
Input your letter to delete:
A
Letter to delete: A
Element A is not found in the array
Array Content:
B D Z X W M O S P H G
Instead of the desired output
Before deletion:
B D Z X W M O S P H G E
Input your letter to delete:
A
Letter to delete: A
Element A is not found in the array
Array Content:
B D Z X W M O S P H G E
I have tried to change for (i = 0; i < size-1; i++) into for (i = 0; i < size; i++) in else statement but the printf would only show the original array. I also tried to construct printf for the original array but both the original array and the misleading array content will print in the output. I need to know how to handle the error. Please teach me how.
#include <stdio.h>
int main() {
{
char letters[12] = {"BDZXWMOSPHGE"};
char toDelete, found;
int i, pos, ch;
printf("Before deletion:\n");
for (int i = 0;i<12;i++) {
printf("%c ", letters[i]);
}
printf("\nInput your letter to delete: \n");
scanf(" %c", &toDelete);
found=0;
printf("\nLetter to delete: %c\n", toDelete);
for (i=0; i < 12; i++) {
if(letters[i] == toDelete)
{
found = 1;
pos = i;
break;
}
}
if(found == 1) {
for(i = pos; i < 12; i++)
letters[i] = letters[i+1];
}
else
printf("\n\nElement %c is not found in the array\n\n", toDelete);
printf("\nArray Content:\n");
for(i = 0; i < 12; i++)
printf("%c ", letters[i]);
}
return;
}
You have my gratitude. Feel free to leave tips on how to improve this even more.
Aucun commentaire:
Enregistrer un commentaire