Getting the sum of an array with increments of 10 JAVA - java

Explanation
I was given a task in my Grade 12 Computer Science class that just totally has me stumped. So far I have tried using a bunch of if statements (While i know that is not the best way of doing I though for sure it was going to work) but that didn't work. I then tried to use nested loops but that didn't work either here is the code that I created so far for this method.
Code (Note: Max=1000)
private static void totals2 (Scanner user_input,int max){
int[] num = new int[max];
int[] total=new int[10];
System.out.println("Welcome to totals\nThis method gathers input and displays the sum depending on which category they fall in");
System.out.println("Enter numbers from 0-99 only (Up to 1000 inputs)\nEnter any number outside of 0-99 to stop collecting\n");
for (int i = 0; i < num.length; i++) {
System.out.println("Please enter a number to be stored in index: " + i);
num[i] = user_input.nextInt();
if (num[i] < 0 || num[i] > 99) {
break;
}
}
for(int i = 0; i < 100; i +=10){
int j;
int k=(i/10)-1;
for(j=0 ;j<1000;j++){
if (num[j] <= i){
total[k]+= num[j];
}
}
System.out.println(total[k]);
}
}
Question
Create a procedure that will output the total of all numbers (in an array) entered less than 10, the total of all numbers entered less than 20, the total of all numbers entered less than 30, ... and the total of all numbers entered less than 100 (so 88 will be included in both totals for numbers less than 90 and less than 100).

As it is your assignment, I will not post any code here. Just some thoughts.
Do you need to save the number out of 0 to 99? If not, check your first loop.
for your second for loop, if i=0, what value will be k? if i=10 what value will be k?
I did not run your algo, that's all issues I found while reading it. Learn how to use a debugging tool will be helpful for your further study. (Recommend Intellj for Java development)

Great first question:
This already has answers for your problems, normally your question would probably get closed as a duplicate of these, but I think it should be left open so you can get some details about your code since you did such a good job with your first question.
Since you are pretty close to getting this correct I am just going to say that everything you need to get your code working is in the two questions linked below.
How to use Scanner properly:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
How to iterate over an Array:
How to avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException?
Effectively Debugging:
What is a debugger and how can it help me diagnose problems?
What is a stack trace, and how can I use it to debug my application errors?

First off, you can not iterate through an Array with integer index values greater than the number of indexes (- 1 because arrays are zero (0) based) contained within the Array otherwise you will simply end up with an ArrayIndexOutOfBoundsException. If there are only 20 elements contained within the Array then you can only iterate from 0 to 19....not 0 to 999. With this in mind, change 1000 to num.length and you should be fine with the exception of....
For your for loop used to increment by 10 for the "find values less than" value, initialize the variable i to 10 instead of 0. Think about it...do the math...what do you think will happen when you try to divide 0 into 10 then subtract 1 [(0 / 10) - 1]? You end up with an invalid index value for the variable k and therefore, another ArrayIndexOutOfBoundsException.
Also, if you read the question carefully you can see that what is required are the sums of values supplied that are less than 10, less than 20, less than 30....less than 100. Not Less Than or Equal To (... <= ...). Correct your if statement condition within your second for loop.
Food for thought:
You might want to ask the User to supply the max array index value as
well and eliminate that as a parameter for the totals2() method. Place the explanation for it into the "Welcome" message.

Related

Why do I need to assign -1 to an int for a random number guesser in Java

this is my first question here so I apologize if this has been answered before. I am working through beginner loops in university and am following along my textbook to program a number guesser. The code works, but what I don't understand is why on line 17 I needed to create an int and give it a value of -1. Screenshot of code here. Any explanation would be great, thanks!
This is simply to guarantee that the loop doesn't exit on the first time through. The while condition is evaluated before the code inside it is. If it had been initialized to 0 and the number had been 0, none of the code inside the while would have been executed. Think about with this part of your code
int number = (int)(0 * 101) //Math.random() returned 0
int guess = 0;
while(guess != number) // while(0 != 0) this is always true so the while loop won't be executed
It isn't likely that you will ever have this actually affect your output, it is a possibility, and so rather than check if number is 0, guess is set to a number that it is guaranteed to execute the while loop at least once.
You will need a loop to ask the question several times till the answer is correct. In a loop you can test the value of a variable in the beginning of the loop or in the end. If you test in the beginning of the loop, then the variable must have a value, otherwise the program would not compile. So, to start the loop you must give any value that for sure is not the correct answer, for example any negative number or any number greater than 100.
You can initialize the variable guess to any integer. u just need a integer to compare it with the variable number . feel free to replace it with any integer as it re initialized in while loop if it is not equal to variable number .

