How to calculate the grade point average(GPA) of students - c#

I want to write a method for a University class that takes a discipline as a parameter and returns the grade point average(GPA) of the students in that discipline, but I don't know how to do it, this is the signature of the method:
public double AverageOfDiscipline(discipline D)
{
double sum = 0;
for (int i = 0; i < students.Length; i++)
{
//???
}
return //????
}
and this is my project:
public enum discipline { Computer, Civil, Mechanical, Electrical}
public enum educationType { Undergraduate, Postgraduate}
class Student
{
public string nameAndLastName;
public double GPA;
public discipline discipline;
public educationType education;
public Student(string nameAndLastName, double GPA, discipline discipline, educationType education)
{
this.nameAndLastName = nameAndLastName;
this. GPA = GPA;
this.discipline = discipline;
this.education = education;
}
public string ToString()
{
return nameAndLastName + ": "+ education + ", "+ discipline+ "; "+"GPA: "+ GPA ;
}
}
class University
{
public string uniName;
public Student[] students;
public double AverageOfDiscipline(discipline D)
{
double sum = 0;
for (int i = 0; i < students.Length; i++)
{
//???
}
return //????
}
}
Thanks for your help.

For the university class you need to iterate through the students array,
check if they are pursuing the specified displine, sum then calculare average as below
public double AverageOfDiscipline(discipline D)
{
double sum = 0;
int totalStudentsForDispline = 0;
for (int i = 0; i < students.Length; i++)
{
if (students[i].discipline == D)
{
sum += students[i].GPA;
totalStudentsForDispline += 1;
}
}
return sum > 0 ? sum / totalStudentsForDispline : 0;
}

Related

Code not providing desired output

I am currently trying to figure out where I went wrong in this logic of code for the assignment. Any remarks or advice would be appreciated!
The output I keep getting no matter what input I put in keeps giving me:
average temperature 0,
highest temperature 5,
lowest temperature 0,
average excluding lowest 0,
number of cold days 10
First Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TemperatureAverager
{
class Temperatures
{
public double[] weeksTemperatures;
public double threshTemp;
public double average;
public double averageExcludingLowest;
public double highest;
public double lowest;
public int numOfThreshs;
public double[] WeeksTemperatures
{
get
{
return weeksTemperatures;
}
}
public double ThreshTemp
{
get
{
return threshTemp;
}
}
public double Average
{
set
{
average = value;
}
get
{
return average;
}
}
public double AverageExcludingLowest
{
set
{
averageExcludingLowest = value;
}
get
{
return averageExcludingLowest;
}
}
public double Highest
{
set
{
highest = value;
}
get
{
return highest;
}
}
public double Lowest
{
set
{
lowest = value;
}
get
{
return lowest;
}
}
public int NumberOfThreshs
{
set
{
numOfThreshs = value;
}
get
{
return numOfThreshs;
}
}
public Temperatures()
{
}
public Temperatures(double[] wTemperatures, double threshT)
{
weeksTemperatures = wTemperatures;
threshTemp = threshT;
}
public double DetermineAverage()
{
double average = 0;
for (int x = 0; x < 7; x++)
{
average = average + weeksTemperatures[x];
}
average = average / 7;
return average;
}
public double DetermineAverageExcludingLowest()
{
for (int x = 0; x < 7; x++)
{
averageExcludingLowest = averageExcludingLowest + weeksTemperatures[x];
if (weeksTemperatures[x] < lowest)
{
lowest = weeksTemperatures[x];
}
}
averageExcludingLowest = ((averageExcludingLowest - lowest) / 7); // calculate average excluding lowest temperature
return averageExcludingLowest;
}
public double DetermineLowest()
{
for (int x = 0; x < 7; x++) //Traverse through the week's temperatures
{
if (weeksTemperatures[x] < lowest) //find the lowest temperature of the week
{
lowest = weeksTemperatures[x]; //and set it to lowest
}
}
return lowest;
}
public double DetermineHighest()
{
for (int x = 0; x < 7; x++) //Traverse through the week's temperatures
{
if (weeksTemperatures[x] > highest) //find the highest temperature of the week
{
highest = weeksTemperatures[x]; //and set it to highest
}
}
return highest;
}
public double DetermineNumberOfThreshs()
{
for (int x = 0; x < 7; x++) //Traverse through the week's temperatures
{
if (weeksTemperatures[x] < threshTemp) //find the lowest temperature of the week
{
numOfThreshs++;
}
}
return numOfThreshs;
}
public override string ToString()
{
return "=====================\nWeekly Statistics\n" + "---------------------\n" + "Average Temperature: " + average + "\nHighest Temperature: "
+ highest + "\nLowest Temperature: " + lowest + "\nAvg. Excl. Lowest: " + averageExcludingLowest + "\n# of Cold Days: " + numOfThreshs + "\n====================="; //Formats and the invoice to be printed
}
}
}
Second Class
namespace TemperatureAverager
{
class TemperatureApp
{
static void Main(string[] args)
{
double[] week = new double[7];
string[] days = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; //array to track days of week
for (int x = 0; x < 7; x++)
{
Console.Write("What was the temperature on " + days[x] + "?: ");
string userTemperatureInput = Console.ReadLine();
week[x] = double.Parse(userTemperatureInput);
}
Console.Write("How cold is too cold?: ");
string userThreshInput = Console.ReadLine();
double thresh = double.Parse(userThreshInput);
Temperatures weekOne = new Temperatures(week, thresh);
Console.WriteLine(weekOne.ToString());
Console.ReadLine();
}
}
}
Class one
public class Temperatures
{
private double sum;
private int daysInWeek;
public double[] WeeksTemperatures { get; set; }
public double ThreshTemp { get; set; }
public double Average { get; set; }
public double AverageExcludingLowest { get; set; }
public double Highest { get; set; }
public double Lowest { get; set; }
public int NumOfThreshs { get; set; }
public Temperatures(double[] wTemperatures, double threshT)
{
this.WeeksTemperatures = wTemperatures;
this.ThreshTemp = threshT;
sum = 0.0;
daysInWeek = 7;
}
public void GetWeekStatistics()
{
GetSum();
DetermineLowest();
DetermineHighest();
DetermineAverage();
DetermineAverageExcludingLowest();
DetermineNumberOfThreshs();
}
private void GetSum()
{
for (int x = 0; x < daysInWeek; x++) //Traverse through the week's temperatures
{
this.sum = this.sum + this.WeeksTemperatures[x];
}
}
public void DetermineLowest()
{
this.Lowest = this.WeeksTemperatures[0];
for (int x = 0; x < daysInWeek; x++) //Traverse through the week's temperatures
{
if (this.WeeksTemperatures[x] < this.Lowest) //find the lowest temperature of the week
{
this.Lowest = this.WeeksTemperatures[x]; //and set it to lowest
}
}
}
public void DetermineHighest()
{
this.Highest = this.WeeksTemperatures[0];
for (int x = 0; x < daysInWeek; x++) //Traverse through the week's temperatures
{
if (this.WeeksTemperatures[x] > this.Highest) //find the highest temperature of the week
{
this.Highest = this.WeeksTemperatures[x]; //and set it to highest
}
}
}
private void DetermineAverage()
{
this.Average = this.sum / daysInWeek;
}
public void DetermineAverageExcludingLowest()
{
this.AverageExcludingLowest = ((this.sum - this.Lowest) / daysInWeek); // calculate average excluding lowest temperature
}
public void DetermineNumberOfThreshs()
{
for (int x = 0; x < daysInWeek; x++) //Traverse through the week's temperatures
{
if (this.WeeksTemperatures[x] < this.ThreshTemp) //find the lowest temperature of the week
{
this.NumOfThreshs++;
}
}
}
public override string ToString()
{
return "=====================\nWeekly Statistics\n" + "---------------------\n" + "Average Temperature: " + this.Average + "\nHighest Temperature: "
+ this.Highest + "\nLowest Temperature: " + this.Lowest + "\nAvg. Excl. Lowest: " + this.AverageExcludingLowest + "\n# of Cold Days: " + this.NumOfThreshs + "\n====================="; //Formats and the invoice to be printed
}
}
Change in class two
Temperatures weekOne = new Temperatures(week, thresh);
weekOne.GetWeekStatistics();
You have 7 all over the code. Make it a constant like
public static int DaysCount = 7 on the Tempratures class and reference that whenever needed (see example below).
class Temperatures
{
public static int DaysCount = 7;
}
You can then use it like this:
static void Main(string[] args)
{
double[] week = new double[Temperatures.DaysCount];
}
I can't see where you run the Determine...() functions, så the values are never calculated.
In the Determine...() functions you should set the value to an appropriate initial value before you run the loop as in:
public double DetermineHighest()
{
highest = -273 // degrees
for (int x = 0; x < DaysCount; x++) //Traverse through the week's temperatures
{
if (weeksTemperatures[x] > highest) //find the highest temperature of the week
{
highest = weeksTemperatures[x]; //and set it to highest
}
}
return highest;
}

I need help on using an array made in one class in a different class and get its sum

In my Inputs class I have an array named score. I need to use it in my MathFun class and get the sum of it.
class Inputs
{
int amountgames;
public void AmountOfGames()
{
Console.WriteLine("How many games did you play?");
amountgames = int.Parse(Console.ReadLine());
}
public void Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
}
class MathFun
{
int number1;
int number2;
int total;
int averaged;
public int Average;
public int Added1;
public MathFun()
{
}
public void DivideThem()
{
Average = number1 / number2;
}
public void Added()
{
Added1 = inputs.score.sum();
//This is where in the array and its sum
}
public MathFun(int innumber1, int innumber2)
{
number1 = innumber1;
number2 = innumber2;
}
public int Number1
{
get
{
return number1;
}
set
{
number1 = value;
}
}
public int Number2
{
get
{
return number2;
}
set
{
number2 = value;
}
}
public int Total
{
get
{
return total;
}
}
public int Averaged
{
get
{
return averaged;
}
}
public void CalcTotal()
{
total = Added1;
averaged = Average;
}
}
You have two choices
Create an instance of Inputs that you can use in MathFun.
Make Scores() static, so that an instance is not required. If you do that, amountgames and AmountOfGames() will also have to become static.
Either way, you will have to return the inputs from Scores() or store them in some way in the class.
public int[] Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
return score;
}
Here's how you could approach it with the first approach
Inputs inputs = new Inputs();
int[] scores = Scores();
// Use scores with MathFun
NOTE: I would not generally create a function that is both responsible for writing scores out to the console and returning them. A single responsibility per method is preferred. The solution here is one that modifies your current code as little as possible.
Found my own solution
int sum = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
}
add this to the array to add it all up
then just make an instance of sum

how do you calculate and return a total value in c#?

I'm, trying to add a method Takings which calculates and returns the total value of all the bookings for this show. If anyone could lead me in the right direction that would be great :)
namespace GCUShows
{
public class Show
{
private string title;
private Dictionary<int, Booking> bookings;
public string Title
{
get { return title; }
set { title = value; }
}
public Show(string title)
{
this.title = title;
this.bookings = new Dictionary<int, Booking>();
}
public void AddBooking(int bookingID, Booking booking)
{
this.bookings.Add(bookingID, booking);
}
public void RemoveBooking(int bookingID, Booking booking)
{
this.bookings.Remove(bookingID);
}
public Takings
{
}
}
namespace GCUShows
{
public enum TicketType
{
Adult,
Child,
Family
}
public class Booking : ITicket
{
private const int LIMIT = 6;
public Show show;
private int bookingID;
public List<ITicket> tickets;
public int BookingID
{
get { return bookingID; }
set { bookingID = value; }
}
public Booking(Show show)
{
this.BookingID = BookingIDSequence.Instance.NextID;
this.show = show;
show.AddBooking(this);
this.tickets = new List<ITicket>();
}
public void AddTickets(int number, TicketType type, decimal fee)
{
if (type == TicketType.Adult)
{
for(int i =0; i < number; i++)
{
tickets.Add(new AdultTicket(show.Title, fee));
}
}
else if (type == TicketType.Child)
{
for(int i=0; i< number; i++)
{
tickets.Add(new ChildTicket(show.Title));
}
}
else if (type == TicketType.Family)
{
for (int i = 0; i < number; i++)
{
tickets.Add(new FamilyTicket(show.Title, fee));
}
}
}
public string PrintTickets()
{
string ticketInfo = "Booking " + bookingID.ToString() + "\n";
foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
return ticketInfo;
}
public decimal TotalCost()
{
decimal totalCost;
foreach (ITicket ticket in tickets)
{
totalCost += ticket.Fee;
}
return totalCost;
}
public override string ToString()
{
return string.Format("{0}: Total Cost={1:c}", bookingID, TotalCost());
}
}
}
Assuming Bookings contains a property int Val, it could look like:
public int Takes()
{
return bookings.Values.Sum(b => b.Val);
}
If Booking has a Cost property, you can do this:
var total = bookings.Sum(x => x.Value.Cost);
Alternatively to other Linq answer you can do the same thing with a foreach
public decimal Takings()
{
decimal runningTotal = 0;
foreach (KeyValuePair<int, Booking> kvp in bookings) {
runningTotal += kvp.Value.TotalCost();
}
return runningTotal;
}
which might look a little less "magic" if you are new to programming.
this is my bookings class
namespace GCUShows
{
public enum TicketType
{
Adult,
Child,
Family
}
public class Booking : ITicket
{
private const int LIMIT = 6;
public Show show;
private int bookingID;
public List<ITicket> tickets;
public int BookingID
{
get { return bookingID; }
set { bookingID = value; }
}
public Booking(Show show)
{
this.BookingID = BookingIDSequence.Instance.NextID;
this.show = show;
show.AddBooking(this);
this.tickets = new List<ITicket>();
}
public void AddTickets(int number, TicketType type, decimal fee)
{
if (type == TicketType.Adult)
{
for(int i =0; i < number; i++)
{
tickets.Add(new AdultTicket(show.Title, fee));
}
}
else if (type == TicketType.Child)
{
for(int i=0; i< number; i++)
{
tickets.Add(new ChildTicket(show.Title));
}
}
else if (type == TicketType.Family)
{
for (int i = 0; i < number; i++)
{
tickets.Add(new FamilyTicket(show.Title, fee));
}
}
}
public string PrintTickets()
{
string ticketInfo = "Booking " + bookingID.ToString() + "\n";
foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
return ticketInfo;
}
public decimal TotalCost()
{
decimal totalCost;
foreach (ITicket ticket in tickets)
{
totalCost += ticket.Fee;
}
return totalCost;
}
public override string ToString()
{
return string.Format("{0}: Total Cost={1:c}", bookingID, TotalCost());
}
}
}

Refer variable from different class

using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
S_Matrix_size size = new S_Matrix_size(r,c);
double[,] entry = new double [size.size_R,size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < **matrix_no1.size**; i++)
{
}
}
}
}
As the title says, I'm trying to access a variable from a class instance, but don't know how to do it properly.
You can't access matrix_no1.size because size is inaccessible.
Add a public property to your C_Matrix_entries class, and reference it in Main().
public class C_Matrix_entries
{
public S_Matrix_size size { get; private set; }
public C_Matrix_entries()
{
...
size = new S_Matrix_size(r,c);
As #GrantWinney rightfully pointed out (as I was shaping up a working reply for you), you cannot access matrix_no1.size because it is inaccessible. (It is also out of scope being that matrix_no1 is a local variable declared in the default C_Matrix_entries constructor.)
Based on your code, here is an end-to-end working example of how to fix the problem using a somewhat different public property added to C_Matrix_entries. Beyond the flavor of the new S_Matrix_size public property you add to C_Matrix_entries (i.e. Grant Winney's will work too), you will need to compute the product of its size_R and size_C properties in your loop's setup.
using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
private S_Matrix_size _size;
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
_size = new S_Matrix_size(r,c);
double[,] entry = new double [_size.size_R,_size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<_size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<_size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
public S_Matrix_size Size { get { return _size; } }
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < matrix_no1.Size.size_R * matrix_no1.Size.size_C; i++)
{
// TODO: something useful
Console.WriteLine(i); // FORNOW
}
}
}
}

