While Loop in C# - c#

I want to exit from a loop when both i and j have the value 6, but it exits when one of them has the value 6.
int i,j,k;
i=k=0;
j=1;
Random num = new Random();
Console.WriteLine("Please Press any Key to Roll");
while((i!=6)&&(j!=6))
{
Console.ReadKey();
i= num.Next(0,7);
j= num.Next(0,7);
Console.WriteLine("1st Rolled Number is: "+ i);
Console.WriteLine("2st Rolled Number is: "+ j);
k++;
}
Console.WriteLine("Your have achieved it in "+ k + " Atempts");

To exit the loop when both i and j have the value 6, you can change the condition in the while loop to
Change too
while ((i != 6) || (j != 6))
This will exit the loop when either i or j. To exit the loop when both i and j have the value 6,
while (!(i == 6 && j == 6))
This will exit the loop when both i and j have the value 6.

In other words, the loop should continue if either i isn't 6 or j isn't 6 - this is a logical or (||) condition, not a logical and (&&) condition:
while ((i != 6) || (j != 6))

an alternative approach can be
while(true)
{
Console.ReadKey();
i = num.Next(0, 7);
j = num.Next(0, 7);
Console.WriteLine("1st Rolled Number is: " + i);
Console.WriteLine("2st Rolled Number is: " + j);
k++;
if (i == 6 && j == 6) break;
}
Console.WriteLine("You have achieved it in " + k + " attempts");

Related

Why does not while loop stop?

int Coins = 27;
int playersInput =0;
int counter = 0;
while (Coins >= 0) {
Console.WriteLine("There are " + (Coins - playersInput) + " in the bag" + "\n");
Console.WriteLine("Turn #" + (counter + 1));
playersInput += Convert.ToInt32(Console.ReadLine());
if (playersInput % 2 == 0) {
Console.WriteLine("Player 0 turn");
} else {
Console.WriteLine("Player 1 turn");
}
counter++;
}
Console.WriteLine("The last player lost this game");
The code has to alternate between two players and if the coins value reaches to 0 it has to print the console.writeline that is outside the while loop and I don't want to use break.
You never update Coins and the number of coins left in the jar is Coins - playersInput.
while ((Coins - playersInput) >= 0)

C# Multiplication Pattern for-loop. Need to figure out how to configure the header of a table of numbers that multiplies each time

