0

//IT DESCRIBES WORKING OF SWITCH STATEMENT.


int main()
{   
    char c;
    int num,i,fact ;
    while(1)
    {   
        printf("CHOOSE f,p,o,e\n");
        scanf("%c",&c);
        if (c =='e')
            break;
        switch(c)
        {
            case 'f':
                printf("Enter num to calculate factorial\n");
                scanf("%d",&num);
                fact = 1;
                for (int i = 1 ; i <= num ; i++ )
                    fact = fact*i;
                printf("factorial is %d\n",fact);
                break;  
            case 'p':
                printf("Enter a number to ckeck if prime\n");
                scanf("%d",&num);
                for( i = 1 ; i < num ; i++)
                {
                    if(num/i == 0 && i != num){
                        printf("NOT A PRIME\n");
                        break;
                        }
                    else
                        continue;
                }
                if(i == num)
                    printf("IS PRIME\n");
                break;          
            case 'o':
                printf("Enter a number to check if O/E\n");
                scanf("%d",&num);
                if(num%2 == 0)
                    printf("IS EVEN\n");
                else
                    printf("IS ODD\n");
                break;          
        }
        printf("RAN a TIME\n");
    }
}

When I run this code , output is -
CHOOSE f,p,o,e
f
Enter num to calculate factorial
5
factorial is 120
RAN A TIME
CHOOSE f,p,o,e
RAN A TIME
CHOOSE f,p,o,e .

Why it is printing two times after I choose a character and ouput is shown?

v7676
  • 31
  • 2
  • When you type the `` that is considered a character by `scanf("%c")` ... maybe filter it out: `do scanf("%c", &c); while ((c == '\n') || (c == '\r'));` – pmg Oct 10 '20 at 10:07
  • Change `scanf("%c",&c);` to `scanf(" %c",&c);` (note the added space). Its job is to filter whitespace characters, such as the newline left in the buffer after `scanf("%d",&num);` The `%d` automatically filters whitespace. The `%c` does not. – Weather Vane Oct 10 '20 at 10:16

0 Answers0