MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Student Average with Explanation

PHP Easy PHP OOP Basics 32 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around student, average, mark. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Create a Student class that stores marks and prints average with 2 decimals.

Input Format

First n. Next line n marks.

Output Format

One number with 2 decimals.

Constraints

n

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php class Student{ private $marks=[]; function add($m){ $this->marks[]=$m; } function avg(){ if(!count($this->marks)) return 0.0; $sum=0.0; foreach($this->marks as $m) $sum+=$m; return $sum/count($this->marks); } } $inputText=trim(stream_get_contents(STDIN)); if($inputText==='') exit; $tokens=preg_split('/\\s+/', $inputText); $i=0; $n=intval($tokens[$i++] ?? 0); $st=new Student(); for($k=0;$k<$n;$k++) $st->add(floatval($tokens[$i++] ?? 0)); echo number_format($st->avg(),2,'.',''); ?>

Output Example

Input:
4 80 90 70 100
Output:
85.00

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next