How would one do > x < in C# - c#

I'm attempting to make a random number generator that then selects one of three options based on the random number. I would like to use > x < as the second choice of three but it gives me an error:
Operator '>' cannot be applied to operands of type 'bool' and 'int'
Here's the code:
int rand;
Random myRandom = new Random();
rand = myRandom.Next(0, 90);
if (rand < 33)
{
}
if (33 > rand < 66)
{
}
if (rand > 66)
{
}

Well the simplest option is to use else if so you only need to check one condition anyway - which means it would handle 33 as well (currently not handled):
if (rand < 33)
{
Console.WriteLine("rand was in the range [0, 32]");
}
else if (rand < 66)
{
Console.WriteLine("rand was in the range [33, 65]");
}
else
{
Console.WriteLine("rand was in the range [66, 89]");
}
If you do need to test two conditions, however, you just want && to check that they're both true:
// I've deliberately made this >= rather than 33. If you really don't want to do
// anything for 33, it would be worth making that clear.
if (rand >= 33 && rand < 66)
If you find yourself doing this a lot, you might want to have an extension method so you can say:
if (rand.IsInRange(33, 66))
where IsInRange would just be:
public static bool IsInRange(this int value, int minInclusive, int maxExclusive)
{
return value >= minInclusive && value < maxExclusive;
}

You should use the and && operator as in
if (rand > 33 && rand < 66)
{
}
This makes sure the rand is less than AND greater then the values specified

To check the both bounds of the value you need two comparisons.
You probably want to use the <= operator instead of < in that comparison, otherwise the code will do nothing for the values 33 and 66:
if (rand < 33)
{
}
if (33 <= rand && rand < 66)
{
}
if (rand >= 66)
{
}
You can also use else to get rid of some comparisons:
if (rand < 33)
{
}
else if (rand < 66)
{
}
else
{
}
Note: You have a random value between 0 and 89, so if you want each if statement to be used in one third of the cases, you would use values 30 and 60 instead of 33 and 66.

Related

C# - function skip "if" loop

static void PrintPartOfArray(int[] array, int from, int to)
{
int x = array.Length;
if (from > x && from < 0)
{
Console.WriteLine("there is an exeption!");
}
if (to > x && to < 0)
{
Console.WriteLine("there is an exeption!");
}
else
{
for (int i = from; i <= to; i++)
{
Console.WriteLine(array[i]);
}
}
}
static void Main(string[] args)
{
int[] array2 = new int[] { 3, 6, 54, 24, -90, 7, 4 };
PrintPartOfArray(array2,2,7);
}
it supposes to show the "exception error when the function receives a number outside the length of the array, for some reason it not working, when I checked with the debugger it simply skipped the if loops, what have I done wrong?
Consider "early return" for things like this.
if (from > array.Length - 1 || to > array.Length - 1 || from < 0 || to < 0)
{
Console.WriteLine("One of your arguments is out of range.");
return;
}
// Normal, error-free code goes here.
If from and to are greater than x, they can't possibly also be less than 0. Recall that x is the length of an array, which can't be negative. That being said, it's literally impossible for either of your if statements to evaluate to true. Did you mean || instead?
Also, the last index of the array is array.Length - 1, not array.Length. Similarly, the first item in the array is at index 0, not index 1. I think that your array indices are off by 1 here.

Building an exponent calculator

