1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[C] Play Again Loop Logic

Discussion in 'C' started by anubizs, Jun 11, 2015.

  1. anubizs

    anubizs New Member

    Joined:
    Jun 11, 2015
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I made a basic calculator using this codes. What i want to learn is how to make a loop after the program ask "try again y/n"? it will return to choose an operation.


    Code:
    #include<stdio.h>
    #include<conio.h>
    
    
    
    int main(){
    int num1, num2, choice;
    
    printf("Choose an operation\n\n");
    printf("[1] Add\n[2] Subtract\n[3] Multiply\n[4] Divide\n[5] Exit\n");
    scanf("%d", &choice);
    
    switch(choice){
        
        case 1:
            printf("Enter 1st number:\n");
            scanf("%d", &num1);
            printf("Enter 2nd number:\n");
            scanf("%d", &num2);
            printf("\n%d", (num1+num2));
            break;
        case 2:
            printf("Enter 1st number:\n");
            scanf("%d", &num1);
            printf("Enter 2nd number:\n");
            scanf("%d", &num2);
            printf("\n%d ", (num1-num2));
            break;
        case 3:
            printf("Enter 1st number:\n");
            scanf("%d", &num1);
            printf("Enter 2nd number:\n");
            scanf("%d", &num2);
            printf("\n%d", (num1*num2));
            break;
        case 4:
            printf("Enter 1st number:\n");
            scanf("\n%d", &num1);
            printf("Enter 2nd number:\n");
            scanf("%d", &num2);
            printf("\n%d", (num1/num2));
            break;
        case 5:
             return 0;
            
        default:
            printf("That is not a valid choice.");
            break;
    }
    getch();
    }
    
    
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    I would just enclose the lot in a for loop:
    Code:
    for (int quit=0; !quit; )
    {
    printf("Choose an operation\n\n");
    //...
    case 5: quit=1; break;
    //...
    }
    
     
    shabbir likes this.

Share This Page