Pages

Branching


C language executes program statements in a sequence. Sometimes we need to alter the flow of sequence of statements. This is possible using Branching statements offered by C language. They are also known as control statements. Programmer can jump from one part of the program to other with the help of such statements. 

Branching Statements in C:
  • if statement: Executes a block of code if a condition is true.
  • else statement: Executes a block of code if the condition in the if statement is false.
  • switch statement: Selects one of multiple blocks of code to execute based on the value of an expression.

Key Concepts to learn:
  • Boolean expressions: Evaluate to either true (non-zero) or false (zero).
  • Control flow: The order in which statements are executed.
  • Nested statements: Placing one statement inside another.

Followings are broad categories of C language Branching Statements:

1. if statement
2. if…else statement
3. nested if statement
4. switch statement


Let’s learn branching statement by executing following programs.


Programs based on if statement

Programs based on if…else statement

Programs based on nested if statement

Programs based on switch statement


Sample Programs



#include<stdio.h>
int main()
{
 int number;

 printf("Enter number:");
 scanf("%d",&number);

 if(number%2 == 0)
  printf("Entered number is even.");
 else
  printf("Entered number is odd.");
 return 0;
}
/* Sample Output
Enter number:5
Entered number is odd.
*/



#include<stdio.h>
void main ()
{
 int number;
 printf("Enter your number:");
 scanf("%d",&number);
 switch(number)
 {
  case 1 :printf("One");
             break;
  case 2 :printf("Two");
             break;
  case 3 :printf("Three");
             break;
  case 4 :printf("Four");
             break;
  case 5 :printf("Five");
             break;
  default :printf("Invalid number\n" );
 }
}
/*Output
Enter your number:5
Five
*/




#include<stdio.h>
void main()
{
  int number;

  printf("Enter number:");
  scanf("%d",&number);

  if(number > 0)
      printf("Number is positive.");
  else
      printf("Number is not positive.");
}
/*Output
Enter number:11
Number is positive.
*/


2 comments:

  1. Replies
    1. Contact me with your offer through Contact us page of the blog.

      Delete