Sum of a sequence by using for and while loop [duplicate] - java

This question already has answers here:
Sum numbers using loop
(2 answers)
java for loop sum and average of range
(3 answers)
Closed 2 years ago.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Last Number ");
int inputedNumber = Integer.valueOf(scanner.nextInt());
int result = 0;
int outcome = 0;
for(int i = 0; i < inputedNumber; i++) {
result += ;
}
/*/*while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}*/
System.out.println(result);
}
}
I have a problem to understand what is wrong here, because I would like to solve the task , originally it should be (Implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.) but it gives me another answer, please , pin out for me in a both way , to understand what I went wrong , because everything so far make sense for me , but code doesn't work as it should to be

You can try the code below:
for(int i = 1; i <= inputedNumber; i++) {
result += i;
}
Note: you should start with i=1 based on your requirement:
1+2+3+..+n

You need to replace result += ; with result += i;

For the first case. This is not a valid Java code, you should put a value/variable after += operator.
for (int i = 0; i < inputedNumber; i++) {
result += ;
}
If you put the variable i after it, and use i<= inputedNumber. You will get the expected answer.
for (int i = 0; i <= inputedNumber; i++) {
result += i;
}
In the second case, you are actually doing n*(n+1)
while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}
This can be tested as input the value as 2:
The first iteration:
outcome -> 0
inputedNumber -> 2
result -> 2
The second iteration:
outcome -> 1
inputedNumber -> 2
result -> 4
The third iteration:
outcome -> 2
inputedNumber -> 2
result -> 6
The fix is similar to what I suggested before. You could take this as an exercise.

Related

Java: Unable to understand for loop behaviour

I am slightly new to coding, I am solving a problem which should print all the integers between variables L and R including L,R. but I am getting the required output repeatedly. I don't understand the reason for it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int L = sc.nextInt();
int R = sc.nextInt();
for (int i = 0; ; i++) {
if (i >= L && i <= R) {
System.out.print(i + " ");
}
}
}
Input: L=4 ,R=8
Output: 4 5 6 7 8 4 5 6 7 8 4 5 6 7 8 and so on...
You put the condition is the wrong place, so your loop is infinite.
To further explain, since your loop has no exit condition, i will be incremented forever, but after reaching Integer.MAX_VALUE, the next i++ will overflow, so i will become negative (Integer.MIN_VALUE). Then it will continue to increment until it reaches again the range you wish to print, so that range will be printed again and again, forever.
The correct loop should be:
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
Now i will start at the first value you wish to print (L), and the loop will terminate after printing the last value you wish to print (R).
If are new to coding then follow this link to understand how for loop works
And you are not defining any condition when for loop should stop executing the code block
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
This is how your for loop should be

Find Maximum Positive Index

