Write a method countToBy that accepts integer parameters n and m and that produc
ID: 3575973 • Letter: W
Question
Write a method countToBy that accepts integer parameters n and m and that produces output indicating how to count to n in increments of m separated by commas. For example, to count to 10 by 1 you'd say countToBy(10, 1); The following table shows several other calls and their expected output:
Notice that the increment does not have to be 1, such as when counting to 25 by 4s. The count must always end at n, but notice that at will not always be possible to start counting at 1, as shown in the output when n is 30 and m is 4. But the first number should always be in the range of 1 to m inclusive. It is possible that only one number will be printed, as shown in the output when n is 3 and m is 6.
Your method should throw an IllegalArgumentException if either m or n is less than 1. Note that the output does not advance to the next line.
Call Meaning Output countToBy(10,1); count to 10 by 1s 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 countToBy(25,4); count to 25 by 4s 1, 5, 9, 13, 17, 21, 25 countToBy(30,4); count to 30 by 4s 2, 6, 10, 14, 18, 22, 26, 30 countToBy(34,5); count to 34 by 5s 4, 9, 14, 19, 24, 29, 34 countToBy(3,6); count to 3 by 6s 3 countToBy(17,3); count to 17 by 3s 2, 5, 8, 11, 14, 17Explanation / Answer
Answer:
public void countToBy(int n, int m)
{
try
{
if(n<1 || m<1)
throw new IllegalArgumentException("m and n must be greater or equal to 1");
int start = n%m;
while(start<=n)
{
if(start!=n) // to remove comma sign from last number.
System.out.print(start+", ");
else
System.out.print(start);
start+=m;
}
}
catch(IllegalArgumentException iae)
{
System.out.println(iae);
}
}
Explanation :
At first, I am getting the starting value by using modulus operator. Let's say (17,3) is an input. So, at the end 17. Before that, 17-3 = 14 before that 14-3=11. So, if I continue this pprocess, I will end up at 2, which I need to take as starting symbol. And this method is to get remainder of any divsion. So I used modulus operator.
Now, after getting the starting value, I am incrementing it by 'm' value and printing it till it reaches 'n'.
Note: To remove the trailing comma in the last output, I used one more if else to print last value without comma.
:)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.