C else-if Statements

C else-if Statements

Else if statement in c programming; In this tutorial, you will learn everything about else if statements in C programming with examples.

C else-if Statements

In c programming else-if ladder is used to decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed

Syntax of C else-if Statements

The syntax of the else-if Statements in c programming; as shown below:

if (test expression1) {
   // statement(s)
}
else if(test expression2) {
   // statement(s)
}
else if (test expression3) {
   // statement(s)
}
.
.
else {
   // statement(s)
}

Example 1 – C else-if Statements

See the following c program else-if Statements; as shown below:

// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);

    //checks if the two integers are equal.
    if(number1 == number2) {
        printf("Result: %d = %d",number1,number2);
    }

    //checks if number1 is greater than number2.
    else if (number1 > number2) {
        printf("Result: %d > %d", number1, number2);
    }

    //checks if both test expressions are false
    else {
        printf("Result: %d < %d",number1, number2);
    }

    return 0;
}

Output of the above c program

Enter two integers: 12
23
Result: 12 < 23

Example 2 – C else-if Statements

See the second c program for else if statement; as shown below:

#include <stdio.h>
int main()
{
   int var1, var2;
   printf("Input the value of var1:");
   scanf("%d", &var1);
   printf("Input the value of var2:");
   scanf("%d",&var2);
   if (var1 !=var2)
   {
	printf("var1 is not equal to var2\n");
   }
   else if (var1 > var2)
   {
	printf("var1 is greater than var2\n");
   }
   else if (var2 > var1)
   {
	printf("var2 is greater than var1\n");
   }
   else
   {
	printf("var1 is equal to var2\n");
   }
   return 0;
}

Output of the above c program

Input the value of var1:12
Input the value of var2:21
var1 is not equal to var2

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *