Creating a c# function to compare int results - c#

This will be so easy for some of you programming geniuses out there but I am a student who recently began learning about C# (and programming in general) and I find myself.... stuck.
This is an assessment I am working on so I am not looking for a copy/paste answer, it would be preferable if I could find out where I am going wrong/where to start so I can fix it myself.
The aim of the assessment is to:
use the random number generator to generate 4 numbers - 2 for player 1 and 2 for the dealer.
Add players 2 numbers together, add dealers 2 numbers together (show results on screen)
this is where I become stuck...
I need to create a function that basically says:
If DealerResult is > PlayerResult display: Dealer Wins.
If PlayerResult > DealerResult, display: You win.
If DealerResult == PlayerResult display: it is a draw.
So far I have the following code. As you will see, I can generate the numbers, add them together and display the results on screen.
using System;
namespace Assessment
{
class MainClass
{
public static void Main (string[] args)
{
//Decalre Variables
Random r = new Random ();
int PlayerNumber1 = r.Next (6, 25);
int PlayerNumber2 = r.Next (6, 25);
int DealerNumber1 = r.Next (6, 25);
int DealerNumber2 = r.Next (6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine ("Welcome!");
Console.ReadLine ();
Console.WriteLine ("Your total is: " + PlayerTotal);
Console.ReadLine ();
Console.WriteLine ("Dealer total is: " + DealerTotal);
Console.ReadLine ();
}
}
}
From here, I am stuck. Suggestions would be so appreciated as to how I should proceed to compare the numbers and display the appropriate result/s through a function.
As mentioned earlier, this is an assessment so I am not looking for a quick fix or final answer. Also, the assessment requires the use of a FUNCTION to generate the result, not a loop or any other type of programming magic that some of you super-geniuses may be aware of. (And I say that with envy - I wish I was half as smart as some of the people I see posting on here). :)

You just need simple if statements, and put them into a function:
private static void DisplayResult(int playerTotal, int dealerTotal)
{
if(playerTotal > dealerTotal)
{
Console.WriteLine("You win!");
}
else if(playerTotal < dealerTotal)
{
Console.WriteLine("Dealer wins!");
}
else
{
Console.WriteLine("Draw!");
}
}
Explanation: We create a function that takes two int parameter.One of them is playerTotal, another is dealerTotal.The function compare these values and display the proper result in the console according to this comparison.After you create your function all you need to do is pass PlayerTotal and DealerTotal variables to your function like this:
DisplayResult(PlayerTotal, DealerTotal);
Note: You should put this method into MainClass

To start you will need a function. Functions look like this:
<access modifier> <return type> <Name> ( <parameters> )
{}
A quick example:
private bool GetResult (int playerValue, int dealerValue)
{
}
What this means is that the function will return a bool, and it takes two int parameters.
To return nothing, return void. To call the function, use its name and pass the parameters inside the parenthesis:
bool result = GetResult(1, 2);
Now to do a comparison, we use the if statement:
if (<expression> <comparator> <expression>)
{}
Another quick example:
if (playerScore > dealerScore)
{
Console.WriteLine("Player wins!");
}
Which says, "If PlayerScore is greater than DealerScore, do what is inside the brace" (a print in this case).
I'm trying to explain the basics, instead of give an actual answer, as you requested. Please let me know if I can clarify anything better, and good luck learning programming in C#!

Another variation demonstrating function returning result as a string.
using System;
namespace Assessment
{
class MainClass
{
public static void Main(string[] args)
{
//Decalre Variables
Random r = new Random();
int PlayerNumber1 = r.Next(6, 25);
int PlayerNumber2 = r.Next(6, 25);
int DealerNumber1 = r.Next(6, 25);
int DealerNumber2 = r.Next(6, 25);
int PlayerTotal = (PlayerNumber1 + PlayerNumber2);
int DealerTotal = (DealerNumber1 + DealerNumber2);
Console.WriteLine("Welcome!");
Console.ReadLine();
Console.WriteLine("Your total is: " + PlayerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.ReadLine();
Console.WriteLine("Dealer total is: " + DealerTotal);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(DisplayResult(PlayerTotal, DealerTotal));
Console.ReadLine();
}
private static string DisplayResult(int playerTotal, int dealerTotal)
{
var result = "An unhandled exception has occured ";
if (playerTotal > dealerTotal)
{
result = "You win!";
}
else if (playerTotal < dealerTotal)
{
result = "Dealer wins!";
}
else
{
result = "Draw!";
}
return result;
}
}
}

Related

c# Roll Dice simulation to return how many times every side landed

My first post on here! I started learning how to program a couple of days ago and have picked up a rolling dice project. I think I have done the main part of it but my problem comes from:
Printing how many times each side came up (maybe store them in an array)?
Bonus: Print out the percentage of times each side appeared (rounded up to 2 decimals)
Keep in mind the times and sides are user input so could be e.g. 50 times x 35 sides.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
namespace Dice_roll
{
class Program
{
static void Main(string[] args)
{
static int getRandomNumber(int min, int max)
{
Random randomRoll = new Random();
lock (randomRoll)
{
return randomRoll.Next(min, max);
}
}
int sides, rollTimes, i;
i = 0;
bool boolCheckSides = false;
bool boolCheckRolls = false;
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
Console.WriteLine("Now select how many times you want it to roll: \n");
do
{
boolCheckRolls = Int32.TryParse(Console.ReadLine(), out rollTimes);
if (boolCheckRolls == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckRolls == false);
do
{
Console.WriteLine("Rolling... " + getRandomNumber(1, sides));
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
int[] arr = new int[rollTimes];
}
}
}
I'm sorry if my code is messy or something, I'm still very beginner.
Well, I assume that your code is not complete yet, so I will just share some opinions of mine.
1- You are adding a method getRandomNumber inside your main function. This method won't compile and should be moved outside the scope of main function. The scope of main function is any code between the curly brackets "{}" shown in the code below
static void main(string[] args){}
just a small side note, try to use Uppercase letters for naming methods in C#, except the main function as that's a naming convention ;-)
2- You did a great job in declaring the variables you need (boolCheckSides, boolCheckRolls, i) before you start assigning them values. However, you also need to declare the Array before using it not after, so your code should look something like this
//Declare the Array
int[] arr = new int[rollTimes];
do
{
int temp = getRandomNumber(1, sides);
Console.WriteLine("Rolling... " + temp);
//Save the value acquired from this roll in the array
arr[i] = temp;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
Then you can easily play around with the array and find the frequency of any number. I would suggest you refer to this post Count the frequency of element of an array in C# if you want to find the short answer, and refer to this post Frequency of Numbers in a 1D Array for the long answer. Just please note that the second post is using C++ language, but it is still showing the same logic though.
3- Just a small advise, please try to avoid "do...while" loops as much as possible. It needs a lot of attention when you write them as they can easily get you into infinite loop.
I suggest you to use a Dictionary, with the side (1 to X) as Key and number of time its appears .
class Program
{
Dictionary<int, int> RollDice = new Dictionary<int, int>();
static void Main(string[] args)
{
:
Console.WriteLine("Welcome to a little dice rolling program.\n Select how many sides you want the dice to have: \n");
do
{
boolCheckSides = Int32.TryParse(Console.ReadLine(), out sides);
if (boolCheckSides == false)
{
Console.WriteLine("Invalid number.. \n");
}
} while (boolCheckSides == false);
//Initialize the dictionary with key and value
for(int i = 1; i<=sides;i++)
RollDice.Add(i, 0);
:
i = 0;
do
{
var value = getRandomNumber(1, sides + 1)
Console.WriteLine("Rolling... " + value);
RollDice[i]++;
i = i + 1;
System.Threading.Thread.Sleep(500);
} while (i < rollTimes);
and you could display your stats by looping over the dictionary:
foreach (var pair in RollDice)
{
Console.WriteLine($"DiceSide:{pair.Key} , appears: {pair.Value}, probability: {(float)pair.Value/(float)rollTimes:0.00}");
}

Increasing length of and passing array C#

I have an assignment that requires us to use arrays and not lists. I have two problems right now; one being that every time the user makes an input, the length of array playerNumber increases by one so I need it to be indefinite and I also need to send the array back to the main method. The code below works only once and when I try to enter a second input the program crashes.
int x = 0;
string answer = "yes";
string[] playerNumber = new string[] {};
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber = new string[] { y };
playerNumber[x - 1] = y;
x++;
Console.Write("Enter another number : ");
answer = Console.ReadLine();
Console.WriteLine();
}
It is not clear what your'e trying to do.
To start with, your index is out of bounds.
Your'e doing: playerNumber[x-1], but x == 0, so you get an exception. This is the only reason your code fails. Note that taking the ++x; one line up will also fail you, since in the second loop, playerNumber is again an array of size 1, but x value is now 2, and your'e again out of bounds.
Secondly, your'e initializing your array both outside and inside the while loop. You have no use of the outer initialization (and maybe there's no need for the inner one - again, depends on what exactly you're trying to achieve).
Thirdly, you should give the user the correct instruction: If you want answer to be yes or no, specify it in your Console.Write.
So if I managed to guess what you were trying to do, here's your code with a few changes, including the usage of Array.Resize (which is very inefficient in this context), and returning the array, as you asked:
using System;
public class Test
{
public static string[] MyFunc()
{
int x = 1;
string answer = "yes";
string[] playerNumber = new string[x];
while (answer == "yes")
{
Console.Write("Enter a number : ");
string y = Console.ReadLine();
playerNumber[x-1] = y;
x++;
Array.Resize(ref playerNumber, x);
Console.Write("Would you like to enter another number? (yes/no)");
answer = Console.ReadLine();
Console.WriteLine();
}
return playerNumber;
}
public static void Main()
{
Console.WriteLine(MyFunc()[0]); // prints the first string
}
}

How do I loop a function in c#?

I have been given this question, in my computer science class, and I cannot figure out how to answer it.
Question:
•Create a procedure called tossCoins with one integer parameter - numTosses
•Inside your tossCoins procedure, call your tossCoin function from challenge #5
numTosses times. So for example if we enter tossCoins(50), the tossCoin function will be called 50 times.
•Your tossCoins procedures should then print out the number of times that the coin landed on heads and the number of times the coin landed on tails
•Extend your main program, so that the user can choose how many times to toss the coin
I have already created the tossCoin function, but cannot figure out how to run it the amount of times the user asks, or how to create a tally of heads and tails.
This is the code I have so far:
static void Main(string[] args)
{
Random rnd = new Random();
Console.WriteLine(tossCoin(rnd));
Console.Write("Please enter a number: ");
int numTosses = Convert.ToInt16(Console.ReadLine());
Console.ReadLine();
}
static string tossCoin(Random rnd)
{
int num = rnd.Next(1, 3);
string heads = "Heads";
string tails = "Tails";
if(num == 1)
{
return heads;
}
else
{
return tails;
}
}
static void tossCoins(int numTosses)
{
int headsTally = 0;
int tailsTally = 0;
for(int i = 0; i < numTosses; i++)
{
string outcome = tossCoin(rnd);
numTosses--;
if(outcome == heads)
{
headsTally++;
}
else
{
tailsTally++;
}
}
}
}
If anyone can help, it would be great, as I am trying to learn the different rules of using functions, and procedures. Thanks, Leighton.
A couple things, first it looks like you've almost got it. You just need to call your tossCoins() function in your main method. Second, you don't need to decrement numTosses in your for loop, ie. remove the line numTosses--;
EDIT: as Tommy said, the statement outcome == heads wont compile since heads isn't defined. Either replace heads with "Heads" or define it earlier in the function. And yea you might want to return/print the result.

Combination by using factorial function method

I cannot combinate 20 and 17, the program says that the result is 1. Why?? I'm sure my code is right but i just cannot combinate big numbers.
using System;
namespace question
{
class beat_That
{
static int Factorial(int m)
{
int result = 1;
for (int i = 1; i <= m; i++)
{
result *= i;
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine("enter number of objects in the set: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter number to be chosen: ");
int k = Convert.ToInt32(Console.ReadLine());
int combination = Factorial(n) / (Factorial(n - k) * Factorial(k));
Console.WriteLine("C(" + n + ", " + k + ") = " + combination);
Console.ReadKey();
}
}
}
I'm guessing this is a homework assignment? Here are some tips that will hopefully get you going in the right direction:
(1) Typically, .NET classes are Pascal Case, so for example: comb should be Comb. Also, it's better to assign descriptive class names instead of short abbreviations. For clarity I'm going to assume you at least rename comb to Comb so it isn't confused with a variable name, but another option might be Calculator for example.
(2) Check your syntax and any compiler errors. For example, the compiler should be complaining about this line of code:
Console.WriteLine("the combination of {0} and {1} is {2}. "),a1,b1,;
(3) Your methods Factorial and Combination are static methods (as opposed to instance methods). This changes how you call these methods. Static methods are called without an instance, for example: Comb.Combination(..)
(4) Make sure you test various inputs! Your implementation of Combination is not quite correct, but I'll leave that as an exercise to figure out why.

Alphabetizing Arrays

So I'm having a couple of troubles with my code. For starters, I have this problem which is outputting all of the arrays. Mind you I have only been coding for 12 days and my teacher has somewhat skipped over the very basics in C# coding due to my college's outlook on learning. AND I just learned that it doesn't order them alphabetically.....
static int inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
pl[i] = Console.ReadLine();
}
while (pl[i++].CompareTo("Q") != 0);
//if they write Q for the player it will quit
return i - 1;
}
static void Main(string[] args)
{
String[] players = new String[100];
Array.Sort(players);
// Sort array.
//defines players in this new instance
var count = inputPartInformation(players);
//for the portion of the code that handles the input
//calculates the average score
Console.WriteLine("List of People in Order: {0}, {1}, {2}, {3}, {4}, {5}, {6},", players);
Console.ReadLine();
}
}
}
You are sorting before the names are populated; that does nothing.
You are printing a single item using a fixed multi-item list of parameter references {0}, {1},{2} and so on; it is not going to work, and even if it did it would limit your output to the first seven items
You do not know how many items to sort. Change void inputPartInformation(string[] pl) to return count (which is i-1), and use Array.Sort(players, 0, count);
The simplest way to convert multiple strings into a single string is by using string.Join:
Console.WriteLine("List of People in Order: {0}", string.Join(", ", players.Take(count)));
First, "Q" is being added to the input list because you don't test for "Q" until after the input has been accepted and inserted into your array. One way of reworking this would be to hold the input name into a temporary variable, test that for "Q", and add it to your array only if it is something else. Within your loop, modify your input/test to something like:
bool enteringNames=true;
do{
String nextName = Console.ReadLine();
if (nextName.CompareTo("Q")==0)
{
enteringNames=false;
}
else
{
p[i]=nextName;
}
i++;
}
while(enteringNames);
This is just one way of getting the job done. Keep in mind that a fixed 100-entry array isn't the most robust way of doing this...never know how many names might be going in!
Now, the last WriteLine is a bit odd, but I think you can figure that part out on your own - its pretty straightforward to either iterate through the array, or just join all the strings together :)
Second, your sort isn't working because you call Array.Sort(players) before you call inputPartInformation(players) to actually load the data - so you're sorting without any data!. Move the Array.Sort call after the call to inputPartInformation.
Hope this helps!
Try this, it will work, but first try to study about the APIs
static int inputPartInformation(string[] pl)
{
int i = 0;
String temp;
while (true)
{
Console.Write("Enter a Name: ");
temp=Console.ReadLine();
if (temp=="Q")
break;
else pl[i++] = temp;
}
return i;
}
static void Main(string[] args)
{
String[] players = new String[100];
int size=inputPartInformation(players);
for (int i = 0; i <= size; i++)
Console.WriteLine(players[i]);
}
}
Q is appearing in your outcome because you are assigning it to your array.
Rewrite you function to check the value before you assign it, for example
static void inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
newStrInput = Console.ReadLine();
if (newStrInput == "Q")
break;//if they write Q for the player it will quit
pl[i]=newStrInput;
i++;
}
while (i>-1);//infinite loop
}

Categories