All for Joomla All for Webmasters

C if else Statement

The if statement in C language is used to perform operation on the basis of condition. By using if-else statement, you can perform operation either condition is true or false.

There are many ways to use if statement in C language:

  • If statement
  • If-else statement
  • If else-if ladder
  • Nested if

If Statement

The single if statement in C language is used to execute the code if condition is true. The syntax of if statement is given below:

  1. if(expression){
  2. //code to be executed
  3. }

Let’s see a simple example of c language if statement.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main(){
  4. int number=0;
  5. clrscr();
  6. printf(“enter a number:”);
  7. scanf(“%d”,&number);
  8. if(number%2==0){
  9. printf(“%d is even number”,number);
  10. }
  11. getch();
  12. }

Output

enter a number:4
4 is even number
enter a number:5

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){
  2. //code to be executed if condition is true
  3. }else{
  4. //code to be executed if condition is false
  5. }

Let’s see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main(){
  4. int number=0;
  5. clrscr();
  6. printf(“enter a number:”);
  7. scanf(“%d”,&number);
  8. if(number%2==0){
  9. printf(“%d is even number”,number);
  10. }
  11. else{
  12. printf(“%d is odd number”,number);
  13. }
  14. getch();
  15. }

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){
  2. //code to be executed if condition1 is true
  3. }else if(condition2){
  4. //code to be executed if condition2 is true
  5. }
  6. else if(condition3){
  7. //code to be executed if condition3 is true
  8. }
  9. else{
  10. //code to be executed if all the conditions are false
  11. }

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main(){
  4. int number=0;
  5. clrscr();
  6. printf(“enter a number:”);
  7. scanf(“%d”,&number);
  8. if(number==10){
  9. printf(“number is equals to 10”);
  10. }
  11. else if(number==50){
  12. printf(“number is equal to 50”);
  13. }
  14. else if(number==100){
  15. printf(“number is equal to 100”);
  16. }
  17. else{
  18. printf(“number is not equal to 10, 50 or 100”);
  19. }
  20. getch();
  21. }

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
PinIt
submit to reddit

Leave a Reply

Top