Here is the problem: Write a C# program that uses looping to print the following table of values
N 10*N 100*N 1000*N
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000
[Update 1] Originally I could not figure out how to get the top left corner (i==0) to be 'N', thank you to the user who pointed out that solution (added in answers below)
What I currently have is this:
0 100*N 100*N 100*N
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000
[Update 2] Next I had the issue after reorganizing my code to get all the top headers to show 10* N, 100* N, 1000* N. I thought I should use some math equation to do it but instead opted for a literal string. (Maybe there is a better method of doing this?)
Here is my source code:
Console.Write("Display the exponent table:\n");
Console.Write("-----------------------------------");
Console.Write("\n\n");
for (int i = 0; i <= 5; i++)
{
Console.Write(i + "\t");
for (int j = 1; j <= 3; j++)
{
if (i == 0) Console.Write((i + 10) * 10 + "*N" + "\t");
else if (j == 1) Console.Write((i * 10) + "\t");
else if (j == 2) Console.Write((i * 100) + "\t");
else if (j == 3) Console.Write((i * 1000) + "\t");
else Console.Write("\t");
}
Console.Write("\n");
This is an introductory course, so I have not learned more advanced methods of solving this type of problem. It must be solved using basic loops and not more advanced math functions.
Thanks!
When the first case of a loop needs to be specialized somehow, it's usually easiest to check the indices and specialize the code in that case. (Not having seen your code) in this case, that would look something like:
if (i == 0 && j == 0)
cell = "N"; // first cell has a different format
It doesn't pay to try being too clever unless the simple solution would make errors or misunderstanding more likely. A comment is good when you need to break a pattern in a way that might be unexpected for someone else reading the code.
Here is also a nice solution:
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 3; j++)
{
if(i == 0) Console.Write("N" + (j > 0 ? "*" + Math.Pow(10,j) : "") + "\t");
else Console.Write(i * Math.Pow(10,j) + "\t");
}
Console.Write("\n");
}
In your solution, your inner loop has no big benefit. You could also write just the Console.Write without the if checks and without the inner loop. To get from 1 -> 10, 2 -> 100, 3 -> 1000 and so on, you have to calculate 10^j, or in C# Math.Pow(10, j). This solution is easier to extend if you want to add another column.
Here is the solution I came up with to solve the table of numbers. Thanks, u/piojo for the help!
It is a very basic/literal solution, but the assignment is only intended to use basic looping methods.
If there is an improved or condensed solution other than this, I'd love to see alternative methods.
[SOLUTION]
Console.Write("Display the exponent table:\n");
Console.Write("-----------------------------------");
Console.Write("\n\n");
for (int i = 0; i <= 5; i++)
{
if (i==0) Console.Write("N\t10*N\t100*\t1000*N\t");
else Console.Write(i + "\t");
for (int j = 1; j <= 3; j++)
{
if (i == 0) Console.Write(" ");
else if (j == 1) Console.Write((i * 10) + "\t");
else if (j == 2) Console.Write((i * 100) + "\t");
else if (j == 3) Console.Write((i * 1000) + "\t");
else Console.Write("\t");
}
Console.Write("\n");

Number Guessing Game in c#

I'm working on Visual Studio about binary search in c#. My project about the computer find the user's guess number. So, I use tihs code in the main;
int min = 0; // minimum number in the array
int max = 100; // maximum number in the array
int middle = 50; // middle number in the array
int counter = 1;
string name, input;
int guess_number;
Console.WriteLine("Hello, this is a game that finding the number of in your mind. If you want to play so let me know you! ");
name = Console.ReadLine();
Console.WriteLine("Awesome welcome to the game " + name + " guess a number between " + min + " and " + max + " Please! ");
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(" You select " + guess_number + " so, ");
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);
Console.ReadKey();
However, output always repeat after the user write anything, why the reason about that, is there anyway to get the number?
from your description, I think you need to let user input new value to guess_number variable in the loop end otherwise the loop will not end from the condition guess_number != 0.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
Console.WriteLine(counter + " times I tried for finding your number ");
input = Console.ReadLine(); // let user key in new value.
guess_number = Convert.ToInt32(input);
} while (guess_number != 0);
the last readKey should be inside the while.
do
{
counter += 1;
if (guess_number == 2)
{
min = middle + 1;
}
else if (guess_number == 1)
{
max = middle - 1;
}
else if (guess_number != 1 || guess_number != 2 || guess_number != 0)
{
Console.WriteLine(" Please write 0, 1 or 2 " + name);
}
middle = (min + max) / 2;
Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!");
input = Console.ReadLine();
guess_number = Convert.ToInt32(input);
Console.WriteLine(counter + " times I tried for finding your number ");
} while (guess_number != 0);

Testing if a list of integer is odd or even

Trying to determine if my list of integer is made of odd or even numbers, my desired output is a list of true an/or false. Can I perform the following operation on the list lst or do I need to create a loop? A is the output.
List <int> lst = new List <int>();
A = IsOdd(lst);
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.
Just use the modulus
loop through the list and run the following on each item
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
Alternatively if you want to know if all are even you can do something like this:
bool allAreEven = lst.All(x => x % 2 == 0);
There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:
if (x % 2 == 0)
//even number
else
//odd number
Here are a few other methods (from the website) :
//bitwise operation
if ((x & 1) == 0)
//even number
else
//odd number
//bit shifting
if (((x >> 1) << 1) == x)
//even number
else
//odd number
//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
//even number
else
//odd number
#region even and odd numbers
for (int x = 0; x <= 50; x = x + 2)
{
int y = 1;
y = y + x;
if (y < 50)
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
Console.ReadKey();
}
else
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
Console.ReadKey();
}
}
//order by desc
for (int z = 50; z >= 0; z = z - 2)
{
int w = z;
w = w - 1;
if (w > 0)
{
Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
Console.ReadKey();
}
else
{
Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
Console.ReadKey();
}
}
--simple codes--
#region odd / even numbers order by desc
//declaration of integer
int TotalCount = 50;
int loop;
Console.WriteLine("\n---------Odd Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 == 0)
{
Console.WriteLine("Even numbers : #{0}", loop);
}
}
Console.WriteLine("\n---------Even Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 != 0)
{
Console.WriteLine("odd numbers : #{0}", loop);
}
}
Console.ReadLine();
#endregion

Checking for a prime number

