In: Computer Science
For example, suppose you had a program to determine if a number is positive, negative or zero. Read in a number and then use the if statement to determine if the number is positive (>0) or negative (<0) or zero (==0):
if (x>0)
//display positive message
else if (x<0)
//display negative message
else
//display zero message
Example (1)- In this example suppose we have an integer array . and we want to display sum of all even value and sum of all odd value.
Our array is -
//declare the array with 5 value
Int a[5]={15,20,22,17,18}
If(a[i]%2==0)
{
evenSum=Evensum+a[i];
Print the sum of even number in Array.
}
else
{
oddSum=oddSum+a[i];
Print the sum off odd number in Array
}
Example(2)- using if with AND operator
//if value of i is greater the 10 and less then 50 then go inside the if statement.we use And(&&) operator in this example so it will execute only when both condition are true
If(i>10 && i<50) {
If(i%5==0)//if value of i is divisible by 5 then go inside the if statement
{
Print i; //print value of i
}
}
Example (3)- using if with OR opetator
If(i>5) //if value of I is greater then 5 then go inside the if statement
{
//if value of i is equal to 6 or i is divisible by 2 then go inside if statement. We use or(||) operator in if statement it means if any one condition is true the this if statement will be execute
If(i==6 || I%2==0)
{
Print the value of i
}
}