I'm relatively new to programming in C#. I'm building an exponent calculator, and I got it working, but while debugging I came across an issue that I do not understand why I get the output that I get.
This is the class and method in question when I get the output I know is wrong. (note i did later fix it by making it total *= lower in the for loop)
using System;
namespace stars
{
public class Exponent
{
public int Exp(int lower, int power)
{
int total = lower;
if ( power == 0 )
{
//returns 1 for any exponent of 0
Console.WriteLine(" 1");
return 1;
}
else if ( lower == 0 )
{
//returns 0 for any base of 0
Console.WriteLine("0");
return 0;
}
else if ( ( power % 1 ) == 0 ) // check for integer exponent
{
for ( int i = 1; !( i > power ); i++ ) //math
{
lower *= lower;
}
Console.WriteLine(lower);
return total;
}
else
{
Console.WriteLine("error");
}
}
}
}
at the last elseif, where I have my forloop, to (incorrectly) calculate the value of some integer to the power of another integer, I (incorrectly) perform the calculation lower = lower * lower, where lower is the base number.
i.e. 5^4,, 5 = lower, 4 = power
anyways, when I run it at 5^4, the result is 0. Why does it come out to 0? I figured it would work like this
5 * 5 = 25 ---> 25 * 25 = 625 ----> 625 * 625... etc
or is the end value so large that the compiler spits out 0.
First of all you should modify total in your routine and don't modify lower changing given parameter is often leads to errors.
Something like this:
public class Exponent
{
// static: we don't want this
public static int Exp(int lower, int power)
{
// Special cases
if (power == 0 || lower == 1)
return 1;
else if (lower == 0)
return 0;
else if (power < 0) //DONE: you've forgot about this case
throw new ArgumentOutOfRangeException(nameof(power));
// we don't want "power % 1 == 0" case - int power is always integer
// General case: math
int total = lower;
// "!( i > power )" - let's put at simpler (and correct) - "i < power"
for (int i = 1; i < power; ++i)
total *= lower;
return total;
}
}
...
// 5**4 == 625
Console.Write(Exponent.Exp(5, 4));
There are lot of issues in the code, I have fixed them. Though you have to consider other scenarios also. like if lowerand power are negative numbers, if numbers are big, it will not give you the required result.
public static int Exp(int lower, int power)
{
int total = lower;
if (power == 0) {
//returns 1 for any exponent of 0
Console.WriteLine(" 1");
return 1;
}
else if (lower == 0)
{
//returns 0 for any base of 0
Console.WriteLine("0");
return 0;
}
for (int i = 1; i < power; i++) //math
{
total *= lower;
}
Console.WriteLine(total);
return total;
}
There's quite a bit wrong styling wise with the code, and there's obviously an error somewhere or else you'd get the correct output. Let's break it down.
First I'll rewrite your code to be cleaner and easier to read:
public int Exp(int lower, int power)
{
int total = lower;
// 0 to the power of y is always 0
if ( lower == 0 )
return 0;
// x to the power of 0 is always 1
if ( power == 0 )
return 1;
// Your parameters for the Method explicitly state that
// 'power' is always an int, so no need to check
for ( int i = 1; i < power; i++ )
lower *= lower;
return total;
}
The cleanups I did:
Removed unnecessary 'else if's from code, as you are returning from within your 'if' anyways
Removed unnecessary braces reducing clutter
Moved comments to before check, as it is customary to comment code above it not below it
Now the problem is a lot more obvious: You're doing lower *= lower instead of total *= lower. So correct code would be this:
public int Exp(int lower, int power)
{
int total = lower;
// 0 to the power of y is always 0
if ( lower == 0 )
return 0;
// x to the power of 0 is always 1
if ( power == 0 )
return 1;
// Your parameters for the Method explicitly state that
// 'power' is always an int, so no need to check
for ( int i = 1; i < power; i++ )
total *= lower;
return total;
}

Defining boolean local variables

