HIDE NAV

C If Else and Else-If

A demostration of some common uses for if else and else-if branching.

if_else.c


#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int a = 4;
	int b = -1;
	int c = -25;

	// if,else-if chain using equal comparisons.
	// Note that only one of the below branches will execute.
	if (a == 2){
		printf("This is the branch for value of a = 2.\n");
	}else if (a == 3) {
		printf("This is the branch for value of a = 3.\n");
	}else if (a == 3) {
		printf("This is the branch for value of a = 4.\n");
	}else{
		printf("This is the branch for all other values of a.\n");
	}

	// combining comparisons with AND logic
	printf("Checking if %d is between 2 and 8...\n", b);
	if ( (b > 2) && (b < 8) ) {
		printf("True, %d is between 2 and 8\n", b);
	} else {
		printf("False, %d is NOT between 2 and 8\n", b);
	}

	// combining comparisons with OR logic
	printf("Checking if %d has absolute value greater than 5...\n", c);
	if ( (c < -5) || (c > 5)) {
		printf("True, %d has absolute value greater than 5.\n", c);
	} else {
		printf("False, %d has absolute value smaller than 5.\n", c);
	}

	// Not equal comparison
	if (a != b) printf("%d is not equal to %d\n", a, b);

	// Negation of a compound comparison
	if ( !((a == b) && (a == c)) ) printf("%d, %d and %d are not all three the same value\n", a, b, c);

	return EXIT_SUCCESS;
}