How can I get this code to loop correctly? - c#

int a = 0;
int b = 0;
for (int c = 0; c < 2; c++)
{
Console.WriteLine("Give me a number");
int h = Convert.ToInt16(Console.ReadLine());
switch (c)
{
case 0:
a = h;
while (a <100 || a>250)
{
Console.WriteLine("That number is too large");
break;
}
break;
case 1:
b = h;
while (a < 100 || a > 250)
{
Console.WriteLine("That number is too large");
break;
}
break;
}
}
Console.WriteLine("{0}",a+b);
Console.ReadKey();
When I input numbers greater than 250 or less than 100 it does give me the message ("That number is too large") but the problem is that it still executes the addition at the end of the code. I am trying to make it so that if those numbers fall outside of that range, it asks me again for the numbers. Any tips on how I can do this?

Subroutines are wonderful things, and useful in many situations.
int GetNumberBetween( int minValue, int maxValue )
{
int h;
for (;;)
{
Console.WriteLine("Give me a number");
h = Convert.ToInt32(Console.ReadLine());
if ( h >= minValue && h <= maxValue )
break;
Console.WriteLine("I don't like that number, try again");
}
return( h );
}
void DisplaySum( void )
{
int a = GetNumberBetween( 100, 250 );
int b = GetNumberBetween( 100, 250 );
Console.WriteLine("{0}",a+b);
Console.ReadKey();
}

