1

I came across this program on http://www.programmr.com . And the question is Complete the program to print the sum of negative numbers, positive even numbers, positive odd numbers from a list of numbers entered by the user. The list terminates when the number entered is zero . And my code is,

$nums = array();

while(trim(fgets(STDIN)) != 0){
    array_push($nums,trim(fgets(STDIN)));
}

I know the code is incomplete but what im trying to do is to push the inputs to the array and then calculate the sum. When I print_r($nums) the array it gives me this,

Array
(
    [0] => 34
    [1] => 32
    [2] => 45
    [3] => 0
)

And my input is,

 12
 34
 12
 32
 12
 45
 12
 0
 0

It pushes the alternative elements i dont know whats happening with this. Please help me , thanks in advance.

1 Answer 1

1

You are calling fgets(STDIN) twice in your code, i have adjusted it a bit so the array part is working. The rest of the assignment i let you figure that part out ;) Hint: Use modulus operator.

$nums = array();

do {
    $number = (int) trim(fgets(STDIN));
    array_push($nums,$number);
} while ($number !== 0);

print_r($nums);

Also if you are using PHP5.6 or higher you can use short array syntax like so:

$nums = [];

And

$nums[] = $number;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.