Write a program to take 10 numbers in an array and count the number of positive, negative numbers and zeros.
Write a program to take 10 numbers in an array and count the number of positive, negative numbers and zeros.
STEP 1: First I have taken 10 numbers in an array and you can provide any 10 nos. on your choice in an array.
$arr=["-5","-4","-3","-2","-1","0","1","2","3","4"];
STEP 2: Then I have declared 3 variables. One variable is to count for positive number, another is to count for negative number and the last variable is is to count for zero number, where I have stored 0 in each variable.
$posnos=0;$neganos=0;$zeronos=0;
STEP 3: Then I have stored the array values in another variable where I will count the number of values stored in the array and that's why I have used count() function.
$length=count($arr);
STEP 4: Then I have taken one variable $i=0 where I am checking the for loop condition that whether $i<$length and if this for loop condition $i<$length is true then we check the if condition and after that it will be $i++ that means $i will increase by 1 otherwise if the for loop condition $i<$length is false then it will execute the else part.
for ($i=0; $i < $length; $i++) {
STEP 5: Then after the for loop condition is true it will check the if condition that is if($arr[$i]>0) and if the if condition is true it will execute $posnos++ means $posnos will increase by 1.
if ($arr[$i]>0) {
$posnos++;
}
STEP 6: But if the if condition is false then it will check the elseif part where elseif($arr[$i]<0) and if the elseif condition is true it will execute $neganos++ means $neganos will increase by 1 and if the elseif condition is false then it will check the else part where it will execute $zeronos++ means $zeronos will increase by 1.
elseif ($arr[$i]<0) {
$neganos++;
}
else{
$zeronos++;
}
}
STEP 7: Then it will print the count of positive number, negative number and zero number using echo.
echo "The positive number is: ".$posnos;
echo "<br>";
echo "The negative number is: ".$neganos;
echo "<br>";
echo "The zero number is: ".$zeronos;
CODE:
<?php
$arr=["-5","-4","-3","-2","-1","0","1","2","3","4"];
$posnos=0;$neganos=0;$zeronos=0;
$length=count($arr);
for ($i=0; $i < $length; $i++) {
if ($arr[$i]>0) {
$posnos++;
}
elseif ($arr[$i]<0) {
$neganos++;
}
else{
$zeronos++;
}
}
echo "The positive number is: ".$posnos;
echo "<br>";
echo "The negative number is: ".$neganos;
echo "<br>";
echo "The zero number is: ".$zeronos;
?>
OUTPUT:
The positive number is: 4
The negative number is: 5
The zero number is: 1
Comments
Post a Comment