Trying to Count the Number of Operations in Code

I have recently been reading Sedgewick's Algorithms Book, and I came across an example I didn't quite understand...
Using this code, Sedgewick mentions that the if statement is run precisely
N x (N-1)(N-2)/6 times.
I don't quite understand why that is.... I see that there are the triple nested loops, each with an upper bound that is increasing, but why is the value divided by six?
I ask for your understanding that I am not good at math, so the explanation may be a little bit cheesy.
In order to 'if(a[i] + j[i] + k[i]) statement' inside the code be executed The variables i, j, and k that point out an array 'a' index in Tripple for loop must fit the condition of the statement (0<= i <j<k <N), right?
For example, N is 4.
It seems to be available through the permutation (4P3 = 4^3) that selects three of the four, but if 4 is selected in 'i' as shown in the picture above, you can see that progress is blocked in 'j' for-loop (j = 4+1; j<4; j++).
So We can't get the number of times an if statement will run with a simple sequence.
What we need is a combination (nCr).
When index flows from 0 to N-1,
The number of cases (i,j,k) that satisfy i < j < k(=> if statement can run) can be obtained by the formula nC3.
According to this formula, if statement is run precisely N x (N-1)(N-2)/6 times
I hope you understand it well and if you don't, please leave a comment!
Have a nice day!

Getting exponents in a method without using Math.pow()

This was the problem I was given:
Create method lastDigit that is passed two positive integers. The first integer is the base and the second integer is the exponent. lastDigit will return the last digit of base^exponent. You need to think before you write your code. Hint: You do not need to actually find the product of base^exponent.
Then I need to use the method to find answer the questions below:
1) What is the last digit of 3^400?
2) What is the last digit of (3^0)(3^1)(3^2)(3^3)…(3^10)?
3) What is the last digit of the product of (3^0)(3^1)(3^2)…..(3^400)?
Here's the code that I wrote:
public static int lastDigit(int m, int n){
int p=1;
for(int i=1; i<=n; i++)
p=p*m;
return p%10;
}
However when I was trying to find the answers to the questions, I keep getting -1 for both the first and third questions, and 1 for the second question. Is there something wrong with the code, or how can I get the right answer?
You or a program you wrote may be suffering from Integer Overflow.
This is caused by chronic limitation of the int type.
Symptoms include
Negative integers that are really supposed to be positive
Small numbers that are supposed to be big
This condition can be controlled by ensuring that your int values don't exceed 2 billion.
If symptoms persist, see a debugger, or print out intermediate values.
*side effects may include frustration, throwing your computer out of a window, and/or deleting important system files.
But in all reality, let's say that you have a base of seven.
7=7
7*7=49
49*7=343
The last digit is 3.
However, if you, only take the last digit in between operations,
7*7 =49 -> 9
9*7 =63
The last digit is still three.
Doing this keeps the number well below the int limit.
This is actually what the p=(p*m)%10; solution is:
p= (p*m) %10
multiply the previous digit by the exponent take the last digit
The int variable is overflowing. Try changing p=p*m to p=(p*m)%10.

Creating java array to convert numeric score to alphabetic grade

