Beginner c# trouble - c#

Im new to c# and Im having a little problem. I want to make an easy program to ask the user for a integer number between 1-50, and then to display on the console if its a odd number or not. So, what i tried is this:
Console.WriteLine("Skriv ut ett heltal: ");
int x = int.Parse(Console.ReadLine());
if (x == 1,3,5,7,9,11,13,15,17,19)
{
Console.WriteLine("The number is odd");
}
else
{
Console.WriteLine("The number is not odd");
}
Now i get an error at my if statements condition. How can i fix this?

C# does not allow you specify multiple values to check a variable against using a single if statement. You would need to check each value (1, 3, 5, etc) individually if you wanted to do it this way, and that would be a lot of redundant typing.
In this particular example, an easier way to check if something is odd or even is to check the remainder after dividing by 2, using the modulus operator %:
if (x % 2 == 1)
{
Console.WriteLine("The number is odd");
}
else
{
Console.WriteLine("The number is even");
}
However, if you really do need to check against a list, then the easy way is to use the Contains method on an array (an ICollection<T>, really). To make it nice and easy, you could even write an extension function that lets you check against a list in a syntactically pretty fashion:
public static class ExtensionFunctions
{
public static bool In<T>(this T v, params T[] vals)
{
return vals.Contains(v);
}
}
Then you could say:
if (x.In(1,3,5,7,9,11,13,15,17,19))
{
Console.WriteLine("The number is definitely odd and in range 1..19");
}
else
{
Console.WriteLine("The number is even, or is not in the range 1..19");
}
Voila! :)

if(x % 2 == 0)
{
// It's even
}
else
{
// It's odd
}

If you want to test whether x is a number in a particular list:
int[] list = new int[]{ 1,3,5,7,9,11,13,15,17,19};
if(list.Contains(x))
The common way to check to see if an integer is odd is to check if it divides evenly by 2:
if(x % 2 == 1)

x == 1,3,5,7,9,11,13,15,17,19 is not valid syntax for expressing multiple options. If you really want to do this then you can use a switch statement:
switch(x) {
case 1:
case 3:
case 5:
case 7:
case 9:
case 11:
case 13:
case 15:
case 17:
case 19:
// is odd
break;
default:
// is even
break;
}
The correct way would be to use the modulo operator % to determine if a number is exactly divisible by 2 or not, rather than trying every odd number, like so:
if( x % 2 == 0 ) {
// even number
} else {
// odd number
}

That's not valid C#. You can't test set inclusion like that. In any case, it's not practical to test for all the numbers in the world.
Why don't you just do this instead;
if (x &1 == 1) // mask the 1 bit
Bitwise operations are pretty quick so that code should be pretty fast.

Your if statement should be like this if you are having multiple conditions:
if any 1 of conditions is true:
if(x == 1 || x == 3 || x == 5)
{
//it is true
}
if all of the condition must be true:
if(x == 1 && y == 3 && z == 5)
{
//it is true
}
But if you are only looking for odd/even numbers. Use the % operator as the other answer says.

While, as others have pointed out, this is not the best way to solve this problem, the reason you're getting an error in this case is because you can't have multiple values like that in an if statement. You have to word it like this:
if (x == 1 || x == 3 || x == 5)
If you don't know, || is the symbol for 'or'

Try the following:
Console.WriteLine("Skriv ut ett heltal: ");
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x % 2 == 1 ? "The number is odd" : "The number is not odd");
x % 2 == 1 does a modulus of 2 on the input (takes as many '2's off as possible until the number is between 0 and 2 - so 0 or 1 in this case)

One way to do that is:
if (x == 1 || 3 || 5){
Console.writeLine("oddetall");
}
or so it is possible to create an Array []
int[] odd = new int[3]; // how many odd to be tested
if(x=odd){
Console.WriteLine("Oddetall");
}

Related

Error says that it can't transform string into int

