Lets assume i have a 2x3 matrix where row denote student and column denote marks. eg:[[67,80,56], [32,26,31]] need to find the average of each row and assign a grade based on avg. if avg>40 then return "p" else return "F".
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=2;
int m=5;
int mark[][]=new int[n][m];
for(int i=0;i<n;i )
{
for(int j=0;j<m;j )
{
mark[i][j]=sc.nextInt();
}
}
String result=grade(mark);
System.out.println("RESULT:" result);
}
public static String grade(int mark[][])
{
int n=2,m=5,avg=0;
for(int i=0;i<n;i )
{
for(int j=0;j<m;j )
{
int sum=0;
sum=sum mark[i][j];
if(j==m)
{
avg=sum/m;
}
}
if(avg>=90)
{
return "A ";
}
else if(avg<40)
{
return "F";
}
}
return null;
}
}
IN the above code my my average value is initialised to 0.scope of average in for loop is not reflected in outside loop.how to correct itenter image description here
CodePudding user response:
First of all, if you need to print the grade of every student separately you will need to call your grade method for every student's marks. So put your method call in a for loop.
for(int i = 0; i < n; i ) {
System.out.println(grade(mark[i]))
}
Consequently, the definition of your method changes to
public static String grade(int mark[]) {
...
}
And at last, your if(j==m)
check will always be false, cause in your code, j
will never reach m
in your for loop. It comes to a simple calculation of array element's sum.
public static String grade(int mark[][])
{
int m = 5, avg = 0;
int sum = 0;
for(int j = 0;j < m; j ) {
sum = sum mark[i][j];
}
avg = sum / m;
if(avg >= 90)
{
return "A ";
}
else if(avg < 40)
{
return "F";
}
}
CodePudding user response:
You are declaring the sum
variable inside your 2nd loop it should be declared before your 2nd loop starts. If you declare it inside it will not have the calculated value from the previous iteration.
Also you can easily calculate avg outside the loop and then gor for your cheking.
EG:
int n=2;
int m=3;
int[][] mark = { { 67,80,56 }, { 32,26,31} };
// grade function
for (int i = 0; i < n; i ) {
int sum=0;
for (int j = 0; j < m ; j ) {
sum=sum mark[i][j];
}
int avg = sum / m;
System.out.println(avg);
//your code to check pass/fail
}
Also Don't return if you want to print values for each row. Instead of return use print there.
if(avg>=90)
{
System.out.println("GRADE")
}