You need a better control on your external loop. Instead of a for use a while and increment the variable C only when you have a good number.
int a = 0;
int b = 0;
int c = 0;
while (c < 2)
{
Console.WriteLine("Give me a number");
int h;
if(!Int32.TryParse(Console.ReadLine(), out h)
{
Console.WriteLine("Not a valid number");
continue;
}
switch (c)
{
case 0:
a = h;
if(a <100 || a>250)
Console.WriteLine("That number is too large");
else
c = 1;
break;
case 1:
b = h;
if(b < 100 || b > 250)
Console.WriteLine("That number is too large");
else
c = 2;
break;
}
}
Console.WriteLine("{0}",a+b);
Console.ReadKey();
By the way, I suggest to use Int32.TryParse instead of Convert.ToInt32 (What happen in your code if the user types something that cannot be converted to a number?)
I have also fixed a typo in your second test. You should use the variable b instead of a

You're over thinking the solution. If you are just trying to sum two numbers, then simply do that. Think of it logically. You can add the error messages as needed.
Get the number for a
Get the number for b
Sum the numbers
Note: If you need to sum more than two numbers then this solution won't work
//...
int a = 0;
//Capture a value for a, and range check it
while (a < 10 || a > 50)
{
Console.WriteLine("Give me a number for (a)");
a = Convert.ToInt32(Console.ReadLine());
}
int b = 0;
//Capture a value for b, and range check it
while (b < 10 || b > 50)
{
Console.WriteLine("Give me a number for (b)");
b = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("{0}", a + b);
Console.ReadKey();
//...
EDIT:
int a = 0;
//Get a value for a
while (true)
{
Console.WriteLine("Give me a number for (a)");
a = Convert.ToInt32(Console.ReadLine());
//Range check and exit if valid
if (a >= 10 && a <= 50)
break;
Console.WriteLine("That number is too large");
}
int b = 0;
//Get a value for b
while (true)
{
Console.WriteLine("Give me a number for (b)");
b = Convert.ToInt32(Console.ReadLine());
//Range check and exit if valid
if (b >= 10 && b <= 50)
break;
Console.WriteLine("That number is too large");
}
Console.WriteLine("{0}", a + b);
Console.ReadKey();

Related

Setting a max and min value for user number input in console

Console.WriteLine(" **************************************");
Console.WriteLine(" ****** Reviewer Awarding Points ******");
Console.WriteLine(" **************************************");
Console.WriteLine();
string[]properties= { "Clarity", "Orginality", "Difficulty" };
int[] a = new int[3];
int[] b = new int[3];
for(int i = 0; i < 3; i++)
{
Console.WriteLine(" ***" + properties[i]+"***");
Console.Write(" Alice: ");
a[i] = Convert.ToInt16(Console.ReadLine());
if(a[i]>100 || a[i] < 1)
Console.Write(" Bob: ");
b[i] = Convert.ToInt16(Console.ReadLine());
Console.WriteLine();
}
Console.Read();
}
I want user to enter a value between 1 and 100(including 1 and 100).So what I am gonna do?
your question is not clear
try
int value;
do{
Console.Write("Enter a value");
value=int.parse(Console.ReadLine());
}while(value<1 || value>100);
Make a method that checks the result for being in range:
public int AskInt(string question, int min, int max){
while(true){
Console.WriteLine(question);
string input = Console.ReadLine();
if(int.Tryparse(input, out int value) && value >= min && value <= max)
return value;
}
}
The only way to escape the loop is to enter a valid number that is in range, otherwise the question just repeats
Then you can use it multiple times in your code:
int age = AskInt("Enter an age between 10 and 100: ", 10, 100);
int weight = AskInt("Enter a weight between 100 and 350: " 100, 350);
Try this:
if(a[i]>=100 || a[i] <= 1)
You can learn about C# operators at this site: https://www.w3schools.com/cs/cs_operators.php

Using correct number in calculation c#

A user enters two prime numbers which are then multiplied together, and another calculation of (a-1) * (b-1) is completed (a and b being the prime numbers entered). a function to checks the numbers entered, if the numbers are NOT prime, the user will be asked to re-enter the numbers. However, when I test this, I've noticed that if the user inputs a number which ISN'T prime, and then re-enters a prime number, the calculations are based on the number which ISN'T prime. E.g. if the user enters 2 and 4, since 4 isn't prime they are asked to enter another number, e.g 3, the calculations will be based on the numbers 2 and 4.
How can I correct this so it takes the valid prime number and not the invalid number originally entered?
namespace example
{
class Program
{
class Co_P
{
static void coprime(ref int c, int calculation)
{
if (gcd(c, calculation) == 1)
Console.WriteLine("it's Co-Prime");
else
do
{
Console.WriteLine("it isn't Co-Prime");
Console.WriteLine("Enter a Co-Prime");
c = int.Parse(Console.ReadLine());
coprime(ref c, calculation);
} while (gcd(c, calculation) != 1);
}
static int Prime_a(int a) //check a is prime
{
if (a <= 1) return 0;
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
return 0; //not prime
}
}
return 1;
}
static void result(int a) //outputs if a is prime/or not
{
if (Prime_a(a) != 0)
{
Console.WriteLine(a + " is a prime number");
}
else do
{
Console.WriteLine(a + " isn't prime number");
Console.WriteLine();
Console.WriteLine("Please make sure you enter a prime number");
a = int.Parse(Console.ReadLine());
} while (Prime_a(a) == 0);
}
static int Prime_b(int b)
{
if (b <= 1) return 0;
for (int i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return 0;
}
}
return 1;
}
static void resultb(int b)
{
int result = Prime_b(b);
if (Prime_b(b) != 0)
{
Console.WriteLine(b + " is a prime number");
}
else do
{
Console.WriteLine(b + " is not a prime number");
Console.WriteLine("Please make sure you enter a prime number");
b = int.Parse(Console.ReadLine());
} while (Prime_b(b) == 0);
}
static void Main(string[] args)
{
int a;
Console.WriteLine("Enter a prime number for a");
a = int.Parse(Console.ReadLine());
Console.WriteLine();
result(a);
Console.WriteLine();
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
int total = a * b;
Console.WriteLine("The total of the prime numbers is = " + total);
int calculation = (a - 1) * (b - 1); //calculation
Console.WriteLine();
Console.WriteLine("The result = " + calculation);
Console.WriteLine();
}
}
}
You should extend result and resultb function so it returns new prompted valid number
static int result(int a) {
var result = Prime_a(a);
if (result != 0)
...code...
return result
}
Also don't forget to reassign those values
...code...
a = result(a);
...code...
b = resultb(b);
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
In line resultb(b); you are passing int to method resultb. int is a value type, or in other words, passing int to a method means passing its value to a method, where copy of that value is created. In this case a copy of b is created in method resultb. Every further change on b inside method resultb is made on copy and original stays the same.
In resultb method pass parameter by reference by adding ref keyword. Instead
static void resultb(int b)
{
// code
}
method will look like this
static void resultb(ref int b)
{
// code
}
You will call the method this way
resultb(ref b);
Here's the portion of code.
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(ref b);
Console.WriteLine();
Now every change on passed b inside method resultb will reflect on the original.
You should do the same for method result(int a).