novice java programmer, new to arrays, working on an assignment of the following prompt:
Write a program that will plot the grade distribution of scores of a test. The scores are inputted one at a time and the loop will break when a score of 0 (zero) is entered. The output will print a * for each score in the letter grade and will place the letter grades on the horizontal axis below the graph.
My main issue is in the creation of an array that enables me to sum the number of scores in each grade (A, B, C...). I am prohibited from the use of if or switch statements in this conversion. I'm wondering where to start in the creation of this array. Thanks!
Does it have to be an array? If not, a Map is a good choice for this type of scenario. The keys of the map are the various grades (A, B, C, etc) and the value of each key is an integer (or long) to hold the number of grades for that key. So, the basic logic is to get the counter from the map for the grade (i.e. key), increment it and put it back into the map.
If you don't mind using external libraries, then Guava's Multiset is an even better fit.
EDIT: OK so you need to use an array, but one challenge (if I read your post correctly) is that you can't use if or switch statements (presumably to access the array). One possible way around this is to assign 'A' to index 0, 'B' to index 1, etc. Then you can use the following notation for array indexing:
char gradeAsChar = ...; //I'll leave this to you to get the grade as an (uppercase) char
gradesArray[gradeAsChar - 'A'] = gradesArray[gradeAsChar - 'A'] + 1;
'A' - 'A' is 0, 'B' - 'A' is 1, etc. The above, of course, is ripe for index out of bounds issues if the character is unexpected so you'll need some error handling there.
Of course, if you don't care about memory efficiency (which you always should while coding!), you can make a new array like so:
int[] grades = new int[101];
Then whenever a user enters an input, you can do something like:
int grade = input.nextInt();
grades[grade] = grades[grade] + 1;
You can figure out the number of grades that equal A by running something like:
int A = 0;
for (int i = 91; i < 101; i++){
A += grades[i];
}
That's what I thought of when you said you weren't allowed to use if or switch statements. Let me know if it helped. Again, terribly inefficient, but at least you keep track of all the scores you have. That's a plus.
This should be a rough runtime of O(n), but could be better I think.
Good luck!
EDIT: You can do a more efficient version of the method above by using the concept of integer division. What is integer division you may ask, it's when you divide two integers, say 10/3 and the answer might be 3.333 but java discards the fractional parts so that the answer is 3.
Therefore, if you divide by 10, you can use the result to get which scores are A and so forth. For example: 92/10 = 9, 97/10 = 9, 83/10 = 8, etc. The caveat is that the score is from 91-100 for A so you have to subtract 1 before applying this concept.
This should reduce the array from 101 elements to 10 since you are only keeping track of the number in the tens digit, which is more important anyways. You may be able to further optimize this but again, this isn't my homework so I don't want to spend too much time on it. I thought of this when I woke up :).
Hope this gave you some food for thought!

How to output this to the screen?

I'm currently studying for my introductory CS final, and I'm having a really rough time with a few problems. The one I'm most worried about asks me to produce the code, in Java, to create the following output to the screen:
+
+++0
++++++00
++++++++++000
... (this pattern continues for 200 lines)
This might seem like a very basic question, but how do I go about doing this? I know that I should write some arrays and use for loops to go through them and output stuff to the screen, but I would really appreciate some guidance on how to solve this problem, along with others of its ilk. Thanks!
The pattern for the number of 0 is simply an arithmetic sequence. The number of + is as follows:
Row 1: 1
Row 2: 3 = 1 + 2
Row 3: 6 = 3 + 3
Row 4: 10 = 6 + 4
Turns out that these are triangular numbers. So, calculate the triangular number for each row in a loop, and have a nested loop that prints + that many times, then print the required number of 0.
I don't think this deserves a -1. Beginner question is not equal to a bad question.
As for the question itself. You have to carefully identify the pattern first and then word it in plain English. The pattern is quite simple.
Start with 1 cross and 0 zero. For each iteration, increase the growth
of crosses by 1 (so it's +1, +2, +3...) starting with a growth of 2
units and increase the growth of zeroes by 1 starting at 1 unit.
Now put this into pseudo-code and then code it. Be sure to understand the patterns first. I cannot stress this enough. Going right into coding will not help you.
First you need to be able to recogonize the pattern, then you need to be able to code it.
I'm going to go out on a limb and suggest that you are mixing the two "steps" of this problem together, so let's be very specific in dividing them.
The (parenthesis) items are the _additional_ elements.
index 0 : +
index 1 : +(++)(0)
index 2 : +++(+++)0(0)
index 3 : ++++++(++++)00(0)
so a good guess is that the pattern could be described as:
the previous number of +'s (and index + 1 more),
followed by the previous number of 0's (and one more).
combined with
index 0 is "+"
You might want to calculate index 4, 5, and 6 from this "rule" and see if it seems to describe the pattern correctly.
Now that you have the pattern, you really only need two variables, the number of + signs, and the number of 0s. You can calculate the "next" one from the previous one. The coding shouldn't be too hard, but if it is, then post your program and your "new" problem with that program in another question.
public class Answer {
public static void main(String[] args) {
int plusCount = 1;
for(int i=0; i<200; i++) {
for(int j=0; j<plusCount; j++) {
System.out.write('+');
}
plusCount += i+2;
for(int j=0; j<i; j++) {
System.out.write('0');
}
System.out.println();
}
}
}

Categories