string num;
num = Console.ReadLine();
Console.WriteLine(num);
switch (num)
{case 1:
Console.WriteLine(one);
I'm trying to do a c# project where you type a number from 1 to 100 and you see the wrote version of it.
The variable num is a string. But you're trying to compare it with an integer here:
case 1:
The quickest solution would be to compare it with a string:
case "1":
Alternatively, and possibly as a learning experience for you, you may want to try converting num to an int. Take a look at int.TryParse for that. An example might look like this:
string num = Console.ReadLine();
int numValue = 0;
if (!int.TryParse(num, out numValue)) {
// The value entered was not an integer. Perhaps show the user an error message?
}
You mentioned only wanting to print numbers between 1 and 100.
This version does that.
var consoleResponse = Console.ReadLine();
if (int.TryParse(consoleResponse, out int parsedValue)
&& parsedValue >= 1
&& parsedValue <= 100) {
Console.WriteLine(parsedValue);
}

How to Insert multiple conditions in while loop in

I want to use multiple conditions in while loop:
Console.WriteLine("Select an action to perform\n");
int n1 = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Insert a valid method\n");
n1 = Convert.ToInt32(Console.ReadLine());
}
while ((n1 == 1) || (n1 == 2));
Console.WriteLine(n1);
Console.ReadKey();
In here I want to check the value n1 is equals to 1 or 2. Until the user enter n1 or 2 this should loop. The thing is I can get this to working if im using just one condition but cant get this working when there are 2 conditions. Also how to equal these values to another string?
Ex:
while ((n1 == "one") || (n1 =="two"))
I think theres something I didnt understand about || (OR) operator. I read few solutions yet I couldnt figure it out.
You are confusing do....while with do...until (the latter of which is not a c# construct).
If you want an "until" sort of logic loop, use while(true) and use an if statement with the until condition to break the loop.
Console.WriteLine("Select an action to perform\n");
int n11 = Convert.ToInt32(Console.ReadLine());
while (true)
{
Console.WriteLine("Insert a valid method\n");
n1 = Convert.ToInt32(Console.ReadLine());
if ((n1 == 1) || (n1 == 2)) break;
}
An alternative is to keep the while construct but invert the logic. This isn't my favorite answer because it may cause the logic to become less clear.
Console.WriteLine("Select an action to perform\n");
int n11 = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Insert a valid method\n");
n1 = Convert.ToInt32(Console.ReadLine());
}
while ((n1 != 1) && (n1 != 2));
You want this to loop until the user enters 1 or 2.
But in the code, you asked it to loop when the user enters 1 or 2.
So, instead of
while ((n1 == 1) || (n1 == 2));
you should write
while (!(n1 == 1 || n1 == 2));
Remaining part of the code is good, it'll work as expected.
No need to check for strings "one" and "two" as you're converting input to Int32 in line 6.
Convert.ToInt32(Console.ReadLine()) can't convert string "one" to Integer '1'.
Your current code is this:
while ((n1 == 1) || (n1 == 2))
This code states that the loop should be repeated / continue if n1 == 1 or n1 == 2. What you actually want is to repeat where n1 isn't equal to either of them:
while (n1 != 1 && n1 != 2)
This states that if n1 isn't 1, and n1 isn't 2, then it should loop. If this statement isn't true, the loop will exit and your code will move on to Console.WriteLine(n1);.
Note that n1 != 1 && n1 != 2 is the opposite of n1 == 1 || n1 == 2.
I suggest using infinite loop while(true) {...} which we break on valid input (please, note int.TryParse instead of Convert.ToInt32 - we don't want exception on input like "bla-bla-bla"):
// Let's be nice and show expected user response - 1 or 2
Console.WriteLine("Select an action to perform (1, 2)\n");
int n1;
while (true) {
// If user input is a valid i.e.
// 1. Input is valid integer - int.TryParse returns true
// 2. User input is either 1 or 2
// we break the loop and start business logic; otherwise keep asking
if (int.TryParse(Console.ReadLine(), out n1) && ((n1 == 1) || (n1 == 2)))
break;
// Again, let's be nice and help user
Console.WriteLine("Insert a valid method (either 1 or 2)\n");
}
Console.WriteLine(n1);
Console.ReadKey();

How to search for number in string with method Contains and Linq in c#?

I create calculator which have buttons with numbers and operators for basic operation (+, -,...) and just want to filter buttons with numbers to detect when is clicked number (between 0-9). Also i put new eventhadler which convert sender to button.
I wondering what will be nice and easy way to filter the buttons with numbers (using linq)
What did i try so far is
if(btn.Text == btn.Text.Contains(x => x >= '0' && x <= '9'))
MessageBox.Show("number " + btn.Text + " is pressed!");
How to make upper code workable?
Here you go, for your immediate needs:
if(btn.Text.All(char.IsDigit))
{
//Do your stuff
}
If all you want to know is that is it a number or not do this. No LINQ is required
LINQ Way to check the numbers are between 0 and 9
if(yourstring.ToCharArray().Where(c=> c < '0' || c > '9').Any())
return false;
else
return true;
To check that it contains a valid number
double num;
if (double.TryParse(btn.Text, out num))
{
// It's a number!
}
or to check less than 10 without linq
static bool IsLessThanTen(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
if you need to check at least one number in the button text, then use below
return btn.Text.Any(char.IsDigit)
If you writing calculator, you better check NCalc - Mathematical Expressions Evaluator for .NET and this CodeProject tutorial
This should work
bool hasNumeric = yourString.IndexOfAny("0123456789".ToCharArray()) > -1;

Project Euler 10: simple code is not giving the desired result, need help understanding why

I'm solving Project Euler problems for kicks, I'm currently at number 10.
First of all: I know there are other solutions, I'm currently writing another method using the sieve of Eratosthenes. What I'd like your help with is understanding why this code does not work.
This is my code (the problems involves finding the sum of every prime under 2 million). The prime-checking method seems to work fine, but the result is way less than it should be.
class Euler10
{
public static void Main()
{
long sum = 0; // Was originally an int. Thanks Soner Gönül!
for(int i = 1; i < 2000000; i++)
{
if (CheckIfPrime(i) == true)
sum += i;
}
System.Console.WriteLine(sum);
System.Console.Read();
}
static bool CheckIfPrime(int number)
{
if (number <= 1)
return false;
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for (int i = 3; i*i < number; i += 2)
{
if ((number % i) == 0)
return false;
}
return true;
}
}
The number I get is 1,308,111,344, which is two orders of magnitude lower than it should be. The code is so simple I am baffled by this error.
EDIT: making sum a long solved the digit problem, thanks everyone! Now, though, I get 143042032112 as an answer: the i*i in CheckIfPrime() isn't always right.
Using the sqrt() function and adding one (to compensate for the int cast) gives the correct result. Here's the correct CheckIfPrime() function:
bool CheckIfPrime(int number)
{
if (number <= 1)
return false;
if (number == 2)
return true;
if (number % 2 == 0)
return false;
int max = 1 + (int)System.Math.Sqrt(number);
for (int i = 3; i < max; i += 2)
{
if ((number % i) == 0)
return false;
}
return true;
}
EDIT 2: Will Ness helped me optimize the code further (calculating number's square root and comparing it to i is slower than elevating i^2 and then comparing it to number): the problem with the original method is that it didn't take into consideration edge cases in which number is the exact square of i, thus sometimes returning true instead of false. The correct code for CheckIfPrime(), then, is:
bool CheckIfPrime(int number)
{
if (number <= 1)
return false;
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for (int i = 3; i*i <= number; i += 2)
{
if ((number % i) == 0)
return false;
}
return true;
}
Thanks again people!
Your code does not work because it tries using a 32-bit int to hold a number that exceeds the highest value in a 32-bit variable. The answer to the problem is 142,913,828,922, which needs 38 bits.
Changing the data type of sum to long should fix this problem.
Using long should help.http://msdn.microsoft.com/en-us/library/ctetwysk.aspx
Gives you a 64 bit integer where as int is only 32 bits.
You are using int for sum variable which is 32-bit but you are try to assign it more than Int32.Maximum which is 2,147,483,647.
But your result is 143,042,032,112 which needs more bits than 32 for storing it.
Set its type as long which stores 64 bit.
long sum = 0;
Here a working DEMO.
for (... i=3 ; i*i < number; i+=2 ) is wrong. It should be
for (... i=3 ; i*i <= number; i+=2 )
...
both i and number must be of the same type of course; this will almost never give you an overflow, since you start from 3 (unless number is very big, close to the upper limit of the type's range).
The comparison should be inclusive to catch cases where number is a square of a prime.
Your algorithm is not the Sieve of Eratosthenes; the modulo operator gives it away. Your algorithm is trial division by odd numbers. Here is a function using the Sieve of Eratosthenes:
function sumPrimes(n)
sum := 0
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve[p]
sum := sum + p
for i from p * p to n step p
sieve[i] := False
return sum
Calling sumPrimes(2000000) gives the answer, which I won't write down out of respect for Project Euler. That function runs in time O(n log log n), which is much better than the O(n^2) of your original program. There are better ways to sieve, but that is simple, and easy to get right, and good enough for most purposes, including yours. You should get an answer in less than a second.
I'll leave it to you to translate to C# with appropriate data types.
If you're interested in a somewhat larger version of this problem, I calculated the sum of the first billion primes at my blog: 11138479445180240497.

Using any loop in C#, count from 0 to 20 with a message for each line and for each number divisible by 5, have a special message

I am currently working on loops (for, while, and do while). I understand the basics and have successfully been able to do the basics with little to no effort.
I am currently working on a problem that goes just a touch beyond the basics where the end result will show a message ("Pass {0} in the loop") where obviously the "{0}" is the number loop. However, I am trying to create a separate message for those number that are divisible by 5 (5, 10,15,20). Could I get a pointer in the right direction. I played around with the ideas of using an "if" statement or even a "foreach", but have had no luck since yesterday finding a possible viable option or simply did not know how to phrase it properly. Below is my current code:
static void Main(string[] args)
{
int i = 1;
Console.WriteLine("Do while loop positive numbers");
do
{
Console.WriteLine("Pass {0} in the loop", i++);
} while (i <= 20);
Console.ReadLine();
}
Check the remainder operator: %
Combined with an if statement you should be all set.
Won't write code for you but would like to give hint
You can use an if condition inside the do while loop to check if it is divisible by 5 then display the special message. You can use % operator to check whether the number is divisible by some other number or not
static void Main(string[] args)
{
int i = 1;
Console.WriteLine("Do while loop positive numbers");
do
{
Console.WriteLine("Pass {0} in the loop", i++);
//if your number is divisible by 5 then display message
} while (i <= 20);
Console.ReadLine();
}
simply check if it is divisible by 5
if(i%5==0)
Console.WriteLine("{0} is divisible by 5",i);
% or modules operator is used to get the remainder of the division
on side note ,stackoverflow is not a good place to start programming,other websites or tutorials are more helpful
You should do:
if (i%5==0)
print your special message
Just use the operator % and check for the remainder of the division i % 5. If it is 0 then i is divisble by 5.
To check if a number is divisible by another number you can use the % or modulo operator, you can use it the same way as an addition or division operator, a = c % b.
The modulo operator gives you the remainder of a division. So if you did 51 % 5, you would get 1 as 5 goes into 51 ten times with one left over. Therefore if when you use the modulo operator and the result is 0, the first number is divisible by the second with no remainder.
Therefore, what you need to do is set up an if statement to check if the modulo of i is 5, or whatever you need. There are lots of tutorials on if statements out there, so I wont really go into detail about the code.
The following will check if I is divisible by 5, and then write to the Console if it is. Add this to your loop:
if(i % 5 == 0)
{
Console.WriteLine("{0} is divisible by 5!", i);
}
The for loop
for( int i = 0; i <= 20; i++ )
{
if( i % 5 == 0 && i > 0 )
{
Console.WriteLine( "{0} is divisible by 5.", i );
}
}
The do...while equivalent
int x = 0;
do
{
if( x % 5 == 0 && x > 0 )
{
Console.WriteLine( "{0} is divisible by 5.", x );
}
x++;
}
while( x <= 20 );
Note that I prefer starting loops with zero unless there is a good reason to do otherwise. Indexes are zero-based in .NET and (IMO) it's good to write code that follows that pattern.
As everyone is pointing out, the important thing here is the modulus operator (%).
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
And for a complete breakdown of why the .NET modulus operator is really a remainder operator:
http://blogs.msdn.com/b/ericlippert/archive/2011/12/05/what-s-the-difference-remainder-vs-modulus.aspx
Try using the the % operator in your if statement.
if((i%5) == 0)
divisible by 5 message
else
the regular message
using System;
namespace loop
{
class Program
{
static void Main(string[] args)
{
int i= 1;//start
while (i<=20)
{
Console.WriteLine(i);
i++;
}
Console.ReadKey();
}
}
}
//Just another way to look at the problem in a more simplified way

Categories

Resources