if Statement in C: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-04 05:11:24   9852  Share
Subject Syllabus DetailsSubject Details 8 Program
☰ TContent
☰Fullscreen

Table of Content:

The C programming language provides a general decision-making capability in the form of a language construct known as the if statement.The general format of this statement is shown here:

Syntax

The syntax of an if statement in C programming language is ?

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

Imagine that you could translate a statement such as "If it is not raining, then I will go swimming" into the C language. Using the previous format for the if the statement, this might be "written" in C as follows:

if ( it is not raining )
I will go swimming

The if statement is used to stipulate execution of a program statement (or statements, if enclosed in braces) based on specified conditions. I will go swimming if it is not raining. Similarly, in the program statement.

if ( count > MAXIMUM_SONGS )
[playlist maxExceeded];

the maxExceeded message is sent to playlist only if the value of count is greater than the value of MAXIMUM_SONGS ;otherwise,it is ignored.


Flow Diagram Example

if statement in c programming language

Wrong Syntax

if n > 0 {
printf("i is positive");
}

Example of right statement

if(n > 0) {
 printf("i is positive");
}

Equivalent of the above Syntax

The block braces { } can be omitted if they enclose a single statement.

if(n > 0)
 printf("i is positive");

Program


 #include<stdio.h>
 void main(){
	float radius, area, PI;
	PI=3.14f;
	radius = 2.1f ;

	 if (radius >= 0) {
	 area = radius * radius * PI;
	 printf("The area for the circle %f ",area);
     }
  }

Output

The area for the circle 13.847399 
  1. The first line of the code includes the standard input-output library of C.
  2. The main function is defined as void, meaning it does not return any value.
  3. Three float variables are declared: radius, area, and PI.
  4. The value of PI is assigned as 3.14f.
  5. The value of radius is assigned as 2.1f.
  6. An if statement is used to check if the value of radius is greater than or equal to zero.
  7. If the condition in the if statement is true, the area of the circle is calculated by multiplying the square of the radius with PI.
  8. The calculated area is then printed to the console using the printf function, with the text "The area for the circle" followed by the area value.

Another Example


#include<stdio.h> 
int main () { 
   /* local variable definition */
   int a = 100;
 
   /* check the boolean condition using if statement */
	
   if( a < 220 ) {
      /* if condition is true then print the following */
      printf("a is less than 220\n" );
   }
   
   printf("value of a is : %d\n", a);
 
   return 0;
}

Output

a is less than 200
value of a is : 100
Press any key to continue . . .