Hello friends, today I am going to discuss the topic control decision the if statement in C language programming. In our daily life, we all need to make decisions on different situations or different topics, sometimes we are all in confusion state. Example 1. if the weather is fine, then I will go for walk.
2. If the highway is busy with traffic, I would like to take a diversion.
or 3. if no friends are free, I would like to take a diversion.
In these all our statements, conditions were there. C language also solves these types of decision control instructions by using different decision control statements, these are as follows. The following video shows how to use if statement in C language.
Types of Control Decision Statements
- The simple If statement
- The If-Else statement
- Nested If statements
- The Conditional Operators (? :)
we will see each one by one.
The simple if statement
When we are writing our program, we need syntax or the general form of the statement so that we can write our statement easily.
Syntax
if (expression)
program statement;
or
if (condition is true)
execute this statement;
Example 1: Calculate the absolute value of an integer
In this example first, we have to understand what is absolute value?
Absolute value describes the distance of a number on the number line from 0 without considering which direction from zero the number lies. The absolute value of a number is never negative. The absolute value of 5 is 5 and the absolute value of -5 is also 5.
| | | | | | | | | | | | | | | | |
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
Now we have to find out how to define absolute value? if the number is less than 0 then we have to convert that number in positive format and then find out the absolute value, Otherwise print that number as it is because the value of a positive number is as it is, sees the below example.
Coding
//Example: a program to determine if a number is even or odd
#include <stdio.h>
int main ()
{
int number;
printf ("\n Enter the number: "); // read the input by user
scanf ("%d", &number);
if (number < 0) //Actually if condition by using MOd operator
number = -number;
printf ("The absolute value is %d \n", number);
return 0;
}
output
Enter the number: -233
The absolute value is 233
Output re-run Enter the number: 76
The absolute value is 76
Do you like my post, please feel free to give comments or subscribe to my blog? Also, see my youtube channel for one-to-one communication, or Subscribed to the My Computer Tutors for updates. I will keep updating you with the latest tutorials.
Comments
Post a Comment
Your comment will inspire me, Please leave your comment