I want to assign an output to a menu made with a switch

1

I want option 5 to leave the menu

this is the code

#include<stdio.h>
int a,n,i,j=0,k=0;
int A [100];
int B [100];
int C [100];
int opc;
int main() {
    do {
        do {
            printf("Selecciona una opcion: \n\n");
            printf("1.- Agregar elementos: \n");
            printf("2.- Ver arreglo: \n");
            printf("3.- Ver elementos pares: \n");
            printf("4.- Ver elementos impares: \n");
            printf("5.- Salir\n");
            scanf("%d", &opc);
            fflush(stdin);
        }while(opc<=0 || opc>5);


        switch(opc) {
        case 1:

            printf("\nCuantos elementos quieres en el arreglo? ");
            scanf("%d",&n);

        for (i=0; i<n;i++) {
            printf("\nIntroduce [%d]",i+1);
            scanf("%d",&A[i]);
            fflush(stdin);

    }

    break;
    case 2:
        for (i=0; i<n;i++) {
        printf("%d, ",A[i]);
    }

    break;
case 3:
        printf("\nPARES: ");

        for (i=0; i<n;i++) {
            if(A[i]%2==0){

            B[j]=A[i];
            j++;
            }

    }for (i=0; i<j;i++){
        printf("%d\t",B[i]);
    }


    break;
    case 4:printf("\nIMPARES: ");
        for (i=0; i<n;i++) {
            if(A[i]%2!=0){

            C[k]=A[i];
            k++;
            }

    }for (i=0; i<k;i++){
        printf("%d\t",C[i]);
    }


        break;



        case 5:
    return 0;
    break;
    default:
}   






}while(n!=5);





    return 0;
}
    
asked by TysonGolovkin 06.10.2017 в 07:27
source

1 answer

1

The part that interests us about the code is this:

do {
  switch(opc) {
    case 5:
      return 0;
      break;
  }
} while(n!=5);

The main loop is configured so that it is abandoned if n==5 ... but the option chosen from the menu is saving it in opc . The correct thing would be then:

}while(opc != 5);

With this, all you have to do then is eliminate the return 0 .

do {
  switch(opc) {
    case 5:
      break;
  }
} while(opc!=5);

With return 0 what you get is to leave the main directly ... for your particular case the result will be the same but the way forward is different.

I suggest dividing the code into functions to make it easier to manage ... and, please, avoid the use of global variables.

    
answered by 06.10.2017 в 07:46