Sums of iterations - java

Hello I'm a beginner in Java and I have a question regarding summing the iterations. The question is: Write a program that computes the following expression to 4 decimal places:
(1/10) + (2/9) + (3/8) + (4/7) + (5/6) + (6/5) + (7/4) + (8/3) + (9/2) + (10/1)
So far I have:
public class Expression
{
public static void main(String[] args)
{
float x;
for ( float m=1, n=10; m<11; m++,n--)
{
x = (m)/(n);
}
How would I go about summing all the iterations the for loop makes?
Thanks everyone :)

public class Expression
{
public static void main(String[] args)
{
float x = 0;
for ( float m=1, n=10; m<11; m++,n--)
{
x += (m)/(n);
}
System.out.println(x);
}
}

Nice code, i like it so far!
You need a variable like: sum = sum + x; or shorter sum += x; within the loop. Define it with float sum = 0; before the loop.
You can also directly use x and define it with 0, but the compiler will optimise it anyway, so there is no speed gain.

The += operator. x += y is equivalent to x = x + y. In your case, you will have x += (m)/(n), resulting in, ultimately:
public class Expression {
public static void main(String[] args) {
float x = 0;
for ( float m=1, n=10; m<11; m++,n--) {
x += (m)/(n);
}
}
}

Change
x = (m)/(n);
to
x += (m)/(n);
Since x is already in scope outside the loop, it is possible to do this, and x will persist between iterations. I recommend changing the loop, however:
float x=0;
for ( float m=1; m<11; m++)
{
x += (m)/(11-m);
}
It may be more straightforward to read in the future.

Related

math.sqrt gives me incorrect result (double)

I am writing a program that prints 100 random coordinates within a circle. The circle has the radius 10 and its center is located at (0,0). However, some of the coordinates y:value is incorrectly calculated when I'm using: y = Math.sqrt(100 -x^2) The result is like off... Why is that ? (See picture) For positive y:values, they get too big sometimes and its because of the math.sqrt calculation with doubles.
package RKap14;
import ZindansMethods.ZindanRandom;
public class Dot {
public double x;
public double y;
public static void main(String[] arg)throws Exception {
//Create the array with null fields?
Coord[] c;
//Decide how many fields
c = new Coord[100];
//Create an object of class Coord in each slot of the array
for(int i = 0; i<c.length; i++) {
c[i] = new Coord();
}
//Assign random coordinates for each field x & y
for(int i = 0; i<c.length; i++) {
c[i].x = ZindanRandom.randomized(-10,10);
//Since sometimes Java calculates wrong and gives numbers above 10 and below -10...
while(c[i].x > 10 || c[i].x < -10)
c[i].x = ZindanRandom.randomized(-10,10);
c[i].y = ZindanRandom.randomized(-Math.sqrt(100-c[i].x*c[i].x), Math.sqrt(100-c[i].x*c[i].x));
}
//Print out the coordinates in form: (x,y),(x1,y1)...(x99,y99)
for (int i = 0; i<c.length; i++) {
System.out.print("(" + c[i].x + "," + c[i].y + ")" + ",");
}
}
}
class Coord {
double x;
double y;
}
The random method I am using:
//Gives random number a to b. For example -10 <= x <= 10
public static double randomized (double a, double b) {
return (a-1+Math.random()*Math.abs(b-a+1)+1);
}
I don't know what to try. I tried doing this program with a trigonometric approach but I'd rather understand why the calculator is doing its job wrongfully. Are there too many decimals? Can I do something about it ?
Circle test
your random function is generating numbers outside the given range
for example if you substitute the values into your equation and and use 1 as the value returned from Math.random() you will get 101.
Try the following random function instead:
public static double randomized(double min, double max)
return Math.random() * (max - min) + min;
}

What is the name of the Math function (process) that programming languages such as Java use to progress through a set of integers by 10?

The code below that I have written in Java returns the reverse of a number. My question is what is the name for the math process whereby the formula for obtaining the value for my variable reverseNumber is
a =0; (a*10) + b = a;
I remember seeing this in one of my calc or statistic classes before, I just do not remember what it is called. Thanks.
public static int reverse(int number) {
int reverseNumber = 0;
while(number !=0){
lastDigit = number % 10;
number /= 10;
reverseNumber = (reverseNumber * 10) + lastDigit;
}
return reverseNumber;
}
If you are looking for a function to reverse an integer, there is no direct function but you can achieve it using a combination of functions shown below:
public class Main {
public static void main(String[] args) {
int x = 135246;
int y = Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
System.out.println("Reverse of " + x + " = " + y);
}
}
Output:
Reverse of 135246 = 642531
Check Integer and StringBuilder classes to learn more about these functions.

How to print each number of a given number separately?

