How can I add up multiple inputs in solidity?

Viewed 192

This test contract is to perform a mathematics function. One of the inputs required is the "Unit". I need to write a function that then sums up all the unit that were inputted. How can I do this?

This is my code below.

 pragma solidity ^0.8.0;
    
    contract GpCalculator{
    
        string CourseName;
        uint Unit;
        uint Score;
    
    struct Details{
        string CourseName;
        uint Unit;
        uint Score;
        }
     
    Details[] public details;

//function that request for the input

function addCourseDetails(string memory _CourseName, uint _Unit, uint _Score)public{
    details.push(Details(CourseName = _CourseName, Unit = _Unit, Score = _Score));
    }


//functions that allows the user view their last input

function retrieveDetails()public view returns(string memory, uint, uint){
    return(CourseName, Unit, Score);}

//function that grades the performance of the user, based on their input score

function retrieveGrade() public view returns(string memory){
    if (Score >69 && Score<=100){
        return("A");
        } else if (Score >59 && Score<=69){
            return ("B");
            } else if (Score >49 && Score<=59){
                return ("C");
                }else if (Score >45 && Score<=49){
                    return ("D");
                    }else if (Score <45 && Score >=30){
                        return ("E");
                        }else if(Score <30){
                            return ("Retake this course!");
                            }else {
                        return ("Imposible");
                    }
    
//function that calculates Grade point

function calculatePoint()public view returns(uint G){
    if (Score >69 && Score <=100){
        G = 4;
    }else if (Score >59 && Score<=69){
        G = 3;
    }else if (Score >49 && Score<=59){
        G = 2;
    }else if (Score >45 && Score<=49){
        G = 1;
    }else if (Score <=44){
        G = 0;
    }else{
        G = 0;
    }
    return(Unit * G);
    }


}

The final formula is expected to be === Sum of all gradepoint / sum of all Units.

I will appreciate your answers.

1 Answers

You can create a view function that loops through the details array and sums up its items.

A view function is gas free as long as it's invoked using a call - and not as a part transaction (e.g. from another function that was invoked using a transaction).

function getUnitSum() public view returns (uint) {
    // default value 0
    uint sum;

    for (uint i = 0; i < details.length; i++) {
        sum += details[i].Unit;
    }

    return sum;
}
Related