I'm having problems with a task. I need to find and alert the user if the number is prime or not.
Here is my code:
int a = Convert.ToInt32(number);
if (a % 2 !=0 )
{
for (int i = 2; i <= a; i++)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
}
else
{
Console.WriteLine("prime");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("not prime");
}
Console.ReadLine();
Where did I go wrong, and how can I fix it?
Prime numbers is divisible by 1 and themselves you will need to check if number has exactly two divisor starting from one till number then it is prime.
int devisors = 0;
for (int i = 1; i <= a; i++)
if (a % i == 0)
devisors++;
if (devisors == 2)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You can skip one iteration as we know all whole numbers are divisible by 1 then you will have exactly on divisor for prime numbers. Since 1 has only one divisor we need to skip it as it is not prime. So condition would be numbers having only one divisor other then 1 and number should not be one as one is not prime number.
int devisors = 0;
for (int i = 2; i <= a; i++)
if (a % i == 0)
devisors++;
if (a != 1 && devisors == 1)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You just printed prime or not prime, and continued with the loop, rather than stopping. The %2 check is not really needed. Modified appropriately:
int a = Convert.ToInt32(number);
bool prime = true;
if (i == 1) prime = false;
for (int i = 2; prime && i < a; i++)
if (a % i == 0) prime = false;
if (prime) Console.WriteLine("prime");
else Console.WriteLine("not prime");
Console.ReadLine();
public bool isPrime(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return num == 1 ? false : true;
}
Presumably your code is outputting lots of messages, which seem jumbled and meaningless? There are 3 key issues:
You arn't breaking out of your for loop when you've decided it can't be prime
You are assuming it is prime when it might not be, see the comments in the code below.
You are comparing to a itself, and that will always be divisible by a, the <= in the for condition needs to be <
Code:
int a = Convert.ToInt32(number);
if (a % 2 != 0)
{
for (int i = 3 i < a; i += 2) // we can skip all the even numbers (minor optimization)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
goto escape; // we want to break out of this loop
}
// we know it isn't divisible by i or any primes smaller than i, but that doesn't mean it isn't divisible by something else bigger than i, so keep looping
}
// checked ALL numbers, must be Prime
Console.WriteLine("prime");
}
else
{
Console.WriteLine("not prime");
}
escape:
Console.ReadLine();
As other have mentioned, you could only loop to the square root of the a, by per-evaluating the square root and replacing this line:
for (int i = 3 i < a; i += 2)
with this:
float sqrRoot = (Int)Math.Sqrt((float)a);
for (int i = 3 i <= sqrRoot; i += 2)
It is important to per-evaluate it else your program will run much slower, rather than faster, as each iteration will involve a square root operation.
If you don't like goto statements (I love goto statements), post a comment and I'll replace it will a breakout boolean (or see Dukeling's more recent answer).
I've done far too much prime checking.
I did this:
bool isPrime = true;
List<ulong> primes = new List<ulong>();
ulong nCheck, nCounted;
nCounted = 0;
nCheck = 3;
primes.Add(2);
for (; ; )
{
isPrime = true;
foreach (ulong nModulo in primes)
{
if (((nCheck / 2) + 1) <= nModulo)
{ break; }
if (nCheck % nModulo == 0)
{ isPrime = false; }
}
if (isPrime == true)
{
Console.WriteLine("New prime found: " + (nCheck) + ", prime number " + (++nCounted) + ".");
primes.Add(nCheck);
}
nCheck++;
nCheck++;
}
This is not EXACTLY what you are looking for though, so what I'd do is put this in a background worker, but with the list of ulongs as a concurrent list, or something that you can access in 2 threads. Or just lock the list while it's being accessed. If the prime hssn't been worked out yet, wait until it is.
Yet another optimized way is to use Sieve of Eratosthenes algorithm.
From Wikipedia
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.
C# code
int[] GetPrimes(int number) // input should be greater than 1
{
bool[] arr = new bool[number + 1];
var listPrimes = new List<int>();
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (!arr[i])
{
int squareI = i * i;
for (int j = squareI; j <= number; j = j + i)
{
arr[j] = true;
}
}
for (int c = 1; c < number + 1; c++)
{
if (arr[c] == false)
{
listPrimes.Add(c);
}
}
}
return listPrimes.ToArray();
}
private static void checkpirme(int x)
{
for (int i = 1; i <= x; i++)
{
if (i == 1 || x == i)
{
continue;
}
else
{
if (x % i == 0)
{
Console.WriteLine(x + " is not prime number");
return;
}
}
}
Console.WriteLine(x + " is prime number");
}
where x is number to check it if prime or not

Categories

Resources