C Lesson 4: How to write C program using IF statement?

How to write C program using IF statement?

To see the most basic things needed to write a C program, click C Basics: Identifiers and Keywords 

IF Statement:

  • If-else statement is a branching statement.
  • Syntax:
    if (expr) statement
    else statement
  • The expression followed by ‘if’, consists of a logical test that has to checked true or false. If it is true then the instructions following the “if” condition is performed.
  • If the result is false then the instructions following the “else” condition is performed.

How to write C program using IF statement:

Lets see an example through which we learn how to do a C program using IF-Statement.

Here we have seen the most simple example and a well-known too. Lets see its explanation step by step.

  1. #include<stdio.h>
    This is a simple pre-defined library function. It handles all input-output operations.
  2. main():  function where execution starts at first. Note that there is no program without main function.
  3. Now let’s get the input through the variable x.
  4. To get the value of x from user we use the scanf statement. Here the %d indicates the compiler that the input value is an integer.
  5. To indicate the user to type input value in the output screen we use printf statement.
  6. Now we use the if statement. in which we check whether the given input is odd or even using the following condition. “x%2=0”.
    Here the symbol “%” – modulo means the finding the remainder of the division. i.e., if we divide the x by 2, the remainder is the answer of the given expression.
    For the given value to be even, the remainder should be zero.
  7. If the condition is true, then we print the statement, “the input is even”.
  8. If the condition is false, then we print the statement, “the input is odd”.

Check the above program with various input.
Hope you could easily understand the basic conditional statement IF-ELSE statement.

Related Posts:

C Programming Tutorial for Electrical Engineer – Part-1

How to compile and run C program?

Thanks for reading… Hope now become familiar with How to write C program using IF statement… Leave your comments below…

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *