I must create a console application. Write a LepsiStudent method that performs the following parameters on your input:
the name of the first student
field of first student marks
the name of the second student
field of second student marks
The method calculates the arithmetic means of the marks of these students and lists which student has a better average.
In the main method, prepare two fields of marks and student names. Then call the LepsiStudent method.
I code this and I don't know how to continue average grade can someone help me please?
{
class Program
{
static void Main(string[] args)
{
double[] znamkyjan = { 2, 4 };
double[] znamkydan = { 1, 5 };
LepsiStudent(znamkyjan,znamkydan);
}
static void LepsiStudent (double [] znamky, double[] znamky2)
{
Console.WriteLine("Jan Novák");
foreach (var znam in znamky)
{
//Console.WriteLine(znam);
Console.WriteLine(znam / 2);
}
Console.WriteLine("Daniel Havlík");
foreach (var znam2 in znamky2)
{
Console.WriteLine(znam2);
}
}
}
}
The Linq library has a built-in Average method:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
double[] znamkyjan = { 2, 4, 5, 7 };
double[] znamkydan = { 1, 5, 5, 9 };
LepsiStudent(znamkyjan,znamkydan);
}
static void LepsiStudent (double [] znamky, double[] znamky2)
{
double m1 = znamky.Average();
double m2 = znamky2.Average();
Console.WriteLine("Jan Novák: " + m1);
Console.WriteLine("Daniel Havlík: " + m2);
}
}
Output
Jan Novák: 4.5
Daniel Havlík: 5
To calculate an average you need to sum the values and then divide by the number of grades,
and you want to do that for each student.
We could do this with less variables, but this is a little more readable for someone new to programming.
we go over all the first student grades- sum them and divide, and the same for 2nd student- then we compare and print the result..
static void LepsiStudent(double[] znamky, double[] znamky2)
{
double student1Sum = 0;
double student1Avg = 0;
double student2Sum = 0;
double student2Avg = 0;
foreach (var znam in znamky)
{
student1Sum += znam;
}
student1Avg = student1Sum / znamky.Length;
foreach (var znam2 in znamky2)
{
student2Sum += znam2;
}
student2Avg = student2Sum / znamky2.Length;
if (student1Avg > student2Avg)
{
Console.WriteLine("first student has the higher average");
}
else if (student1Avg == student2Avg)
{
Console.WriteLine("neither student has the higher average");
}
else
{
Console.WriteLine("second student has the higher average");
}
}
Just for fun, this does the same thing with linq:
static void LepsiStudent(double[] znamky, double[] znamky2)
{
double student1Avg = znamky.Sum() / znamky.Length; ;
double student2Avg = znamky2.Sum() / znamky2.Length;
string name = (student1Avg == student2Avg) ? "neither" :
Math.Max(student1Avg, student2Avg) == student1Avg ? "first" : "second";
Console.WriteLine($"{name} student has the higher average");
}
Related
I need to print mathematical table without using any loop (for, while, do while, etc.). Can anyone help me out, the easiest example I could find was writing console.writeline 10times for each line.
This is my code!
using System;
using System.Linq;
class Question4
{
int product, i=1;
public static void Main(string[] args)
{
int num;
Console.Write("Enter the Number to Print its Multiplication Table: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nMultiplication Table For {0}: ",num);
TableFunctionName (num);
}
public void TableFunctionName(int n)
{
if(i<=10)
{
table=n*i;
Console.WriteLine("{0} x {1} = {2}",n,i,table);
i++;
}
return;
}
}
Using recursion
static void Multiply(int a, int b) {
if (a > 1)
Multiply(a - 1, b);
Console.WriteLine($"{a} * { b} = {a * b}");
}
static void Main(string[] args) {
Multiply(10, 5);
}
}
You could use recursion
public static void Main()
{
Console.Write("Enter the Number to Print its Multiplication Table: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
CalculateAndPrint(number, 1);
}
static void CalculateAndPrint(int number, int factor)
{
if (factor > 9) return;
Console.WriteLine("{0} x {1} = {2}", number, factor, number * factor);
CalculateAndPrint(number, ++factor);
}
I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}
Is there anyway to achieve the following in C# (or any other ,Net language)?
public double nestedParamArrayLoop(function delegatedFunction, LoopControllers loopControllers)
{
double total = 0;
NestedLoopControllers loopControllers = new NestedLoopControllers(loopController, loopMaxes);
foreach(LoopController loopController in loopControllers);
{
nestedfor (loopController)
{
// this line results in one or more loopControllers being passed in
total += delegatedFunction(loopController);
}
}
return total;
}
public double delegatedFunction(params int[] arguments)
{
// dummy function to compute product of values
long product = 1;
for (int i = 0; i < arguments.Count ; i++)
product *= arguments[i];
return product;
}
Where delegatedFunction is called with a variable number of parameters, according to the number of controllers in the array loopControllers? Each loopController would contain a start value, a max value and an increment value (i.e. template a for loop).
The syntax above doesn't quite work as I'm not sure any exists to capture this paradigm. But the idea is that you can specify an arbitrary number of nested loops and then the nesting is done for you by the compiler (or the runtime). So it's a kind of templated nesting where you define the loop conditions for an arbitrary number of loops and the environment constructs the loops for you.
For example
NestedParamsArrayLoop(delegatedFunction, loopContoller1); results in iterated calls to delegatedFunction(values for loopValue1);
NestedParamsArrayLoop(delegatedFunction, loopContoller1, loopController2); results in
iterated calls to delegatedFunction(values for loopValue1, values for loopValue2);
NestedParamsArrayLoop(delegatedFunction, values for loopContoller1, values for values for loopController2, loopController3); results in
iterated calls to delegatedFunction(loopValue1, values for loopValue2, values for loopValue3);
The goal of this is to avoid writing separate functions with different numbers of arguments but where the actual guts of the logic is common across them.
I hope I've done a decent job of explaining this but if not please ask!
I think this is pretty much what you want to do.
Start with a LoopController definition:
public class LoopController : IEnumerable<int>
{
public int Start;
public int End;
public int Increment;
private IEnumerable<int> Enumerate()
{
var i = this.Start;
while (i <= this.End)
{
yield return i;
i += this.Increment;
}
}
public IEnumerator<int> GetEnumerator()
{
return this.Enumerate().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Now you can define NestedParamArrayLoop like so:
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
double total = 0;
foreach (LoopController loopController in loopControllers)
{
total += delegatedFunction(loopController.ToArray());
}
return total;
}
Now the rest is easy:
void Main()
{
var loopControllers = new List<LoopController>()
{
new LoopController() { Start = 4, End = 10, Increment = 2 },
new LoopController() { Start = 17, End = 19, Increment = 1 },
};
Console.WriteLine(NestedParamArrayLoop(DelegatedFunction, loopControllers));
}
public double DelegatedFunction(params int[] arguments)
{
long product = 1;
for (int i = 0; i < arguments.Count(); i++)
product *= arguments[i];
return product;
}
You could even define NestedParamArrayLoop as this:
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
return
loopControllers
.Select(lc => delegatedFunction(lc.ToArray()))
.Sum();
}
Is this more like what you're after?
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
Func<IEnumerable<int>, IEnumerable<IEnumerable<int>>> getAllSubsets = null;
getAllSubsets = xs =>
(xs == null || !xs.Any())
? Enumerable.Empty<IEnumerable<int>>()
: xs.Skip(1).Any()
? getAllSubsets(xs.Skip(1))
.SelectMany(ys => new[] { ys, xs.Take(1).Concat(ys) })
: new[] { Enumerable.Empty<int>(), xs.Take(1) };
double total = 0;
foreach (LoopController loopController in loopControllers)
{
foreach (var subset in getAllSubsets(loopController))
{
total += delegatedFunction(subset.ToArray());
}
}
return total;
}
Since the OP asked for a solution in any .NET language, I wrote one in F# (translating #Enigmativity's answer). No NestedLoopController class required:
[[ 4 .. 2 .. 10 ]; [ 17 .. 1 .. 19 ]]
|> Seq.map (fun args ->
(1L, args)
||> Seq.fold (fun a x -> a * int64 x))
|> Seq.sum
|> printfn "%d"
You can probably translate this to C# LINQ in a relatively straightforward way…
I think what you really need is what is called cartesian product of multiple sets. Here is good article from Eric Lippert about doing that with arbitrary number of sets in C#. So create function like this (I won't explain it because I cannot do this better than Eric did in his article):
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(params IEnumerable<T>[] sources) {
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var source in sources) {
var tmp = source;
result = result.SelectMany(
seq => tmp,
(seq, item) => seq.Concat(new[] { item }));
}
return result;
}
Then use like this:
foreach (var n in CartesianProduct(Enumerable.Range(1, 4), Enumerable.Range(1, 4))) {
Console.WriteLine(String.Join(", ", n));
// in your case: delegatedFunction(n);
}
outputs
1, 1
1, 2
1, 3
1, 4
2, 1
2, 2
2, 3
2, 4
3, 1
3, 2
3, 3
3, 4
4, 1
4, 2
4, 3
4, 4
It's easy to replace Enumerable.Range with your LoopController, Enumerable.Range is used just as an example.
I figured it out! Turns out it was printing to the console but it would print something like
1 (2)
2 (2)
3 (3)
Indicating each number had gone twice. If I print the numbers with the trial count I get what I am looking for
TC 1, Num 1
TC 2, Num 2
TC 3, Num 3
TC 4, Num 1
TC 5, Num 2
TC 6, Num 3
Thanks for all your suggestions.
I am new to C# and have run into an issue I can't seem to find the solution to.
I have a float array that has 6 slots, 3 of the slots are duplicated numbers
( 1.0f,2.0f,3.0f,1.0f,2.0f,3.0f).
I need to print out each of these numbers to the consul every time I hit "a".
The issue is that after the first 3 numbers it stops printing-- in the console I get :
1,2,3.... index out of range
I use the numbers in the array to change the size of an object. This object continues to change size with each "a" pushed so I know it is going through the whole array.
How can I get it to print the duplicates?
Here is a short version of my code, it has been shortened to remove irrelevant things.
*********************************************************************
public class ChangeSize : MonoBehaviour {
float[] numbers;
int MyIndex;
public int Range;
int trialCount = 0;
// Use this for initialization
void Start () { //************************************Start
numbers = new float[] { 1.0f,2.0f,3.0f,1.0f,2.0f,3.0f };
}
// Update is called once per frame
void Update()
{
changeSizeObj();
}
//**************************************************Functions
void changeSizeObj() {
if (Input.GetKeyDown("a"))
{
transformSize();
}
}
void transformSize()
{
float num = numbers[trialCount];
print(num);
transform.localScale = new Vector3(num, num, num);
trialCount += 1;
}
}
To only print the duplicates, you could do something like this:
*********************************************************************
public class ChangeSize : MonoBehaviour
{
float[] numbers;
HashSet<float> numberCheck; // hashset
int MyIndex;
public int Range;
int trialCount = 0;
// Use this for initialization
void Start () { //************************************Start
numbers = new float[] { 1.0f,2.0f,3.0f,1.0f,2.0f,3.0f };
}
// Update is called once per frame
void Update()
{
changeSizeObj();
}
//**************************************************Functions
void changeSizeObj() {
if (Input.GetKeyDown("a"))
{
transformSize();
}
}
void transformSize()
{
float num = numbers[trialCount];
if (numberCheck.Contains(num)) // check for duplicates
print(num);
else
numberCheck.Add(num);
transform.localScale = new Vector3(num, num, num);
trialCount += 1;
}
}
// *******
Or make use of this method:
public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> items)
{
HashSet<T> seen = new HashSet<T>();
foreach (var item in items)
if (seen.Contains(item))
yield return item;
else
seen.Add(item);
}
Usage:
// Use this for initialization
void Start () { //************************************Start
numbers = new float[] { 1.0f,2.0f,3.0f,1.0f,2.0f,3.0f };
for(var num in numbers.GetDuplicates())
print(num);
}
Currently working on a project and need some help. Still relatively new to c#. I have created a dice rolling game in which 5 dice are rolled at once in turns between 2 players. What I am stuck on is checking through these values for a three of a kind and assigning points .For example, A player presses enter and one appears three times then the player should receive three points or if four appears three times then the player receives the points. I have tried lots of different methods using if statements and for loops but cant seem to get it working. My code is provided below.Any help would be appreciated.
Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dice_v4
{
class Game
{
static void Main(string[] args)
{
Random RandomNum = new Random();
Player[] player1 = new Player[5];
Die[] myDie = new Die[5];
for (int i = 0; i < 5; i++)
{
myDie[i] = new Dice_v4.Die(RandomNum);
player1[i] = new Dice_v4.Player();
}
for (int i = 0; i < 2; i++) // Number of players
{
Console.Write("Enter Name for Player {0}:", i + 1);
string NewName = Console.ReadLine();
player1[i].SetName(NewName);
}
Console.WriteLine();
for (int j = 1; j < 20; j++)
{
for (int i = 0; i < 2; i++)
{
myDie[i].roll();
Console.WriteLine("{0} Rolled:{1} on the first dice", player1[i].GetName(), myDie[i].GetTopNumber());
Console.WriteLine("{0} Rolled:{1} on the second dice", player1[i].GetName(), myDie[i].GetTopNumber1());
Console.WriteLine("{0} Rolled:{1} on the third dice", player1[i].GetName(), myDie[i].GetTopNumber2());
Console.WriteLine("{0} Rolled:{1} on the fourth dice", player1[i].GetName(), myDie[i].GetTopNumber3());
Console.WriteLine("{0} Rolled:{1} on the fifth dice", player1[i].GetName(), myDie[i].GetTopNumber4());
Console.WriteLine("Total Throws:{0}", j);
Console.ReadLine(); }
}
}
}
class Die
{
private int NumberTop1; //attributes
private int NumberTop2;
private int NumberTop3;
private int NumberTop4;
private int NumberTop5;
int threepoints = 0;
private Random RandomNumGenerator;
public Die(Random RandomGenerator) // constructor
{
RandomNumGenerator = RandomGenerator; // initialises random number
}
public void roll()
{
NumberTop1 = RandomNumGenerator.Next(1, 6);
NumberTop2 = RandomNumGenerator.Next(1, 6);
NumberTop3 = RandomNumGenerator.Next(1, 6);
NumberTop4 = RandomNumGenerator.Next(1, 6);
NumberTop5 = RandomNumGenerator.Next(1, 6);
// generates random number / / Number of dice to be rolled
Console.WriteLine("\tTotal score = {0}", threepoints);
}
public int GetTopNumber()
{
return NumberTop1; // Returns number on top which equals dice roll
}
public int GetTopNumber1()
{
return NumberTop2;
}
public int GetTopNumber2()
{
return NumberTop3;
}
public int GetTopNumber3()
{
return NumberTop4;
}
public int GetTopNumber4()
{
return NumberTop5;
}
}
class Player
{
private string Name;
public void SetName(string NewName) // constructor
{
Name = NewName; // initalises name
}
public string GetName()
{
return Name; // Returns name when called
}
}
}
Advice:
Whenever you have variables or properties called something1, something2, ... - you're probably doing something wrong, and you probably want to use a list, array, hashmap...
My idea here would be to add all numbers to a list and then perhaps iterate to make a dictionary where key is the dice value and value is the count. Or you can do something else, depending which format you need for later operations.
List<int> diceValues = new List<int>();
diceValues.Add(die.GetTopNumber());
diceValues.Add(die.GetTopNumber1());
diceValues.Add(die.GetTopNumber2());
diceValues.Add(die.GetTopNumber3());
diceValues.Add(die.GetTopNumber4());
Now that you have them in a list, you can do something like:
var values = new Dictionary<int, int>();
foreach(var item in diceValues) {
if(values.Keys.Contain(item)) {
values[item]++;
} else {
values[item] = 1;
}
}
After this loop you will have a list of Dictionary items where a key will be the dice value, and the value the number of dice with that value.
E.g. if someone threw two threes, and two deuces and one four, the dictionary would look:
Key: 2, Value: 2
Key: 3, Value: 2
Key: 4, Value: 1
By iterating through these you can later make a scoring system...
I would remove these properties all along and use a list or array instead.
You declare a list:
public List<int> Roles { get; private set; }
And your roll method can become:
public void roll()
{
this.Roles = Enumerable.Range(1, 5)
.Select(i => RandomNumGenerator.Next(1, 6))
.ToList();
// Check for three of a kind:
bool threeOfAKind = this.Roles.GroupBy(i => i).Any(g => g.Count() >= 3);
// rest of your logic
Console.WriteLine("\tTotal score = {0}", threepoints);
}
Later you can access each individual roll by this.Roles[numOfRoll]