You are given an array A. We define a term Positive difference index as the count of elements between the two indexes i and j (both inclusive) such that i<j and A[i]<A[j].
Now for the given array, you have to find the maximum positive difference index. It is assured that the test case will be valid such that there exists an answer.
Input format
First line : T i.e Number of test cases.
For each test case :
First line : N
Second line : N space separated integers denoting the element of the array.
Output format
Print the answer to each test case in a separate line and it is given that answer always exists.
Sample Input
1
6
5 3 2 1 1 4
Sample Output
5
Explanation
let i=2 and j=6 then A[i]<A[j] and total elements between them is 5 so the maximum answer that can be achieved is 5.
I had tried to find maximun number from an array and minimum number from array such that A[i]<A[j]. With sample input it worked but for when I submitted the question on hackerearth it displayed none test cases were passed. Can anyone please me help to understand the question and program?
Below program I have written
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int totalTest = Integer.parseInt(line);
for(int i=0;i<totalTest;i++) {
line = br.readLine();
int totalElements = Integer.parseInt(line);
line = br.readLine();
String strArr[] = line.split(" ");
int elements[] = new int[strArr.length];
for(int j=0;j<strArr.length;j++) {
elements[j] = Integer.parseInt(strArr[j]);
}
System.out.println(findMaximumPositiveIndex(elements));
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
if(br!=null)
br.close();
}
}
public static int findMaximumPositiveIndex(int[] arr) {
int max=arr[0];
int maxIndex = 0;
int minIndex=arr[0];
int min=0;
for(int i=0;i<arr.length;i++) {
if( min==0 ) {
min = arr[i];
minIndex=i;
}
if(arr[i] < min) {
min = arr[i];
minIndex = i;
}
if(arr[i] > max) {
max = arr[i];
maxIndex = i;
}
}
return (max - min) + 1;
}
}
The maximum and minimum values from the array, in most cases they won’t help you. So don’t find those. In the example in the question the maximum value is 5 and the minimum is 1. Neither of those two values are involved in calculating the output. Instead the values 3 and 4 are because they are the farthest apart values that fulfil the condition A[i] < A[j]. The output should be 5 because the part of the array 3 2 1 1 4 has length 5. Or “the count of elements between the two indexes i and j (both inclusive)”, as the challenge puts it.
Instead you find the output from the min and max values as (5 – 1) + 1 = 5 (I think; I haven’t studied your code thoroughly). Coincidentally you hit the correct output in this single case. You haven’t done it correctly.
Other examples:
For 2 1 2 1 2 1 the answer is 4 because the part 1 2 1 2 has length 4 and 1 < 2.
For 40 90 10 60 the answer is 4 too because 40 90 10 60 has 4 elements in it and 40 < 60.
I understood that you asked for help understanding the problem, not for solving it, so I am happy to leave that pleasure to yourself.
Thanks for helping to understand the problem statement.
I have modified the code
public static int findMaximumPositiveIndex(int[] arr) {
int min=arr[0],max=arr[0],minIndex=0,maxIndex=0;
int maximumIndex = 0;
for(int i=0;i<arr.length;i++){
min = arr[i];
minIndex=i;
boolean isMaxPresent = false;
for(int j=i;j<arr.length;j++)
{
if(arr[j] > min){
max = arr[j];
maxIndex = j;
isMaxPresent = true;
}
}
if(maximumIndex < ((maxIndex - minIndex) +1) )
maximumIndex = (maxIndex - minIndex) + 1;
}
return maximumIndex;
}
which fulfills all the test cases. Thanks

Printing Odd and Even Elements of an Array [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 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?
You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.
Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();
you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.

Java For Loop Practice

Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}

Wrong results from for loop in a method

I would like to understand, why is it when I specify the number for the method to sum up numbers it returns 21, but when i enter the value through scanner it gives me the correct value. For example number 3 should be 1 + 2 + 3 = 6 but its giving me 21, any ideas thanks.
public class sumInt
{
public static void main(String[] args)
{
int i = sumInt(3);
int j = sumInt(10);
Scanner in = new Scanner (System.in);
System.out.println("Please enter posiutive integer: ");
int k = in.nextInt();
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
}
public static int sumInt(int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
}
You are actually summing up to 6 for i, your current code could also be written as:
System.out.println(sumInt(sumInt(3)));
You'll need to print out i directly instead of calling sumInt on it again.
When you first do int i = sumInt(3);, i gets set to 6 (1 + 2 + 3). When you System.out.println(sumInt(i)), it does sumInt(6), which is 21, because you haven't reset i to 3.
To see the actual results, you should change what you're outputting to:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));
Or change your initial definitions of i and j to:
int i = 3;
int j = 10;
It's because you're calling sumInt in two places, when you only meant to call it in one:
int i = sumInt(3); // sets i = sumInt(3) == 6
System.out.println(sumInt(i)); // prints sumInt(i) == sumInt(6) == 21
Because you're calling sumInt() twice; once at the beginning, then again in the print statements.
You are saying i = sumInt(3) so i == 6.
Then your print sumInt(i) == sumInt(6) which I'm guessing is 21..
You call sumInt twice for the same number.
int i = sumInt(3); //i gets 6
System.out.println(sumInt(i)); //called with 6 =21
This is because of the following lines
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
You are already calculating i and j as the sum of the integers you want, and when you printout , you are again calculating sum of i and j
change the above three lines to the following:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));

Categories

Resources