PHP Program to Student Average with Explanation
PHP
Easy
PHP OOP Basics
32 views
1 min read
91 words
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.
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,'.','');
?>
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).
Solution Guide
Problem
Create a Student class that stores marks and prints average with 2 decimals.
Input / Output
Input
First n. Next line n marks.
Output
One number with 2 decimals.
Details
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).
Official Solution
<?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,'.','');
?>
Solutions (0)
No solutions submitted yet. Be the first!