I have a code is written that is supposed to print each of the numbers separately. Heres an example.
printDigits(1362) prints
2
6
3
1
printsDigits(985) prints
5
8
9
You can pull apart a number into its digits using / 10 and % 10.
I have started some code the way I was taught but I am not sure what to do with the other variables.
Please have a look:
public class Main {
public static void main(String[] args) {
System.out.println(printDigits(1362));
System.out.println(printDigits(985));
}
public static int printDigits(int x){
int y = x % 10;
while (x > 0){
x = y;
System.out.println(x);
x = x / 10;
}
return x;
}
}
Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.
printDigits method should be like this:
public static void printDigits(int x) {
int y;
while (x > 0) {
y = x % 10;
System.out.println(y);
x = x / 10;
}
}
And the calling of the method will be like this:
printDigits(1362); // without the System.out.println()
There are various ways to achieve such results. You can better understand all solutions in these answers.
public static void printDigits(int num) {
while(num>0) {
int remainder = num%10;
num = num/10;
System.out.println(remainder);
printDigits(num);
}
}
You can use recursion to make it even more efficient.
You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out".
Remove the System.out.println around your function calls.
You don't need to return a number, so you can change your return type to void:
public class Main {
public static void main(String[] args) {
printDigits(1362);
System.out.println();
printDigits(985);
}
public static void printDigits(int x) {
while (x > 0) {
int y = x % 10;
System.out.println(y);
x = x / 10;
}
}
}

Turning a iteration into a recursion

Good day!
I just wrote a code as an iteration which is supposed to sum up even numbers in between 0 and y.
I've been sitting now on my desk for about two hours thinking on how to write the same code in a recursion - without any progress so far.
The only explanations I find on the internet explain it for one simple repeat of one specific change - unlike my code which includes two. ("result = result + x;" and "x = x + 2;" )
Could someone please explain to me how I turn this kind of iteration into a recursion? Thanks in advance!
public class Sum {
static int method(int y) {
int result = 0;
for (int x = 2; x<=y;)
{
result = result + x;
x = x + 2;
}
return result;
}
public static void main(String[ ] args) {
int result = method(35);
System.out.println("Sum of even numbers between 0-35: " +result);
}
}
The total of the numbers is the total of this number plus the total of the number minus 2. Written in code:
int method(int y) {
if (y <= 0) {
return 0;
} else {
return y + method(y - 2);
}
}
Needless to say that recursion in this form is not necessary, and will create a StackoverflowException when y is a really large number. Some languages allow you to write a recursive function and indicate it is a tail recursion so that the compiler actually transforms it to an iteration.

How to, in one line, add a variable in a for-loop?

Here is a snippet of Java code that has really baffled me over the past couple of days. The goal is to insert only one line of code in the given place such that the number printed after "Given: " is 5050. I do not want to write multiple lines or change any of the existing lines of code.
public static void main(String args[]) {
for(int x = 1; x <= 100; x++) {
// In one line, write code such that 5050 is printed out.
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
}
I know that 5050 is the sum of the first 100 natural numbers, and this is evident in the for loop, which sets x to each of these consecutive numbers during each occurrence. If I could find a way to add the values of x to each other, that could have been a solution. The problem is that I want the value of x to be 5050 when I exit the loop, so that the "Given: " line prints out 5050 as the value of x.
I also know that I can use another variable to store the temporary value of the sum, i.e. y += x;, however, this would be impossible since I wouldn't be able to declare y multiple times within the loop, and the value of x needs to be 5050, not y. Also, if I try x += x, the result will definitely not be 5050 because of the way the variable is being changed by both the for loop execution and the addition operation.
So, is there actually a solution to this problem?
You have to make two changes. First, you must make x visible outside the for loop. Otherwise there is literally no way to access it after the loop. Then, all you have to do is set x to the desired value (minus one), which will terminate the loop after the value is incremented and tested. Like,
int x;
for (x = 1; x <= 100; x++) {
x = 5050 - 1;
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
Outputs
Given: 5050
Expected: 5050
The only other legal way to write it is like
for (int x = 1; x <= 100; x++) {
} int x = 5050; {
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
which isn't "really" kosher in my opinion. Note that we terminate the loop, add a new x variable and an empty block in that one line.
You can close the parentheses of the for-loop in this line, and introduce a new variable x in the same line:
public static void main(String args[]) {
for(int x = 1; x <= 100; x++) {
}; String x = "5050"; {
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
}
Greetings from Bobby Tables...
EDIT:
As #ElliottFrish has pointed out, the following trick with System.exit(0) after first loop iteration does not work, because there is still no x in scope:
// Doesn't work.
public static void main(String args[]) {
for(int x = 1; x <= 100; x++) {
System.out.println("Given: 5050"); System.out.println("Expected: 5050"); System.exit(0);
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
}
However, we can force this System.exit(0);-solution to compile by moving the given System.out.prinlns into an unrelated method:
class BobbyForloops {
public static void main(String args[]) {
for(int x = 1; x <= 100; x++) {
System.out.println("Given: 5050\nExpected: 5050"); System.exit(0); }} public static void unrelated(int x) {{
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
}
}
Now it again compiles and outputs what was asked. But it's just a variation of the first solution.
Edit: Thanks #Dukeling for proposing a much shorter solution that uses System.exit(0);. #Dukeling's solution is actually even shorter, because it uses a break instead of System.exit(0).
The comment within the code doesn't say where the one line has to be placed, although your post suggested it needs to replace the comment. Taking the comment literally though, this works:
public class X {
private static final String x = "5050";
public static void main(String args[]) {
for(int x = 1; x <= 100; x++) {
// In one line, write code such that 5050 is printed out.
}
System.out.println("Given: " + x);
System.out.println("Expected: 5050");
}
}

Categories

Resources