What wrong with my loop .Need to calculate a running total

I have to build some logic to write some sort of scoreboard. The idea is this:
There are many stages:
1st stage you have 2 numbers. 7 and 3=10
2nd stage you have another 2 numbers. 5 and 1 =6
After the loop has finished, the wanted result should be:
Stage 1 total score=15 (total 1st Stage + firstTry of secondStage)
Stage 2 total score=21 (total 1st Stage + (firstTry + SecondTry of SecondStage)
What's wrong with my loop? I dont seem to get the wanted resoult.
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
//If firstTry + SecondTry==10 is spare
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore +
player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = stageScore;
}
}
}
public class Stage
{
public int FirstTry { get; set; }
public int SecondTry { get; set; }
public int TotalScore { get; set; }
}
public class Player
{
public Player(string name)
{
Name = name;
Game = new Game(name);
}
public Game Game { get; set; }
public string Name { get; set; }
}
public class Game
{
public Game(string playerName)
{
PlayerName = playerName;
Stages = new Stage[10];
for (int i = 0; i < Stages.Length; i++)
{
Stages[i] = new Stage();
}
}
public Stage[] Stages { get; internal set; }
public string PlayerName { get; set; }
}
Change this:
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore + player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = sumFirstAndSecond + stageScore;
}
else if (i > 0) player.Game.Stages[i].TotalScore = player.Game.Stages[i - 1].TotalScore + sumFirstAndSecond;
}
}
Bowling?
Try this, and do not forget to add misses (as 0).
Should work for both running and final scoring.
// All balls, including misses (0)!
public readonly IList<int> _balls = new List<int>();
private int _currentBall;
public int CalculateTotalScore()
{
int score = 0;
_currentBall = 0;
for (var frame = 0; frame < 10; frame++)
{
if (_currentBall >= _balls.Count)
break;
if (_balls[_currentBall] == 10)
{
// Strrrike!
score += AggregateScoreFromCurrentBall(3);
_currentBall++;
}
else if (AggregateScoreFromCurrentBall(2) == 10)
{
// Spare
score += AggregateScoreFromCurrentBall(3);
_currentBall += 2;
}
else
{
score += AggregateScoreFromCurrentBall(2);
_currentBall += 2;
}
}
return score;
}
private int AggregateScoreFromCurrentBall(int numberOfBallsToSum)
{
var sum = 0;
for (var i = 0; i < numberOfBallsToSum; i++)
if (_currentBall + i < _balls.Count)
sum += _balls[_currentBall + i];
return sum;
}

Categories

Resources