I want to make the same as I did here, to do the same operation, but instead of doing the int first_dig and second_dig I want to use it with boolean, something like: bool check = (new code here);
Console.Write("Enter a two digit number: ");
int two_dig_num = int.Parse(Console.ReadLine());
if (two_dig_num >= 10 && two_dig_num <= 99)
{
int first_dig = two_dig_num % 10;
int second_dig = two_dig_num / 10;
if (first_dig == second_dig)
Console.WriteLine("YES!");
else
Console.WriteLine("NO...");
}
else
Console.WriteLine("\nYou haven't entered a Two Digit Number,\nPlease exit the program and try again later");
return;
}
}
}
first_dig == second_dig returns you bool, so if you want to store it in some variable then just:
bool value = first_dig == second_dig;
or with less variables it can be:
bool value = two_dig_num % 10 == two_dig_num / 10;
That is it.
Related
i wanna ask something. My script gots some error
Here is it
using System;
namespace 3nplus1
{
class MainClass
{
public static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
while (Convert.ToBoolean(n = 1))
{
if (Convert.ToBoolean(n % 2 = 0))
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
Console.WriteLine(n);
}
}
}
The error message says:"/Error CS0131: The left-hand side of an assignment must be a variable, property or indexer (CS0131) (3nplus1)
The error is located on the first "if" line
Please help.
Thanks and sorry for bad English.
You are confusing the = operator(assignment) with the == operator which is used for comparisons. So this is not a comparison that evaluates to true but an assignment(that returns the value that you assign).
if (Convert.ToBoolean(n % 2 = 0))
but the compiler complains about it because there must not be an expression on the left side of the assignment(like here) but a variable. You also don't need those Convert.ToBoolean.
Well, as said this is just a followup error. You want something like this:
Console.WriteLine("Enter a number(exit with q): ");
string input = Console.ReadLine();
while (!input.Equals("q", StringComparison.OrdinalIgnoreCase))
{
int n;
while (!int.TryParse(input, out n))
{
Console.WriteLine("Enter a valid integer");
input = Console.ReadLine();
}
int result = n % 2 == 0 ? n / 2 : 3 * n + 1;
Console.WriteLine(result);
input = Console.ReadLine();
}
change this part of your code
while (n != 1)
{
if (n % 2 == 0)
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
A single = represents an assignment, however in your case you want to check for equality and therefore use the == operator. Doing this eliminates the need to use Convert.ToBoolean.
With an = you assign a value to a variable or a property. But you want to make a comparison on the equality and for that you take two ==.
And by the way you don't need Convert.ToBoolean. Just write:
if (n % 2 == 0)
{
...
}
The problem is that the courselist[y] works only for 0 value or 1 if i add a second courselist.How i can obligate the user to give the right value?
Also if the courselist is empty , what i have to do to show the appropiate message?
public static void AddTrainer()
{
Console.WriteLine("Trainer name");
string sname = Console.ReadLine();
Trainer tr = new Trainer(Helper.trainerlist.Count() + 1, sname);
Helper.trainerlist.Add(tr);
Console.WriteLine("Give course");
int y = Convert.ToInt32(Console.ReadLine());
//y = y - 1;
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
Helper.ShowMenu2();
}
You could ask again until the user provides the correct value
string input;
do
{
Console.WriteLine("Give course (0 or 1)");
input = Console.ReadLine();
}
while (input != "0" && input != "1");
int y = Convert.ToInt32(input);
Console.WriteLine("Give course");
int y;
while (!int.TryParse(Console.ReadLine(), out y) || y >= Helper.courselist.Count() || y < 0)
{
Console.WriteLine("Give course that already created (1,2,3,...etc)");
}
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
This worked , but i want to give 1 for the first courselist , not 0. And what if the courselist is empty?
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();
I am working through learning C# on my own - this is not a homework assignment. I am only on chapter 7 so I am hoping for a simple/basic answer.
I am having troubles calling the TalentListing method from Main that gets its parameters from another method. Do I have to duplicate them in the Main method?
I realize the methods are void - I don't need them to return anything, I just need them to run.
Sorry the code is long, I thought it would be best to show it all.
Thank you!
class Program
{
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes);
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string[] contestantNames;
string contestantNameEntered;// user entry
char[] contestantTalentCodes;
char talentCodeEntered; // user entry
string[] talents = { "Dancing", "Musical", "Other" };
char[] validTalentCodes = { 'D', 'M', 'O' };
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
}
public static void TalentListing(string contestantNames, char [] validTalentCodes, char [] contestantTalentCodes)
{ // Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
// What talent code would you like to see (or QUIT)?
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}
The CompetitorTalents(int current) method has no return value, you are using void. The TalentListing receives two strings. So you need to get those two from somewhere. If you want them to come from the CompetitorTalens method, you have to change it so it returns string and actually return something from it.
For this simple app use static global variables. Just copy this code and take a look.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static string[] talents = { "Dancing", "Musical", "Other" };
public static char[] validTalentCodes = { 'D', 'M', 'O' };
public static string[] contestantNames;
public static char[] contestantTalentCodes;
static void Main()
{
int pastContestants;
int currentContestants;
// Call Methods:
Console.Write("LAST YEAR'S TALENT: ");
pastContestants = Contestants();
Console.Write("THIS YEAR'S TALENT: ");
currentContestants = Contestants();
Overview(pastContestants, currentContestants);
CompetitorTalents(currentContestants);
// need to call the TalentListing Method...
TalentListing();
Console.ReadLine();
}
public static int Contestants()
{ // Get & returns valid # of contestants. Called twice - last year & this year
int contestants = 0; // holds return value
const int MIN = 0; // will allow 0 as an answer
const int MAX = 30; // will allow 30 as an answer
Console.Write("Please enter the number of contestants: ");
contestants = Int32.Parse(Console.ReadLine());
while (contestants < MIN || contestants > MAX)
{
Console.Write("Invalid number. Please enter a number between 0 and 30, inclusive: ");
contestants = Int32.Parse(Console.ReadLine());
}
return contestants;
}
public static void Overview(int past, int current)
{ // Accepts contestant - past & current. Displays 1 of 3 messages.
double entranceFee = 25.00;
Console.WriteLine("\nWe had {0} contestants last year and have {1} contestants this year.", past,
current);
//if more than double
if (current > (past * 2))
Console.WriteLine("The competition is more than twice as big this year!");
//if bigger but no more than double
if (current > past && current < (past * 2))
Console.WriteLine("The competition is bigger than ever!");
//if smaller than last year
if (current < past)
Console.WriteLine("A tighter race this year. Come out and cast your vote!");
Console.WriteLine("\nThe revenue expected for this year is {0:C}.", current * entranceFee);
}
public static void CompetitorTalents(int current)
{ // Fill array of competitors and their talent codes.
string contestantNameEntered;// user entry
char talentCodeEntered; // user entry
int[] total = new int[talents.Length];
bool validCode = false;
int counter = 0;
contestantNames = new string[current]; // set array size
contestantTalentCodes = new char[current]; // set array size
// put contestants in array
while (counter < current)// loop for all contestants
{
// get contenstants name and put in array
Console.Write("Please enter the name of contestant: ");
contestantNameEntered = Console.ReadLine();
counter += 1; // contestant number
validCode = false;
//place in correct array element
contestantNames[counter - 1] = contestantNameEntered;
// get contestants talent code, verify and place in array
while (validCode == false) // reset per contestant
{
Console.Write("Please enter the contestant's talent code (D=Dancing, M=Musical, O=Other): ");
talentCodeEntered = Char.Parse(Console.ReadLine().ToUpper()); // convert to uppercase
for (int x = 0; x < validTalentCodes.Length && !validCode; ++x)
if (talentCodeEntered == validTalentCodes[x]) // talent code valid?
{
validCode = true; // true if match found
contestantTalentCodes[counter - 1] = talentCodeEntered; //put talent code in array
x = validTalentCodes.Length; // breaks out of loop
}
if (validCode == false) // false if no match found = invalid code.
{
Console.WriteLine("Invalid code talent Code.");
}
}
}
// search all elements of validTalentCodes array (D, M, O), count instances in contestantTalentCodes array
for (int z = 0; z < validTalentCodes.Length; z++) // validTalentCodes
for (int x = 0; x < contestantTalentCodes.Length; x++) // contestantTalentCodes
if (contestantTalentCodes[x] == validTalentCodes[z])
{
total[z]++;
}
for (int x = 0; x < talents.Length; ++x)
Console.WriteLine("Total contenstants for {0} is {1}.", talents[x], total[x]);
return ;
}
/// Continuously prompt for talent codes and display contestants with the corresponding talent until quit.
/// What talent code would you like to see (or QUIT)?
public static void TalentListing()
{
const char QUIT = 'Q';// must be upper as char are converted!!
char userOption = ' ';
bool validCode = false;
while (userOption != QUIT)
{
Console.Write("\nWhat talent code would you like to view? (D, M, O or Q to quit): ");
validCode = false; // reset from previous section
userOption = Char.Parse(Console.ReadLine().ToUpper());
for (int x = 0; x < contestantNames.Length && !validCode; ++x)
{
if (userOption == validTalentCodes[x]) // valid talent code?
{
validCode = true;
Console.Write("The contestants in {0} talent are: ", validTalentCodes[x]);
// display list of contestants with that code
for (int z = 0; z < contestantTalentCodes.Length; z++) // validTalentCodes
if (contestantTalentCodes[z] == userOption)
{
Console.Write("\n{0}", contestantNames[z]);
}
}
}
if (validCode == false)
Console.WriteLine("Invalid talent code!");
}
Console.WriteLine(); // when QUIT is selected
}
}
}
You need to close the method call (So you were missing a ) at the end) :
TalentListing(CompetitorTalents(contestantNames), CompetitorTalents(validTalentCodes), CompetitorTalents(contestantTalentCodes));
The methods you are calling are void meaning they dont return anything:
public static string CompetitorTalents(int current)
Then in the method call for the CompetitorTalents you should pass in what is the method needs. I would advise doing this on separate lines:
string contestantNames = CompetitorTalents(currentContestants);
And so on, then in the TalentListing you could just reference the individual variables:
TalentListing(contestantNames, validTalentCodes, contestantTalentCodes);
Well, looking at your method signatures we can see the following:
void TalentListing(string, char[], char[])
void CompetitorTalents(int)
Your CompetitorTalents method returns a void, but you are trying to pass the result of that method as parameters for your TalentListing method. So you are essentially trying to call TalentListing(void, void, void), when really it wants a string, a char[], and then another char[]
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