Writing switch statements using integers [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
if (intDaysOverdue <= 30)
{
decInterestRate = 0m;
}
else if (intDaysOverdue >= 30 && intDaysOverdue <= 59)
{
decInterestRate = .5m;
}
else if (intDaysOverdue >= 60 && intDaysOverdue <= 89)
{
decInterestRate = .10m;
}
else if (intDaysOverdue >= 90)
{
decInterestRate = .15m;
}
I need to write this info using a switch statement, but can't seem to figure out how

You cannot do what you want with a switch, but you can simplify it to:
if (intDaysOverdue <= 30)
decInterestRate = 0m;
else if (intDaysOverdue <= 59)
decInterestRate = .5m;
else if (intDaysOverdue <= 89)
decInterestRate = .10m;
else
decInterestRate = .15m;
Your >= 30 and >= 60 conditions are not needed, as they are already true because of the prior if statements.
Switch/Case is more suited for specific values, not ranges. This is what the if statement is for.
If your interest rate increases .5 for every 30 days, similar to as #EZI suggested in the comments, you could further simplify the code to:
decInterestRate = ((int)Math.Min(intDaysOverdue, 90) /30) * .5;

you can't use switch here (you can manipulate it with a default case but why do that?)
switch and case are meant to test individual values, your condition needs an if statement.

Related

Do-while loop won't stop after the while part gets false C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is a part of a code which determines whether a number is prime or not. I know it could be solved in other ways, but I cant figure out why this loop wont stop if I put in a "5" as a number. The divisor reaches 5 after the third "divisor++;" (the divisor starts from 2) but the while loop wont quit.
Can anyone help me?
do
{
if (number % divisor == 0)
{
Console.WriteLine("Number is not a prime.");
}
if (divisor == number - 1)
{
Console.WriteLine("Number is prime.");
}
divisor++;
} while (number % (divisor -1) != 0 || divisor != number);
The condition should probably be ... != 0 && divisor != number.
Difference being && rather than ||.
while (number % (divisor -1) != 0 || divisor != number)
Above statement would never let it break.
For example if divisor is 5 then
5 % (5-1) would 1 and loop will continue
when divisor is 6 then
6 != 5 and it will continue
you should use
while (number % (divisor) != 0);

check condition with range in c# (without using if else statement) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The basic idea we follow is
if (i > 0 && i < 100) {
} else if (i > 100 && 1 < 150) {
}
This is the basic idea for range check..
Is there any good way to check these type of conditions.
Thanks in advance for the help!
int endX=200;
Click on below link you will get what is the difference #Steve
var switchCond = new Dictionary<Func<int, bool>, Action>
{
{ x => x <= 290 , () => endX=244 },
{ x => x <= 530, () => endX=488 },
{ x => x <= 790 , () => endX=732 },
{ x => x <=1000 || x > 976 , () => endX=976 }
};
switchCond.First(sw => sw.Key(endX)).Value();
[Switch case: can I use a range instead of a one number
use ternary operator
var range =
i < 100? "Range1":
i < 150? "Range2":
i < 200? "Range3":
i < 250? "Range4":
i < 300? "Range5":
"Range6";
This is example only to show technique. obviously, you must adapt it to your code objectives and appropriate range definitions. (by the way, in your example, using if- else if, your code misses the value 100. you need to decide which range 100 should be included in, and change one of the inequality operators to either <= or >=.
you could have switch construct "handle" ranges by use of a List of your bounds:
List<int> bounds = new List<int>() {int.MinValue, 0, 100, 150, 200, 300, int.MaxValue };
switch (bounds.IndexOf(bounds.Last(x => x < j)))
{
case 0: // <=0
break;
case 1: // > 0 and <=100
break;
case 2: // > 100 and <= 150
break;
case 3: // > 150 and <=200
break;
case 4: // > 200 and <=300
break;
case 5: // >300
break;
}
where you may have to add some additional checks to

MinHeap implementation in c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working on a MinHeap implementation for school and I have encountered a problem. The code typically works well but sometimes generates an argument out of range exception in my heapify method. I have tried to isolate the problem but I am a terrible debugger.
Here is my code for the function:
private void Heapify(int i)
{
int least;
int leftchild = 2 * (i + 1) - 1;
int rightchild = 2 * (i + 1);
if (leftchild < heap.Count && (heap[rightchild].CompareTo(heap[i]) < 0))
{
least = 1;
}
else
{
least = i;
}
if (rightchild < heap.Count && (heap[rightchild].CompareTo(heap[least]) < 0))
{
least = rightchild;
}
if (least != i)
{
T temp = heap[i];
heap[i] = heap[least];
heap[least] = temp;
this.Heapify(least);
}
Out of range exceptions are generally easy to track down. Basically, you have to make sure that whenever you're accessing an item in an array via indexes, said array's count / length is greater than the index. In other words, ensure that in every call to heap[#index], #index < heap.Count (either by straight checking it or by your method's logic)
if (leftchild < heap.Count && (heap[rightchild].CompareTo(heap[i]) < 0))
If rightchild >= heap.Count, this will give you an exception.

Syntax errors in if/else statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am very new to c# and while working on a basic program I am receiving this error(Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement) and cannot figure out why it is appearing.
if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement
{
Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices.");
}
else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range
{
Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices.");
}
else if (pizzaDiameter >= 24 && pizzaDiameter < 30)
{
Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices.");
}
else (pizzaDiameter >= 24 && pizzaDiameter <= 30)
{
Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices.");
}
else // pizza diameter was not a whole number
{
Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here.
}
else //pizza diameter must be between 12-36
{
Console.WriteLine("Pizza diameter must be a whole number.");
}
There's something wrong with your control structure, i.e. you've got only one if(), but three times else.
Also, try to think about the problem and you'll notice that you can simplify the whole structure significantly (and also skip many checks):
if (pizzaDiameter < 12) // All diameters below 12 will use this branch.
Console.WriteLine("Your pizza seems to be too small.");
else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above.
Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices");
else if (pizzaDiameter < 24) // Again you won't have to care for less than 16.
Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices");
// ...
else
Console.WriteLine("Your pizza seems to be too big.");

How to condense my if statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been asked to create a mark to grade converter in Windows Form Application.
My code below is from the click of a button. Once a user has input their mark into 'Markbox' and the button is clicked the if statement will run and it will find the correct range of the mark. Then it will display a grade, relevant to the mark in 'Gradelb'.
Below is the code under the button click command. I wanted to condense it down to reduce code line space as well as making it more manageable.
void SubmitBtn_Click(object sender, EventArgs e)
{
int mark = int.Parse(Markbox.Text);
if (mark >= 45 && mark <= 50) Gradelb.Text = "A*";
else if (mark >= 40 && mark < 45) Gradelb.Text = "A";
else if (mark >= 35 && mark < 40) Gradelb.Text = "B";
else if (mark >= 30 && mark < 35) Gradelb.Text = "C";
else if (mark >= 25 && mark < 30) Gradelb.Text = "D";
else if (mark >= 20 && mark < 25) Gradelb.Text = "E";
else if (mark >= 0 && mark < 20) Gradelb.Text = "U";
else MessageBox.Show("Please enter a mark between 0-50");
Apologies for any errors or incorrect terminology, I am a new Apprentice employee.
string Gr = new string[] { "A*", "A", "B", "C", "D", "E", "U" };
if(mark >=0 && mark <= 50)
Gradelb.Text = Gr[10 - Math.Max(4, (int)Math.Ceiling(mark/5f))];
else
MessageBox.Show("Please enter a mark between 0-100");
A word of caution: After living a decade of "one-liner"'s life, I can advise you one thing: There is no guarantee that this code will be any more efficient than yours.
Explanation
Since the grades and the marks range they are linked with follow a fixed pattern, I created an array of grades so that I could refer to each grade by array index. Now all I need is a expression that could convert a given number to index.
46-50 => 0
40-45 => 1
and so on...
This can be done by dividing the number by 5 (since that is the group size in your example). So for example dividing 41 by 5 will give you 8.2. Doing a Ceiling() (which returns nearest greater or equal integer) on it will give 9. Subtracting this value from 10 will give you the index of second group (which is grade A).
Math.Max() (which returns larger of the two parameters) is simply there to ensure that values which are out of array bounds do not cause an exception. This will be the case when marks are 15 or less.

Categories