Difference between while loop and for loop [duplicate] - java

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm new to Java.
If you want to know what I'm trying to solve, check this: http://codeforces.com/problemset/problem/200/B
The two versions of the code, solve the same problem:
1-(for loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
for (int i = 0; i < n; i++)
sum += (sc.nextInt() / 100.0);
System.out.println(sum * 100.0 / n);
}
2-(while loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
while (n-- > 0) {
sum += (sc.nextInt() / 100.0);
}
System.out.println((sum * 100.0) / n);
}
===================================================
Here is the input for each of them:
3
50 50 100
Here is the output of each of them:
1-(for loop): 66.66666666666667
2-(while loop): -200.0
===================================================
Why the output differs?

n-- this will change the value of n and it will make it -1 at end.
so your sum will devide by -1 and you get -200 but in first solution n does not change and at end 200/3 = 66.6

it looks like you are decrementing n and then evaluating which will allow n to become negative
-- X = decrement X then evaluate
X -- = evaluate X then decrement X

Related

Java Math.sqrt function rounding down to zero [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
How to divide 1 by 25(1/25) and get result .04 in java [duplicate]
(4 answers)
Closed 1 year ago.
I am trying to write a function to check a T score value and populate half of a 5x5 array.
public void calcTScores()
{
double temp = 0;
double tempSp = 0;
int n = 24;
this.tScores = new String [5][5];
for (int i = 0; i< this.Headers.length; i++){
for (int j = 0; j<this.Headers.length; j++)
{
if(i < j)
{
tempSp += (n-1)*this.SD[i] * this.SD[i] + (n-1)*this.SD[j] * this.SD[j];
tempSp = tempSp/(n+n-2);
tempSp = Math.sqrt(tempSp);
temp = tempSp * Math.sqrt(0.0833);
System.out.println(Math.sqrt(1/12));
temp = ((this.Mean[i] - this.Mean[j])/temp);
if(temp > 2.25 || temp< -2.25)
{
this.tScores[i][j] = "Y";
}
else
{
this.tScores[i][j] = "N";
}
temp = 0;
tempSp = 0;
}
}
}
}
Any idea why Math.sqrt(0.0833) and Math.sqrt(1/12) would evaluate to different values?
The T score when I add the 1/24 and 1/24 value and take the sqrt keeps evaluating to zero but when I plug in the actual decimal it gives me the answer I would expect
Any ideas why this is occuring?
1/12==0 as per integer division
There's nothing wrong with Math.sqrt. You're passing it the number zero.
Math.sqrt(1/12)
1/12 is a division operation on two integers (namely, 1 and 12), so it's going to produce an integer result. 12 goes into 1 zero times, so the integer result is zero. Thus, your expression is
Math.sqrt(0)
Consider
Math.sqrt(1.0/12.0)
Math.sqrt(1/12d)
Cast 1/12 to a double by casting one operand to a double.

Divide an int into whole numbers [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
I am looking for a way to divide an int into whole numbers.
What I mean by this: if I have a number 30 and I want to divide this by 4, I want the output to be 8,8,7,7.
Is there a way in Java to do this?
Thanks in advance.
Sure, Java is turing complete and therefore allows you to implement any algorithm.
I assume that the difference between the resulting numbers should be at most one - you did not explicitly write this.
Try this:
final int input = 30;
final int numberOfPieces = 4;
final int quotient = input / numberOfPieces;
final int remainder = input % numberOfPieces;
int [] results = new int[numberOfPieces];
for( int i = 0; i < numberOfPieces; i++ ) {
results[i] = i < remainder ? quotient + 1 : quotient;
}
This code first calculates the integer quotient and then equally distributes the remainder to the first "pieces".
Since you don't want equal splits of the number, what you may do is :
Divide the number by how many ever parts you want.
Round() the result
Add up the rounded of number how many ever times required & check if sum is same, if not add or subtract 1 as necessary.
Eg: N = 150 , parts = 4
=> 37.5 , Round it round(37.5) => 38
Now, 38*4 = 152 and 152-150 = 2 so subtract 2 from a number and your answer is 38, 38, 38 & 36.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float number = 30.0f;
float parts = 4.0f;
float val = number / parts;
val = Math.round(val);
if (val * parts == number){
System.out.println("Numbers are:");
for (int i = 0; i < parts; i++)
System.out.println(val);
}
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for(int i = 0;i < parts - 1; i++)
System.out.println(val);
System.out.println(val - diff);
}
}
}
Output:
Numbers are:
8.0
8.0
8.0
6.0
If you want to equally share the difference in the above case then just replace the else part with this:
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for (int i = 0; i < parts - diff; i++)
System.out.println(val);
for (int i = 0; i < diff; i++)
System.out.println(val - 1);
}
Your output will be:
Numbers are:
8.0
8.0
7.0
7.0