Note: This is my first time using "Stack Overflow" and I am relatively new to C#
(please excuse my poor programming skills at the moment)
My Code:
static void Main(string[] args)
{
Challenge(5, 12);
}
static void Challenge(int num1, int num2)
{
//finds the sum of the two variables
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is...\n{2}", num1, num2, sum);
bool isDivisible = true;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else if ((sum % 10 != 5) || (sum % 10 != 0))
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
//depending on value of 'isDivisible', returns certain functions
if (isDivisible == true)
{
Console.WriteLine("This value is usable.");
Console.WriteLine("\n\nThe remaining usable values are: ");
for (int newVal = sum + 1; newVal <= 55; newVal++) // '+ 1' added to make sure 'sum' is not printed again
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
else if (isDivisible == false)
{
Console.WriteLine("This value is not usable.");
Console.WriteLine("\n\nThese values are considered usable: ");
for (int newVal = 0; newVal <= 55; newVal++)
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
Console.ReadLine();
}
I viewed some articles online, as well as the "Stack Overflow" post: Why compile error "Use of unassigned local variable"? . After learning that local variables are not initialized (and must be given a value), I set my bool value for "isDivisible" equal to true by default.
Question:
Is there a better way to define a local variable that is of Boolean value (at least in the case of the program I am trying to run here)?
Thanks!
Your condition in the else if is wrong, it's not the complement of the first condition, so it doesn't make sense. The correct complement would be:
else if ((sum % 10 != 5) && (sum % 10 != 0))
However, you don't need to use an else if at all, you can just use an else as you want to catch every case that is not caught by the first condition. That also means that you don't have to initialise the boolean variable, as the compiler can see that it always will be set by one of the code blocks:
bool isDivisible;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
Side note: Instead of (sum % 10 == 5) || (sum % 10 == 0) you could just use sum % 5 == 0.
Side note 2: You don't need to compare a boolean variable to true, you can just use it as a condition. Also, you don't need the else if there either. Instead of this:
if (isDivisible == true)
{
...
}
else if (isDivisible == false)
{
...
}
you can use:
if (isDivisible)
{
...
}
else
{
...
}
Comparison expressions in C# will return a boolean value indicating whether or not they are true. So you could simplify your initial assignment to:
bool isDivisible = ((sum % 10 == 5) || (sum % 10 == 0));
Instead of explicitly setting it to true or false. Then your variable would always be set.
This doesn't work for all cases. Sometimes, it is difficult to reduce the comparison operation to a simple expression. But, it is often a handy way to initialize bools.

C# loop positive and negative numbers

I need help with a simple C# program. Simpley yet I don't know the solution. The problem is here: I need to loop (or print on the screen) all numbers in this order: 2, -3, 4, -5, 6, -7, etc. until they reach 100.
Do you have any ideas how to do that? For now I've done something like that:
for (int i = -2; i <= 100; i += 1)
{
Console.WriteLine(i);
}
But I can't get it to work like the order I want, I know I'm doing something wrong in the i += 1 section but I can't figure out how to do that! Thank you for your support.
You can multiple with -1 on odd numbers, therefore use the % operator:
for (int i = 2; i <= 100; i++)
{
int val = i % 2 == 1 ? i * -1 : i;
Console.WriteLine(val);
}
Demo
for(int i=2;i<=100;++i){
Console.WriteLine(i % 2 == 1 ? -i : i);
}
Pretty simple if we use modulo
The steps are faily straight forward. If we will notice the it's the same solution as printing 2-100 but with 1 little twist, for the odd places the number i should be at his negative sign. So the solution will be the same.
Steps:
Loop i to 100
For every iteration we will decide if it's odd or even.
If i is even will multiply it by 1 that will result with i of course. else, that means it's odd and thus, resulting in
multiplying with -1, resulting with minus i.
Code
for (int i = 2; i <= 100; i++)
{
Console.WriteLine(i * (i%2 == 0 ? 1 : -1));
}
You should iterate from 2 to 100 one by one (yes, all are positive values)
Then in loop body you should invert sign on each iteration (by multiplying on "-1") and print the result on screen.
Using bitwise and to spot the odd numbers:
for (int i = 2; i <= 100; i += 1)
{
int toPrint = i
if((i & 1)==1)
{
// It's odd
toPrint = -toPrint;
}
Console.WriteLine(toPrint);
}
static void Main(string[] args)
{
for (int i = 2; i <= 100; i++)
{
if (i % 2 == 1)
{
int j = -i;
Console.WriteLine(j);
}
else
Console.WriteLine(i);
}
Console.ReadLine();
}
As we all did this task in school:
Enumerable.Range(2, Int32.MaxValue - 1)
.TakeWhile(i => i <= 100)
.Select(i => i % 2 == 0 ? i : -i)
.ToList()
.ForEach(Console.WriteLine);

c# More elegant way of finding if number is in range

At the moment in one of my projects that I am working on, I need to check if a value falls between a number divisible by 12 and a number divisible by 12 + 5.
if (Number >= 0 && Number <= 5) {
value = 0;
} else if (Number >= 12 && Number <= 17) {
value = 12;
} else if (Number >= 24 && Number <= 29) {
value = 24;
}
// etc...
The code above works perfectly but I feel that it could be cut down. Does anyone have an alternative way of how to achieve what I am going for but more elegantly?
Use the % operator. (See http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx)
This should work as long as Number is positive; if it's not you'll have to look into how % works for negative numbers:
if (Number % 12 <= 5) {
value = 12*(int)(Number/12);
}

Categories