Deleting an array element in C

后端 未结 7 1802
自闭症患者
自闭症患者 2021-01-06 14:51

I wrote the following program to delete an array element entered by the user.

#include 
#include 

void main() {
    int j, i,          


        
7条回答
  •  -上瘾入骨i
    2021-01-06 15:06

    Your method with 2 nested for loops is too complicated. You can simple scan the array with an index i and copy all elements different from key with a different index len. The resulting array length is the final value of len.

    Here is a modified version:

    #include 
    #include 
    
    int main(void) {
        int a[100];
        int i, n, key, len;
    
        clrscr();
        printf("Enter the number of elements: ");
        if (scanf("%d", &n) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (n < 0 || n > 100) {
            printf("invalid number of elements\n");
            return 1;
        }
        printf("\nEnter the elements:\n");
        for (i = 0; i < n; i++) {
            if (scanf("%d", &a[i]) != 1) {
                printf("invalid input\n");
                return 1;
            }
        }
        printf("\nEnter the element to delete: ");
        if (scanf("%d", &key) != 1) {
            printf("invalid input\n");
            return 1;
        }
    
        for (i = len = 0; i < n; i++) {
            if (a[i] != key)
               a[len++] = a[i];
        }
    
        printf("\nThe new array is:\n");
        for (i = 0; i < len; i++)
            printf("%d ", a[i]);
        printf("\n");
        getch();
        return 0;
    }
    

    Notes:

    • The prototype for main without arguments is int main(void) and it is considered good style to return 0 for success.

    • always test the return value of scanf(). This prevents many bugs and undefined behavior for invalid input. It also saves a lot of time looking in the wrong places when input was just invalid.

    • avoid naming a variable l as it looks too close to 1 in many fixed pitch fonts.

    • always terminate the program output with a newline.

提交回复
热议问题