Computer >> Máy Tính >  >> Lập trình >> lập trình C

Giải thích câu lệnh if-else lồng nhau bằng ngôn ngữ C

Một ‘if lồng nhau’ là một câu lệnh if là đối tượng của if (hoặc) một else. ‘If’ được đặt bên trong if (hoặc) khác.

Cú pháp

Tham khảo cú pháp đưa ra bên dưới -

if (condition1){
   if (condition2)
      stmt1;
   else
      stmt2;
}
else{
   if (condition3)
      stmt3;
   else
      stmt4;
}

Giải thích câu lệnh if-else lồng nhau bằng ngôn ngữ C

Ví dụ

Dưới đây là chương trình C để thực thi các toán tử điều kiện lồng nhau If Else -

#include<stdio.h>
void main (){
   int a,b,c,d;
   printf("Enter the values of a,b,c: \n");
   scanf("%d,%d,%d",&a,&b,&c);
   if((a>b)&&(a>c)){//Work with 4 numbers//
      if(a>c){
         printf("%d is the largest",a);
      } else {
         printf("%d is the largest",c);
      }
   } else {
      if(b>c){
         printf("%d is the largest",b);
      } else {
         printf("%d is the largest",c);
      }
   }
}

Đầu ra

Bạn sẽ thấy kết quả sau -

Enter the values of a,b,c: 3,5,8
8 is the largest

Ví dụ

Sau đây là chương trình C để kiểm tra số là số dương hay số âm -

#include <stdio.h>
int main(){
   int num;
   printf("Enter a number:\n ");
   scanf ("%d ", &num);
   if(num > 0){
      printf("This is positive num:%d\n", num);
   }
   else if(num < 0){
      printf("This is a negative num:%d",num);
   } else {
      printf("This is a zero:%d",num);
   }
   return 0;
}

Đầu ra

Bạn sẽ thấy kết quả sau -

Run 1: Enter a number:
23
23=This number is positive
Run 2: Enter a number:
-56
-56=This number is negative