Diagram illustrating the flow of the if statement in C programming

Given Diagram is for the syntax and flowchart of the if statement. Let's learn how the syntax (if statement) works from the given diagram. We know that program execution starts from the top and goes to the end. After step-by-step successful execution of the program, the control falls into the if block. Then, the flow jumps to the condition and starts testing the condition.

1. If the condition tested is true (or its result is true), then it executes the statements inside the if body, i.e., the statements to be executed when the condition in the if is true. After successful execution of these statements, the control comes out of the if block and executes the code "statements outside the if."

2. If the condition tested is false, then the code outside the if executes—that is, the "statements outside the if" always execute regardless of whether the condition is true or false.


Example 1: C program to illustrates the use of if statement .

#include<stdio.h>
int main()
{
int x=10;
int y=2;
if(x<y)    /* Test condition to check if x is less than y */
{
printf("\n %d is smaller than %d",x,y);
}
if(y<x)    /* Test condition to check if y is less than x */
{
printf("\n %d is smaller than %d",y,x);
}
return 0;
}

Output:
2 is smaller than 10
The above program demonstrates the use of if statements to determine which number is smaller. In the program, two integer variables, x and y are declared and initialized with values 10 and 2, respectively. The first if statement uses the relational operator < to check if x is less than y, since this condition is false, no output is produced. The second if checks if y is less than x, which is true, so it prints "2 is smaller than 10." After executing, the program terminates successfully.


Example 2: C program to test if a given number is even or odd

#include <stdio.h> int main() { int n; printf("\nEnter Any Number: "); scanf("%d", &n); /* Check if the number is even */ if (n % 2 == 0) { printf("\n%d is Even\n", n); } /* Check if the number is odd */ if (n % 2 != 0) { printf("\n%d is Odd\n", n); } return 0; }

Enter Any Number
5
5 is Odd

Program Explanation:
In C, dividing two integers results in an integer value, truncating any fractional part.
For example, 7/2 results in 3, not 3.5. To determine if a number is even or odd, the program uses the modulus operator %.
Even numbers are multiples of 2 and satisfy n % 2 == 0, whereas odd numbers satisfy n % 2 != 0.
After reading the input into variable n, the program checks these conditions: if n % 2 == 0, it prints that n is even.
if n % 2 != 0, it prints that n is odd.
For input 5, the first condition is false and the second is true so it outputs "5 is Odd."


Previous Topic:-->> Conditions in C || Next topic:-->>if else in C.


Other Tutorials :
Topics wise Java Interview QuestionsTopics wise SQL QuestionsTopics Wise Python Interview Questions SQL Banking Case Study