Validating multiple fields

I used Visual Studio to create an application that features 3 fields where 3 numbers can be added together. Now, I need to validate all 3 fields so that negative numbers cannot be added. If a negative number is entered, each field has also to return a unique message like: "please enter a positive first number."
I figured out how to do that for one field, but how do I set it up for all 3 fields to not accept negative numbers (and display a unique message)?
Here is what I have:
{
int num = int.Parse(txtNum1.Text);
if (num <0)
{
MessageBox.Show("Please enter a positive first number");
}
else
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Hopefully this makes sense.
This might help you
int num = 0;
bool atLeastOneisNegative = false;
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
num = 0;
num = int.Parse(((TextBox)x).Text);
if(num < 0)
{
atLeastOneisNegative = true;
MessageBox.Show("Please enter a positive first number");
}
}
}
if(!atLeastOneisNegative)
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Whereas the question is not stating whether you are using WPF or WinForms. But the logic might help you to achieve to iterate all your TextBoxes and see the value is Positive.
It can be easier with NumericUpDown control or handling the TextBox.Validating event, but anyway:
int i1, i2, i3;
if (!int.TryParse(txtNum1.Text, out i1) || i1 < 0) { MessageBox.Show("Please enter a positive first number" ); return; }
if (!int.TryParse(txtNum2.Text, out i2) || i2 < 0) { MessageBox.Show("Please enter a positive second number"); return; }
if (!int.TryParse(txtNum3.Text, out i3) || i3 < 0) { MessageBox.Show("Please enter a positive third number" ); return; }
int sum = i1 + i2 + i3;
txtResult.Text = sum.ToString();

Index out of Range exception in C# when iterating through an array

I have this code I'm using to create a program that takes a a range and outputs to the Console the prime numbers. I have one problem, I'm trying to iterate through the array I built so the loop should only write to the console the values that are prime using my method's return value. The problem I'm having is that I have the second condition set to numArray.Length but it seems to give me the Index out of Range Exception. I just want the loop to iterate through all values in the numArray and stop when it's done figuring out whether the last value is prime or not.
public struct Prime
{
public int x;
// constructor for Prime
public Prime(int x1)
{
x = x1;
}
public int IsPrime(int number)
{
int i;
for (i = 2; i * i <= number; i++)
{
if (number % i == 0) return 0;
}
return 1;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an Integer");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a Second Integer of Greater Value");
// int num2 = 0;
int num2 = Convert.ToInt32(Console.ReadLine());
/* if (num2temp > num1)
{
num2temp = num2;
}
else
{
Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again.");
Environment.Exit(0);
}
*/ int index = 1;
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
Console.WriteLine("value: {0}", numArray[40]);
/* Prime myprime = new Prime();
if (myprime.IsPrime(numArray[12]) == 1)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("False");
} */
Prime myprime = new Prime();
int value = 0;
for (int y = 1; y <= num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
You're currently trying to iterate up to and including the size of the array. Arrays are 0-indexed in C#. So this:
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
should be:
for (int i = num1; i < num2; i++)
And note that to get at the first element array, num1 would have to be 0, not 1.
Likewise, your initial assignment of index as 1 should be 0 instead. Basically you need to go through all your code (it's confusing at the moment with lots of bits commented out) and check everywhere that you're assuming arrays are 1-based, and instead change your code as they're 0-based.
(In some cases you may just want to make the array one bigger, of course. If you want an array which logically contains the values 1 to x inclusive, you can either create an array of size x and subtract one from each index all the time, or create an array of size x + 1.)
Your index starts from 1 but should start from 0:
int index = 0; //CHANGE HERE
int[] numArray = new int[num2];
for (int i = num1; i <= num2; i++)
{
numArray[index] = i;
Console.WriteLine(" index: {0} assignment: {1}", index, i);
index++;
Console.WriteLine("index: {0}",index);
}
and then here y should also be 0 and check should if it is less than num2:
for (int y = 0; y < num2; y++)
{
if (myprime.IsPrime(numArray[y]) == 1)
{
value = numArray[y];
Console.Write("{0} \t", value);
}
}
because array indexing in C# start from 0.

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