Reputation: 324
I need to add the following intervals to the for loop (I tried with if statements and the teacher asked me to reduce the amount of coding).
Intervals (Pizza Diameters)
12 - 20 = 8 slices
21 - 24 = 12 slices
25 - 30 = 16 slices
31 - 36 = 24 slices
The following code gives me output that's pretty close to what I need, except that it doesn't adhere to the conditions above. For example if I enter 24 it should only give me the output for 8 and 12 slices.
int[] pizzaSlices = new int[4] { 8, 12, 16, 24 };
for (int i = pizzaSlices[0]; i < inputDiameter; i++) {
if (i == pizzaSlices[0] || i == pizzaSlices[1] || i == pizzaSlices[2] ||
i == pizzaSlices[3]) {
Console.WriteLine("cut in " + i + " slices results in a slice area of " +
Math.Round(areaOfThePizza / i, 2) + " per slices");
}
}
Current Output:
Desired Output:
Upvotes: 2
Views: 69
Reputation: 4213
I added another int
array to hold the pizza diameters. The for
loop iterates from 0
to the length of pizzaSlices
, so 0
to 3
.
The if
statement in the for
loop checks if the user entered diameter is in the range of the current iteration's pizzaDims
counterpart.
int[] pizzaSlices = new int[4] { 8, 12, 16, 24 };
int[] pizzaDims = new int[4] { 12, 21, 25, 31 }; // pizza diameters array
if(inputDiameter >= smallest) {
for (int i = 0; i <= pizzaSlices.Length; i++) {
if(inputDiameter >= pizzaDims[i] {
Console.WriteLine("cut in " + pizzaSlices[i] +
" slices results in a slice area of " +
Math.Round(areaOfThePizza / pizzaSlices[i], 2) +
" per slices");
} else {
break; // no need to continue iterating, if one condition is false then
// the rest will be as well
}
}
}
Upvotes: 1
Reputation: 115691
I couldn't resist adding a somewhat LINQ'y solution:
[Test]
[TestCase(37, Result = 0)]
[TestCase(36, Result = 24)]
[TestCase(35, Result = 24)]
[TestCase(30, Result = 16)]
[TestCase(29, Result = 16)]
[TestCase(26, Result = 16)]
[TestCase(22, Result = 12)]
[TestCase(12, Result = 8)]
[TestCase(11, Result = 0)]
[TestCase(10, Result = 0)]
public int GetNumberOfSlices(int diameter)
{
var pizzas = new[] {
new[] { 11, 0 },
new[] { 20, 8 },
new[] { 24, 12 },
new[] { 30, 16 },
new[] { 36, 24 }
};
var pizza = pizzas.FirstOrDefault(p => diameter <= p[0]);
return pizza == null ? 0 : pizza[1];
}
Upvotes: 2