C Programming Tutorial - if else






Hey guys,

here I'm going to talk about if else statement. This can be applied when we have only two possibilities. The following code is from previous example, here I explained how to give an output depending on user's input where user only had 2 choices. Here we are going to see how we can change it into if else statement.

The code from previous article.

#include<stdio.h>

int main() {
int age;
char gender;
printf("How old are you?\n");
scanf(" %d", &age);

printf("What is your gender? (m/f) \n");
scanf(" %c", &gender);


if(age >=18) {
    printf ("You may enter this website!");
   
    if(gender == 'm') {
        printf(" dude");
    }
    if(gender == 'f') {
        printf(" m'lady");
       
    }
}
if (age<18){
    printf("Nohing to see here!");
}

}


Here we had two choices for gender and age therefore we can use if else statement for both. First lets look at the code when we turn age into an if else statement.



#include<stdio.h>



int main() {

int age;

char gender;

printf("How old are you?\n");

scanf(" %d", &age);



printf("What is your gender? (m/f) \n");

scanf(" %c", &gender);





if(age >=18) {

    printf ("You may enter this website!");

   

    if(gender == 'm') {

        printf(" dude");

    }

    if(gender == 'f') {

        printf(" m'lady");

       

    }

} else { 
    printf("Nohing to see here!"); 
}


}


Second, lets look at the code where we change gender into an if else statement. 



#include<stdio.h>



int main() {

int age;

char gender;

printf("How old are you?\n");

scanf(" %d", &age);



printf("What is your gender? (m/f) \n");

scanf(" %c", &gender);





if(age >=18) {

    printf ("You may enter this website!");

   

    if(gender == 'm') {

        printf(" dude");

    } else {
  

        printf(" m'lady");

    

       

    }

} else { 
    printf("Nohing to see here!"); 
}


}

Hope this helps thanks for reading :). 

Comments