can someone explain the steps to compute this equation? Java

Write a program that computes the following equation.
100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
I am not asking for a solution. Yes this is a homework problem, but I am not here to copy paste the answers. I asked my professor to explain the problem or how should I approach this problem? She said "I can't tell you anything."
public static void main(String[] args){
int i;
for(i = 100; i >= 1; i--)
{
int result = i/j;
j = j+1;
System.out.println(result);
}
}
You can try to observe a "trend" or "pattern" when solving questions of this type.
Given: 100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
We derived: Numerator/Denominator, let's call it n divide by d (n/d)
Pattern Observed:
n - 1 after every loop
d + 1 after every loop
So, if you have 100 numbers, you need to loop 100 times. Thus using a for-loop which loops 100 times will seemed appropriate:
for(int n=0; n<100; n++) //A loop which loops 100 times from 0 - 100
To let n start with 100, we change the loop a little to let n start from 100 instead of 0:
for(int n=100; n>0; n--) //A loop which loops 100 times from 100 - 0
You settled n, now d needs to start from 1.
int d = 1; //declare outside the loop
Putting everything together, you get:
int d = 1;
double result = 0.0;
for (int n=100; n>0; x--)
{
result += (double)n/d; //Cast either n or d to double, to prevent loss of precision
d ++; //add 1 to d after every loop
}
You are on the right track. You need to loop like you've done, but then you need to SUM up all the results. In your example you can try:
result = result + i/j;
or
result += i/j;
Note that the declaration of result needs to be outside the loop otherwise you are always initializing it.
Also think about the division (hint), you are dividing integers...
What you have is a series.
There is more than one way to define a series, but all things being the same it's more intuitive to have the index of a series increase rather than decrease.
In this case, you could use i from 0 to 99.
Which in java can be:
double sum = 0;
for (int i = 0; i < 100; i++) {
sum += (100 - i) / (double) (1 + i);
}
if you want the result in the same format then do :
int j = 100;
double sum=0;
for (int i = 1; i <= 100; i++) {
sum += ((double) j / i); // typecast as least one of i or j to double.
System.out.print(j + "/" + i+"+");
j--;
}
// here print the sum

Calculate median [duplicate]

This question already has answers here:
Why double width = 50/110000; the output is 0.000000000000000?
(3 answers)
Closed 8 years ago.
I can't figure out what is wrong, why doesnt my median work ? Everything works except my median and i have been sitting here for a while and looking at it and still don't understand why it doesnt work.
import java.util.Arrays;
public class Stat{
private int[] värden = new int[100];
public int count = 0; // counter = 0
public int Värden(int värde){
värden[count++]=värde;
return värde;
}
public double medelv(){ //medelvärde
double medelv = 0;
int total = 0;
for(int x = 0; x < count; x++){
total += värden[x];
medelv = (total/count);
}
return medelv;
}
public double medianen(){
Arrays.sort(värden);
double medianen = 0;
for(int x = 0; x < count; x++){
if (värden.length % 2 == 0)
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
else
medianen = (double) värden[värden.length/2];
As #zouzou says in the comments, an int divided by another int equals an int. Cast one of them, and it will work.
medelv = ((double)total/count);
A much more concise way to calculate the median:
ArrayList<Integer> integers = new ArrayList<Integer>();
//TO DO: Add the integers to the array list
Collections.sort(integers);
double median;
if (integers.size() > 0) {
int x = integers.size() / 2;
else if (integers.size() % 2 == 0)
median = (integers.get(x - 1) + integers.get(x)) / 2.0;
else median = integers.get(x);
}
I don't see any issues with your logic . Other than finding it in loop . which is not required.
if (värden.length % 2 == 0) {
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
} else {
medianen = värden[värden.length/2];
}
If your array length is even then upper portion is double so no issues . If it is not even then you are picking middle ( 5/2 => 2.5 which would become 3 . it is median)
My question is , you declare the array length as 100. Are you filling all the 100 elements ? if not your logic will not work.

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

Categories