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

If else not read third condition in C

I’ve task named ”Discounted Coffee Machine” and i do it conditions like

if(p<a){
        printf("\nYour balance is not enough.");
        printf("\nRemaining balance: %d",p);
        }
else if(p>=a && dis!=dis2){
        printf("\nEnjoy your Latte. ");
        printf("\nRemaining balance: %d",p-a);
        }
        
else if(p>=a && dis==dis2){
        printf("\nThe discount has been applied.\nEnjoy your Latte.");
        printf("\nRemaining balance: %f",(float)p-(float)a*0.9);
        }

but if i will enter correct discount code didn’t read second else if it read first else if how can i solve ?

i try with second else if like only else but it’s not working also i tried with ‘,’ and ‘||’.

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 :

dis and dis2 are character arrays

 char dis[]="ostim"; 
 char dis2[5];

dis!=dis2 compares the addresses of those 2 different arrays and so dis!=dis2 is always true. Code needs to compare the strings at those addresses. @Chris Dodd
Use strcmp() which returns 0 when the strings are the same.

Replace dis!=dis2 with strcmp(dis, dis2) != 0 or simply

// else if(p>=a && dis!=dis2){
else if(p>=a && strcmp(dis, dis2)) {

Likewise for else if(p>=a && dis==dis2).

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