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();
Related
I'm going through a review my teacher gave the me for my first quarter final, and there is a question I don't remember the teacher going over. The question says "Get 3 values from the user, figure out and display the middle value", i.e. 10, 20, 30... 20 is the middle value. So far I have tried iterations of this code:
Console.WriteLine("Enter a value: ");
int value10 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another value: ");
int value11 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter one last value: ");
int value12 = int.Parse(Console.ReadLine());
if (value10 > value11 && value11 > value12)
Console.WriteLine("{0} is the middle value.", value11);
else if (value11 > value12 && value12 > value10)
Console.WriteLine("{0} is the middle value.", value12);
else
Console.WriteLine("{0} is the middle value.", value10);
No version I have written of this works.... WTF am I missing? I keep trying different combos of values, and directions of the lesser/greater than symbol. I've also tried different variations of if if else and else. Thanks in advance for any help.
One option (that works for many elements too) is to sort and take middle element.
var items = new[]{value10,value11, value12};
Array.Sort(items);
Console.Write(items[items.Length/2]);
It the input is always three items and you just need the second one, why not put the inputs into a list, sort it then select the second value?
List<int> inputList = new List<int>();
inputList.Add(int.Parse(Console.ReadLine()));
Console.WriteLine("Enter another value: ");
inputList.Add(int.Parse(Console.ReadLine()));
Console.WriteLine("Enter one last value: ");
inputList.Addint.Parse(Console.ReadLine()));
inputList.Sort();
Console.WriteLine("{0} is the middle value.", inputList[1])
It would probably be a bit cleaner to write the first part of your program to loop until you have filled a List<int> with as many values as you would like:
const int itemCount = 3;
List<int> inputValues = new List<int>(itemCount);
while(inputValues.Count < itemCount)
{
Console.WriteLine("Enter a value: ");
int parsed;
if(int.TryParse(Console.ReadLine(), out parsed))
inputValues.Add(parsed);
else
Console.WriteLine("Please try again!");
}
The inputs naturally belong together as a collection that can be sorted, so storing your data this way, on the way in, is advantageous. (It is also a small step to use int.TryParse() in place of int.Parse(), if you prefer to handle invalid entries and continue taking inputs without throwing an Exception. The above code will just continue asking for values until it has three values it can parse successfully.)
A List can be sorted "in place" (without copying the list) with its .Sort() method, and the the list's indexer can be used to find the middle item.
int middleIndex = (itemCount - 1) / 2; // hopefully, your list has an odd number of elements!
inputValues.Sort();
int middleValue = inputValues[middleIndex];
Console.WriteLine(middleValue);
Although it's not going to be the most efficient solution for your problem, particularly for larger numbers of elements, I thought I would still bring up that LINQ gives you a powerful syntax to order IEnumerable elements as well:
int middleValue = inputValues.OrderBy(x => x).ElementAt(middleIndex);
Add 'OR' conditions to your if statement:
if (value10 > value11 && value11 > value12 || value12 > value11 && value11 > value10)
Console.WriteLine("{0} is the middle value.", value11);
else if (value11 > value12 && value12 > value10 || value10 > value12 && value12 > value11)
Console.WriteLine("{0} is the middle value.", value12);
i am trying to check condition before entering into it but it is entering in wrong condition
my conditions are ,
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() == "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() != "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) > 10000000)
the values are,
T_B_CX = 0 and T_B_C = 2500000000
it must enter the fist condition i mentioned but it is entering in second condition???
Hopes for your suggestion thanks in advance
you can convert to int and do the comparison as below
if (Convert.ToInt(Target.Tables[0].Rows[0]["T_B_CX"].ToString()) == 0 && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
may be when we get ToString of cell value it returns not exactly string equal to "0", debug and see which value you get for Target.Tables[0].Rows[0]["T_B_CX"].ToString()
There is no code between the two conditions, so the first one is taken as expected, then the second one is evaluated till the != 0.
Try to write something like this
// Convert everything just one time here
int tbcx = Convert.ToInt32(Target.Tables[0].Rows[0]["T_B_CX"]);
long tbc = Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]);
if(tbcx == 0 && tbc >= 100000)
// code here
else if(tbcx != 0 && tbc > 2500000000)
// code here
Also try to avoid the conversion of an integer value to a string and then check against a string.
It makes no sense. If an integer is stored in that table then convert it to an integer and check against an integer.
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");
}
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
I'm teaching myself some C# and got the idea to build a temperature calculator. I want to use a do-while loop to ensure the user picks a valid menu choice. What I tried to do was:
do
{
//etc etc etc;
} (while menuChoice != 1||2||3);
In other words, keep doing what is inside the loop unless menuChoice is 1, 2 or 3. VS2010 Express tells me I can't do that. Is there a way to do this that way or do I have to do something else? Any suggestions on how to do this or should I use some other solution?
do { // stuff
} while (menuChoice != 1 && menuChoice != 2 && menuChoice != 3);
do {
// etc.
} while(menuChoice != 1 &&
menuChoice != 2 &&
menuChoice != 3
);
Each of the clauses of a conjunction must be an expression that evaluates to a bool. Note that != 2 is not an expression that evaluates to a bool. In fact, it's not even a legal expression. This is why you must specify menuChoice != 2.
Also, note that you should use && because the clauses. You want menuChoice to equal 1, or to equal 2, or to equal 3. Therefore you want
!(menuChoice == 1 || menuChoice == 2 || menuChoice == 3)
as the condition in the while loop. By DeMorgan's Laws, this is equivalent to
menuChoice != 1 && menuChoice != 2 && menuChoice != 3
EDIT:
How about this? this would allow you to have a non-contiguous set of numbers and is far more extensible than having a million || statements...:
int[] menuOptions = { 1, 2, 3 };
...
while(!menuOptions.Contains(menuChoice))
Or:
do {
// etc.
} while(menuChoice > 3 || menuChoice < 1);
Just to provide yet one more solution:
using System.Collections.Generic; // for the List<T>
do
{
}
while (!(new List<Int32>(new[]{ 1, 2, 3 })).Contains(menuChoice));
And yes, this is not the best solution, it is, however, an alternative (and useful if your list of options grows).