Using if statement in C: A Beginner's Guide


The if statement is a simple decision-making and branching statement and it is used to control the flow of the program execution. An if statement consists of a Boolean expression followed by one or more statements. The if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets.

  Syntax:
     if( condition )
     {
        // body of the statements will execute if the condition is true ;
     }

  • The condition evaluates to either true or false.
  • True is always a non-zero value, and false is a value that contains zero.

The code is a C program that demonstrates the use of the if statement in C. Here is an explanation of each line of the code:

  • char name[10]; declares a character array variable named name with a maximum size of 10 characters.
  • int age; declares a variable age of type int.
  • printf("\nEnter Your Name : "); prints a message prompting the user to enter their name.
  • scanf("%s",name); reads a string input from the user and stores it in the variable name.
  • printf("\nEnter The Age : "); prints a message prompting the user to enter their age.
  • scanf("%d",&age); reads an integer input from the user and stores it in the variable age.
  • if(age>=18) checks if the value of the variable age is greater than or equal to 18.
  • printf("\n %s age is %d Eligible For Vote",name,age); prints a message stating that the user is eligible to vote if the above if condition is true.
  • return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.

Source Code

//if statement
 
#include<stdio.h>
int main()
{
    char name[10];
    int age;
    printf("\nEnter Your Name : ");
    scanf("%s",name);
    printf("\nEnter The Age : ");
    scanf("%d",&age);
    if(age>=18)
    {
        printf("\n %s  age is %d Eligible For Vote",name,age);
    }
    return 0;
}
 
 
To download raw file Click Here

Output

Enter Your Name : Siva
Enter The Age : 21
Siva  age is 21 Eligible For Vote

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C