C Conditional Statements

As we know that c program executes step by step. But sometimes we have some condition-based statements that time we need to perform or execute a condition-based statement. If, else and switch are conditional statements in c.

Syntax


if (condition) { //true condition case 
  // statement
} else { //else condition case 
  // statement
}

Let us take an example, suppose that you want to print the number when the number is even then you need if block in your code.


int num = 13;
int isEven = (num % 2 == 0);

if (isEven) { // only print if number is even 
  printf("%d is Even number.", num); // 12 is Even number. 
}

But if you want to find the number is odd or event then you need an else block also.


int num = 13;
int isEven = (num % 2 == 0);

if (isEven) { // only print if number is even 
  printf("%d is Even number.", num); // 12 is Even number. 
} else {
   printf("%d is Odd number.", num); // 12 is Odd number. 	
}

Switch statement

C “switch” does fall through. It’ll jump to a matching point and run all of the rest of the case code without testing.


// switch
int msgid = 1;
    
switch (msgid) {
  case 1:
    printf("Message-id is 1\n");
  case 2:
    printf("Message-id is 2\n");
  default:
    printf("Message-id is the default\n");
}

/*
Message-id is 1
Message-id is 2
Message-id is the default
*/

You can see our output is default block because in this can your all cases executed and your last case replaced all the values of msg.


// switch
int msgid = 1;
    
switch (msgid) {
  case 1:
    printf("Message-id is 1\n");
  case 2:
    printf("Message-id is 2\n");
  default:
    printf("Message-id is the default\n");
}

/*
Message-id is 1
*/

else-if ladder

The above case can also handle by an else-if ladder.


// switch
int msgid = 5;
    
if (msgid == 1) {
  printf("Message-id is 1\n");
} else if (msgid == 2) {
  printf("Message-id is 2\n");
} else {
  printf("Message-id is the default\n");
}
/*
Message-id is the default
*/

Nesting of if…else

if..else also support nesting.


// biggest number from three numbers.
int num1 = 5, num2 = 8, num3 = 13, max;
    
if (num1 > num2) {

  if (num1 > num3) {
    max = num1;
  } else {
    max = num2;
  }
} else {

  if (num2 > num3) {
    max = num2;
  } else {
    max = num3;
  }
}

printf("%d is the max number", max);
/*
13 is the max number
*/

You May Also Like

About the Author: Pankaj Bisht