Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't understand the output of this code

#include<stdio.h>
int main()
{
    int a=1,i;
    for(i=0;i<3;i++)
        switch((++a)-1)
    {
        case 0:printf("\nzero");
        case 1:printf("%d.one",i+1);
        case 2:if(i%2==0)
                 printf("\n\t%d.Two",i+1);
                 else
                    printf("\n%d.Two",i+1);
        default:printf("\t%d.step",i+1);
    }

}

it’s oustput is:

1.one
        1.Two   1.step
2.Two   2.step  3.step

I can’t understand why there are six output where it should be three I guess.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because without a break; statement, each case will continue into the next one.

    switch((++a)-1)
    {
        case 0:printf("\nzero");       // Without a break;, the next line gets executed as well!

        case 1:printf("%d.one",i+1);   // Execution continues here, printing "%d.one", even though we are in case 0 
        case 2:if(i%2==0)
               {
                   printf("\n\t%d.Two",i+1);
               }
               else
               {
                   printf("\n%d.Two",i+1);
               }                       // The default will get run as well, for lack of a "break;"

        default:printf("\t%d.step",i+1);
    }

This should be properly written as:

switch((++a)-1)
{
    case 0:
        printf("\nzero");
        break;
        
    case 1:
        printf("%d.one",i+1);
        break;

    case 2:
        if(i%2==0)
        {
            printf("\n\t%d.Two",i+1);
        }
        else
        {
            printf("\n%d.Two",i+1);
        }
        break;

    default:
        printf("\t%d.step",i+1);
        break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading