I'm having issues with passing array values. I've been working on this for hours and can't seem to find the answer. wonder if someone can point me in the right direction. This is what I have so far. I've looked at countless examples, videos and reading material and can't seem to come up with the solution. I would really appreciate the help.
static void Main(string[] args)
{
int Seed = 0;
int[] random = new int[10];
int[] input = new int[10];
for (int x = 0; x < random.Length; x++)
{
Seed = (int)DateTime.Now.TimeOfDay.Ticks;
random[x] = getRnd(Seed);
}
for (int x = 0; x < input.Length; x++)
{
Console.Write("Enter an integer number between 1 and 100: ");
input[x] = Convert.ToInt32(Console.ReadLine());
}
int inputnumber=input[0];
for (int x = 0; x < input.Length; x++)
if (inputnumber <= random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is less than " + random[x]);
}
else if (inputnumber >= random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is greater than " + random[x]);
}
else if (inputnumber == random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is equal to " + random[x]);
}
}
static int getRnd(int Seed)
{
Random myrandomnum = new Random(Seed);
int randomvalue = myrandomnum.Next(1, 100);
return randomvalue;
}
}
}
I need it to print like this.
Enter an integer number between 1 and 100: 1
Enter an integer number between 1 and 100: 8
Enter an integer number between 1 and 100: 44
Enter an integer number between 1 and 100: 22
Enter an integer number between 1 and 100: 16
Enter an integer number between 1 and 100: 88
Enter an integer number between 1 and 100: 41
Enter an integer number between 1 and 100: 77
Enter an integer number between 1 and 100: 10
Enter an integer number between 1 and 100: 52
The entered number 1 is less than 64
The entered number 8 is less than 44
The entered number 44 is less than 80
The entered number 22 is less than 91
The entered number 16 is less than 95
The entered number 88 is greater than 39
The entered number 41 is less than 79
The entered number 77 is greater than 27
The entered number 10 is less than 35
The entered number 52 is less than 65
Press any key to continue . . .
But I'm getting this:
Enter an integer number between 1 and 100: 1
Enter an integer number between 1 and 100: 8
Enter an integer number between 1 and 100: 44
Enter an integer number between 1 and 100: 22
Enter an integer number between 1 and 100: 16
Enter an integer number between 1 and 100: 88
Enter an integer number between 1 and 100: 41
Enter an integer number between 1 and 100: 77
Enter an integer number between 1 and 100: 10
Enter an integer number between 1 and 100: 52
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
The entered number 1 is less than 64
Press any key to continue . . .
There are two problems - one explaining why you're only using the first input number, and one explaining why you're only comparing it against one random number.
For the random number part, here's the problem:
Seed = (int)DateTime.Now.TimeOfDay.Ticks;
random[x] = getRnd(Seed);
...
static int getRnd(int Seed)
{
Random myrandomnum = new Random(Seed);
Unless DateTime.Now.TimeOfDay.Ticks changes between iterations - which is very unlikely, as the system clock resolution is usually in the order of milliseconds, and you're not doing a lot of work between iterations - you're creating multiple instances of Random, all with the same seed. That means you'll get the same sequence of random numbers from each instance - but you're actually only asking for one number from each instance anyway.
The solution is to create a single Random instance, and then use that for every random number you generate.
Random rng = new Random();
for (int x = 0; x < random.Length; x++)
{
random[x] = GenerateRandomValue(rng);
}
...
static int GenerateRandomValue(Random random);
{
int randomvalue = random.Next(1, 100);
return randomvalue;
}
Of course at that point you may consider removing the method entirely, and using:
Random rng = new Random();
for (int x = 0; x < random.Length; x++)
{
random[x] = random.Next(1, 100);
}
You might also want to consider using random.Next(1, 100) if you want a value between 1 and 100 inclusive - the second argument to Random.Next is an exclusive upper bound.
Note that this approach to creating a single instance of Random doesn't play well in a multi-threaded scenario, as Random isn't thread-safe. Fortunately that's not a problem here, but see my article on Random for more information if you need it later.
For the "only using a single input value" problem, LaD1Da's answer goes into more detail, but the issue is that inputNumber is always input[0]... you're never using input[1], input[2] etc.
I have not enough 'Reputation' to simply add a comment:
The issue is that you do not change the inputnumber in your last loop. You always use input[0]. Simply change the last loop to the following:
for (int x = 0; x < input.Length; x++)
int inputnumber = input[x]; // This is new
if (inputnumber <= random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is less than " + random[x]);
}
else if (inputnumber >= random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is greater than " + random[x]);
}
else if (inputnumber == random[x])
{
Console.WriteLine("The entered number " + inputnumber + " is equal to " + random[x]);
}
}
Edit: Additionally you have an issue with your random number generation. Refer to Jon Skeet's answer for that.
There are two problems.
The first problem is in getRnd(). On each iteration of the loop you are passing a new seed, but the loop is executing so fast that it is likely that the number of Ticks will be the same on each iteration. You can fix this by moving the seeding outside of the loop, and passing the Random generator as a parameter to the getRnd() function:
Seed = (int)DateTime.Now.TimeOfDay.Ticks;
Random rand = new Random(Seed);
for (int x = 0; x < random.Length; x++)
{
random[x] = getRnd(rand);
}
The second problem is in your loop. On this line:
int inputnumber=input[0];
You assign the value in input[0] to inputnumber. However, you never change it on future iterations of the loop. You can fix this by iterating through input[] at each loop iteration, i.e.:
for (int x = 0; x < input.Length; x++)
{
if (input[x] <= random[x])
{
Console.WriteLine("The entered number " + input[x] + " is less than " + random[x]);
}
else if (input[x] >= random[x])
{
Console.WriteLine("The entered number " + input[x] + " is greater than " + random[x]);
}
else if (input[x] == random[x])
{
Console.WriteLine("The entered number " + input[x] + " is equal to " + random[x]);
}
}
Related
Hi I am sick of searching I could not find the exact code for my question.
I need to code the sum of the odd numbers from 1 to 100
and sum of the even numbers from 2 to 100.
This is what i have so far.
Thank you so much
// 1) using for statement to Sum Up a Range of values using Interactive
Console.WriteLine(" Sum Up a Range of values entered by User ");
Console.WriteLine();
// 2) Declare the Variables to be used in the Project
string strFromNumber, strToNumber;
int fromNumber, toNumber;
int sum = 0;
int i, even = 0, odd = 0;
int[] array = new int[10];
// 3) Prompt the User to Enter the From Number to Sum From
Console.Write("Enter the From Number to Sum From: ");
strFromNumber = Console.ReadLine();
fromNumber = Convert.ToInt32(strFromNumber);
// 4) Prompt the User to Enter the To Number to Sum To
Console.Write("Enter the To Number to Sum To: ");
strToNumber = Console.ReadLine();
toNumber = Convert.ToInt32(strToNumber);
// 5) Use for statement to Sum up the Range of Numbers
for (i = fromNumber; i <= toNumber; ++i)
{
sum += i;
}
if //(array[i] % 2 == 0) //here if condition to check number
{ // is divided by 2 or not
even = even + array[i]; //here sum of even numbers will be stored in even
}
else
{
odd = odd + array[i]; //here sum of odd numbers will be stored in odd.
}
Console.WriteLine("The Sum of Values from {0} till {1} = {2}",
fromNumber, toNumber, sum);
Console.ReadLine();
There is no need to write the complex code which you have written.
Problem is to calculate the sum of arithmetic progression. The formula to find the sum of an arithmetic progression is Sn = n/2[2a + (n − 1) × d] where, a = first term of arithmetic progression, n = number of terms in the arithmetic progression and d = common difference.
So in case of odd numbers its a = 1, n = 50 and d = 2
and in case of even numbers its a = 2, n = 50 and d = 2
and if you try to normalize these above formulas, it will be more easy based on your problem.
the sum of the first n odd numbers is Sn= n^2
the sum of the first n even numbers is n(n+1).
and obviously, it's very simple to loop from ( 1 to 99 with an increment of 2 ) and ( 2 to 100 with an increment of 2 )
In the simplest case, you can try looping in fromNumber .. toNumber range while adding
number either to even or to odd sum:
// long : since sum of int's can be large (beyond int.MaxValue) let's use long
long evenSum = 0;
long oddSum = 0;
for (int number = fromNumber; number <= toNumber; ++number) {
if (number % 2 == 0)
evenSum += number;
else
oddSum += number;
}
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
Note, that you can compute both sums in one go with a help of arithmetics progression:
private static (long even, long odd) ComputeSums(long from, long to) {
if (to < from)
return (0, 0); // Or throw ArgumentOutOfRangeException
long total = (to + from) * (to - from + 1) / 2;
from = from / 2 * 2 + 1;
to = (to + 1) / 2 * 2 - 1;
long odd = (to + from) / 2 * ((to - from) / 2 + 1);
return (total - odd, odd);
}
Then
(long evenSum, long oddSum) = ComputeSums(fromNumber, toNumber);
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
From the code snippet you shared, it seems like the user gives the range on which the sum is calculated. Adding to #vivek-nuna's answer,
Let's say the sum of the first N odd numbers is given by, f(n) = n^2 and
the sum of the first N even numbers is given by, g(n) = n(n + 1).
So the sum of odd numbers from (l, r) = f(r) - f(l - 1).
Similarly, the sum of even numbers from (l, r) = g(r) - g(l - 1).
Hope this helps.
I need some help with the for-loop. I'm trying to sum up every fifth number that I type in, instead it sums them all up. What do I have to change?
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
for (count = 0; count <= 0; count += 5)
{
total = total + input;
}
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Assuming that you enter a list of numbers, and the 1st number and every five afterwards is added (so 1st, 6th, 11th, etc.):
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
if (count % 5 == 1)
total = total + input;
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
This works by using the modulo operator (%). The modulo operator returns the remainder of a division operation involving the number you specify.
In the code if (count % 5 == 1), the question is:
Is the remainder of count divided by 5 equal to 1?
If so, it adds the number. If not, it is skipped
The reason the remainder is one is because we want results 1, 6, 11, etc:
1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1
If you change the modulo value to 0 it will return the results at position 5, 10, 15, etc.
You could just store the numbers in a list and calculate it at the end:
var numbers = new List<int>();
Console.Write("Enter your number: ");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
numbers.Add(input);
input = int.Parse(Console.ReadLine());
}
var total = numbers.Where((x, i) => (i + 1) % 5 == 0).Sum(); // i + 1 since indexes are 0-based.
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
You can try this:
double total = 0;
int passover = 4;
int input = 0;
do
{
passover++;
Console.Write("Enter your number: ");
int.TryParse(Console.ReadLine(), out input);
if ( passover != 5 ) continue;
passover = 1;
total = total + input;
}
while ( input != 0 );
Console.WriteLine("The sum of every fifth numbers is: {0}", total);
Console.ReadKey();
I think the best way is to recover all the values before making the sum, this code works:
double total = 0;
int input = -1;
List<int> allInput = new List<int>();
while (input != 0)
{
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
allInput.Add(input);
}
for (int i = 0; i < allInput.Count()-1; i += 5)
{
total = total + allInput[i];
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Your sample would go forever, because there is no break point in your loop. You should always put a break point in your loop, otherwise it'll loop indefinitely.
Here is what you need :
int total = 0;
int count = 0;
Console.Write("Enter your number: ");
while (true)
{
int input = 0;
bool isNumber = int.TryParse(Console.ReadLine(), out input);
if (isNumber)
{
count++;
if (count % 5 == 0)
total += input;
}
else
{
break;
}
Console.Write("Add another number or press enter to get the sum : ");
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
So, you'll need first to put the user input inside a loop, and keep asking the user for adding another number until hits the condition where you close this loop. In the example, I decided to break the loop if the user typed anything not a number. but I told the user to press enter to get the some, to end the loop. For you, you'll need to translate that to your application breakpoint, how would you want the user to get the sum ?. Then, change the condition to your logic, so it breaks the loop and gets the sum.
another point is that int.TryParse. When you want to convert strings to numbers (int, long, decimal ..etc). You should always use `TryParse, this will verify the number, if the conversion failed, it'll return false. This way you can maintain the conversion and do something about it.
Given a coin game: you start with a dollar and a coin is flipped. If it's heads the dollar is doubled, if it's tails the game ends. However if head's is flipped again the payoff is now quadrupled and if head is flipped 3 times 8x and so on. The paradox is that the expect value is 1/2*1+1/4*2+1/8*4... = infinity.
So you if you play the game long enough you should be getting progressively richer. Monte carlo simulation suggests not.
This is simulation of the famous St. Petersburg Paradox
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sorrow
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random(Environment.TickCount);
double totalSum = 0;
int bigWins = 0;
double iterations = 1000;
for (int z = 0; z < 10; z++)
{
iterations *= 10;
for (double i = 1; i < iterations; i++)
{
int sum = 1;
int a = 1;
while (a == 1)
{
//generate a random number between 1 and 2
a = rnd.Next(1, 3);
if (a == 1)
{
sum *= 2;
}
if (sum > 8000&&sum<12000)// given discrete probability landing 13 times
{
// if the sum is over 8000 that means that it scored 1 13 times in a row (2^13) - that should happen
//once every 8192 times. Given that we run the simulation 100 000 000 times it should hover around
// 100 000 000/8192
//However is much , much bigger
bigWins++;
}
}
totalSum += sum;
}
Console.WriteLine("Average gain over : "+iterations+" iterations is:" + totalSum / iterations);
Console.WriteLine("Expected big wins: " + iterations / 8192 + " Actual big wins: " + bigWins);
Console.WriteLine();
}
}
}
}
As you can see we should expect 7 times smaller number. This makes me think that perhaps c# random is prone to choosing the same number over and over again?
Is it true or there is something wrong with my code?
How might I fix the issue?
You have two bugs. Your loop starts after a win, so the chance of a big win is 1/2^12, and you keep incrementing bigwins for additional wins after 12.
Try
static void Main(string[] args)
{
Random rnd = new Random(Environment.TickCount);
double iterations = 1000;
for (int z = 0; z < 10; z++)
{
double totalSum = 0;
int bigWins = 0;
iterations *= 10;
for (double i = 1; i < iterations; i++)
{
int sum = 2;
int a = 1;
while (a == 1)
{
//generate a random number between 1 and 2
a = rnd.Next(1, 3);
if (a == 1)
{
sum *= 2;
}
if (sum > 8000)
{
// if the sum is over 8000 that means that it scored 1 12 times in a row (2^12) - that should happen
//once every 4096 times. Given that we run the simulation 100 000 000 times it should hover around
// 100 000 000/4096
bigWins++;
break;
}
}
totalSum += sum;
}
Console.WriteLine("Average gain over : " + iterations + " iterations is:" + totalSum / iterations);
Console.WriteLine("Expected big wins: " + iterations / 4096 + " Actual big wins: " + bigWins);
Console.WriteLine();
}
Console.ReadKey();
}
outputs something like:
Average gain over : 10000 iterations is:12.6774
Expected big wins: 2.44140625 Actual big wins: 1
Average gain over : 100000 iterations is:14.09468
Expected big wins: 24.4140625 Actual big wins: 21
Average gain over : 1000000 iterations is:14.022718
Expected big wins: 244.140625 Actual big wins: 249
Average gain over : 10000000 iterations is:14.0285748
Expected big wins: 2441.40625 Actual big wins: 2456
Average gain over : 100000000 iterations is:14.00012582
Expected big wins: 24414.0625 Actual big wins: 24574
Average gain over : 1000000000 iterations is:14.000105548
Expected big wins: 244140.625 Actual big wins: 244441
Average gain over : 10000000000 iterations is:13.9990068676
Expected big wins: 2441406.25 Actual big wins: 2440546
What you are looking for is the probability that the game gets to or continues past $8000 which is 1 minus the sum of the probabilities of ending before $8000
Probability of ending after...
0 rounds 1/2 $2
1 round 1/4 $4
2 rounds 1/8 $8
3 rounds 1/16 $16 (same as 1/(2^(rounds+1))
...
12 rounds 1/2^13 $8192 (in your code you are off by one round, you get to $8192 after 12 wins, not 13
sum all of the probabilities of ending before $8192 and you get 0.999755859
So... your probability of a game getting to at least $8192 is 1-0.999756 or 0.000244141
Compare this to the probability of 1/8192 = 0.0001220703125 and you see you are off by about a factor of 2.
This doesn't change the fact that Random isn't a good approximation of random, and your expected results will still be off.
If you want to use RNGCryptoServiceProvider you can do the following
initialize a RNGCryptoServiceProvider somewhere in your class
RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
Then where you are assigning the value a you can do the following
//generate a random number between 1 and 2
//allocate an array of bytes to be populated by rngCsp
byte[] randomNumber = new byte[1];
//populate the array with a random byte
rngCsp.GetBytes(randomNumber);
//if the random byte is [0,125] return 1 and if [126,255] return 2
a = randomNumber[0] < 126 ? 1 : 2;
If you are interested in calculating the count of how many times a sequence of 13 or more ones occur, the below code may be of interest to you. It may not be as fast as the original code, but I think it may be slightly easier to read and understand (which I think is important, but because part of the reason why it took so long to spot the bugs in the original code was that it was a little hard to follow the logic). Basically, it keeps a queue of the last 13 items, and checks whether they are all 1.
Note that the calculation I have used to determine the expected number of sequences is also different to yours. I don't just divide by 8192, instead I do (iterations - (iterations * (1 - (1m/8192m)))). I don't think that calculation is 100% right, but it is more accurate than the original.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp4
{
internal class Program
{
private static void Main(string[] args)
{
var queue = new Queue<int>();
var rnd = new Random(Environment.TickCount);
int bigWins = 0;
long iterations = 10000000;
const int sequenceLength = 13;
double probability = 1 / Math.Pow(2, sequenceLength);
for (int z = 0; z < iterations; z++)
{
var a = rnd.Next(1, 3);
queue.Enqueue(a);
if (queue.Count == sequenceLength)
{
if (queue.Distinct().Count() == 1 && queue.First() == 1)
{
bigWins++;
}
queue.Dequeue();
}
}
Console.WriteLine("Expected big wins: " + (iterations - (iterations * (1 - probability))) + " Actual big wins: " + bigWins);
Console.ReadLine();
}
}
}
find numbers in an input range that are evenly divisible by 3. Only =, ++, -- operators can be used.
I've tried to get the remainder using shift operators and other loops but I always require a -= or something similar.
Console.Clear();
int n,
d,
count = 1;
// get the ending number
n = getNumber();
// get the divisor
d = 3;// getDivisor();
Console.WriteLine();
Console.WriteLine(String.Format("Below are all the numbers that are evenly divisible by {0} from 1 up to {1}", d, n));
Console.WriteLine();
// loop through
while (count <= n)
{
// if no remainder then write number
if(count % d == 0)
Console.Write(string.Format("{0} ", count));
count++;
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to try again. Press escape to cancel");
Expected results:
Enter the ending number: 15
Below are all the numbers that are evenly divisible by 3 from 1 up to 15
3, 6, 9, 12, 15
If the == operator is permitted for the assignment, you can have something like
int remainder = 0; // assumes we always count up from 1 to n, we will increment before test
Inside the loop replace the existing if with
remainder++;
if (remainder == 3) {
Console.Write(string.Format("{0} ", count));
remainder = 0;
}
[EDIT: Typo in code corrected]
Think about the underlying maths:
2 x 3 = 3 + 3
3 x 3 = 3 + 3 + 3
4 * 3 = 3 + 3 + 3 + 3
...and so on.
Also, to be evenly divisible by 3 means that the number multiplying 3 must be even.. So...
public bool EvenlyDivisibleBy3(int aNumber)
{
int even = 2;
int currentMultiple = 0;
while (currentMultiple < aNumber)
{
int xTimes = 0;
for (int x = 1; x <= even; x++)
{
((xTimes++)++)++; // add three to xTimes
}
currentMultiple = xTimes;
(even++)++: // next even number
}
return currentMultiple == aNumber;
}
Alright so I am making a program to verify a 4 digit code.
The computer generates a 4 digit code
The user types in a 4 digit code. Their guess.
the computer tells them how many digits are
guessed correctly in the correct place and how many digits have
been guessed correctly but in the wrong place.
The user gets 12 guesses to either win – guess the right code. Or
lose – run out of guesses.
So basically, my program doesn't seem to actually verify whether the code is correct but i cant see why not because i have if and for loops for verification, please take a look.
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int DigitOne = random.Next(0, 10);
int DigitTwo = random.Next(0, 10);
int DigitThree = random.Next(0, 10);
int DigitFour = random.Next(0, 10);
byte[] code = new byte[4];
code[0] = Convert.ToByte(DigitOne);
code[1] = Convert.ToByte(DigitTwo);
code[2] = Convert.ToByte(DigitThree);
code[3] = Convert.ToByte(DigitFour);
bool CodeCorrect = false;
Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3] );
Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while (AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
for (int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
}
if (UserCode.Length != 4)
{
Console.WriteLine("Error. Try Again.\n");
}
else
{
int UserDigitOne = UserCode[0];
int UserDigitTwo = UserCode[1];
int UserDigitThree = UserCode[2];
int UserDigitFour = UserCode[3];
for (int i = 0; i < 4; i++)
{
if (UserCode[i] == code[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
}
}
if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if (AmountOfGuesses > 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
If you step through the code after it generated the number 1246, and then input the same number from the command line, convert it to a char array, then convert each char to a byte, you'll get the following four bytes:
49 50 52 54
These correspond to the ASCII representations of each char, NOT the actual numbers.
Try something like this:
int[] input = new int[4];
for(int i = 0; i < 4; i++ )
{
input[i] = Convert.ToInt32(Console.Read()) - 48;
}
The -48 should turn your ASCII code into the actual numerical representation that was provided. Console.Read() reads individual characters rather than the full line.
Also, you don't have to say:
CodeCorrect == false
This is more simply represented as:
!CodeCorrect
Similarly, if it was set to true, it would just be:
CodeCorrect
I also suggest using a for loop to set multiple elements in an array rather than manually writing out each line of code. It's not a big deal for small arrays, but it's good practice.
UPDATE: Here's a revised version of the full program:
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int[] randCombination = new int[4];
for (int i = 0; i < 4; i++)
{
randCombination[i] = random.Next(0, 10);
Console.Write(randCombination[i].ToString());
}
bool CodeCorrect = false;
Console.WriteLine("\nYou have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while(AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
string input = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(input, out n);
int correctCount = 0;
if(input.Length != 4 || !isNumeric)
{
Console.WriteLine("Error. Input code was not a 4 digit number.\n");
}
else
{
for(int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(input[i]) - 48;
if(UserCode[i] == randCombination[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
correctCount++;
}
}
if(correctCount == 4)
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if(AmountOfGuesses >= 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
}
A couple of things were changed:
Added a for loop at the top that generates a random number, enters it into an array of ints and then prints it to standard output.
I changed the way user input is read back to the Console.ReadLine(). The reason for this is to check if the user inputted a four digit integer. the int.TryParse statement makes sure the input is an int, and the Length property checks the length.
I also used a counter to count each correct guess. If 4 correct digit guesses were made, the safe is unlocked.
Your final if statement would never have evaluated because Amount of Guesses would equal 12, not be greater than it. Changed it to >= from >. Always be on the lookout for small things like this.
EDIT #2: For more information on int.TryParse, see the following:
http://www.dotnetperls.com/int-tryparse
How the int.TryParse actually works
You are comparing numbers with the character representation of a number. Each value of code[] represents an actual number. You then compare those values with the values in UserCode which is a string, meaning there is a character at each index. It is never the case that ((byte)'4') == ((byte)4) (using 4 as an example, but works for any numerical digit).
One way around this is to parse each user input character into a byte using the byte.Parse method.
For fun learning purposes look at the output from the following code:
for (char i = '0'; i <= '9'; i++)
{
Console.WriteLine("char: " + i + "; value: " + ((byte)i));
}
The output is actually:
char: 0; value: 48
char: 1; value: 49
char: 2; value: 50
char: 3; value: 51
char: 4; value: 52
char: 5; value: 53
char: 6; value: 54
char: 7; value: 55
char: 8; value: 56
char: 9; value: 57
This is due to string encoding.
I would also recommend that one you have your code working that you submit it to the fine folks at the Code Review site to review other aspects of the code which could use work.