使用循环和switch语句

时间:2017-05-17 13:45:10

标签: c arrays

此程序有多种选项可供选择,例如 1.add元素到数组
2.搜索元素
3.删除元素
我只展示一个案例,因为其他案件无关紧要。这里1'st循环适用于所有选项,但是对于第二次迭代我不能添加新元素,它总是说“元素添加成功”

int k = 0, found = 0;
//k counts the total elements in the list
while(1){
    switch (choice)
    {
      case 1 :

            printf("Enter the number : ");
            scanf("%d", &num);
            for(i=0; i<=k; i++){
              if(num == number[i]){
                found=1;
                printf("Element already added. Please try again\n");
                break;
              }
            }
            if(found == 0){
              number[k]=num;
              k = k+1;
              printf("Element added successfully\n");
              found = 0;
            }

    break;
    }

}

1 个答案:

答案 0 :(得分:2)

添加第一个元素后,found始终为1。在下一次迭代之前将found重置为0