Difference in output of program in c for scanning character value due to space .(In Dev c++)

43 Views Asked by At

Problem: space role in nested switch

Even if i is char, why does code work?

After making i an int min file is formed i.e. no output.

Here my program goes:

#include <stdio.h> 

int main() {
    char num, i, choice;
    int fact, f = 1;
    int n1, n2, n3;
    int c1, c2, calsum;

    printf("Enter the operation you want to perform:\n 1.Factorial\n 2.Calculator\n 3.Greater of three\n 4.Fibonacci series\n 5.Star Pattern\n");
    scanf("%c", &num);

    switch (num) {
        case '1':
            //Factorial
            printf("Enter the number to find factorial of :\n");
            scanf("%d", &fact);

            for (i = 1; i <= fact; i++) {
                f = f * i;
            }

            printf("Factorial of %d is %d", fact, f);
            break;

        case '2':
            //Calculator
            printf("Enter your choice:\n a.Addition\n b.Subtraction\n c.Multiplication\n d.Division\n");
            scanf("%c",&choice);
            printf("Enter two numbers:");
            scanf("%d%d", &c1, &c2);

            switch (choice) {
                    case 'a':
                        //Addition
                        calsum = c1 + c2;

                        printf("Addition is %d",calsum);
            }
            break;

        case '3': 
            //Find greatest NO.
            printf("Enter three numbers :");
            scanf("%d%d%d",&n1,&n2,&n3);

            if (n1 > n2 && n1 > n3) {
                printf("%d is greatest", n1);
            }
            else if (n2 > n1 && n2 > n3) {
                printf("%d IS GREATEST", n2);
            }
            else {
                printf("%d is greatest", n3);
            }
            break;

        default: printf("Exit");
            break;
    }
    return 0;
}

I'm linking the output of my program:

  1. With space before %c and
  2. Without space.

enter image description here

Description:

While scanning the choice character when space is given before %c, the scanning operation is performed. While without space the scanning is skipped and display further statements.

0

There are 0 best solutions below