The output of this program this is: iiiii .
and this is because of i++ used after print statement. ++ means increment and without i++ its printing i 10 times .then how it will give this output iiiii .it has to be increment one more
class array_output {
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = 'i';
System.out.print(array_variable[i] + "" );
i++;
}
}
}
That's an expected output as you are incrementing the i twice. simple solution is to remove last line in the for loop.
output from your program:
i = 0
i = 2
i = 4
i = 6
i = 8
i = 10
After removing the last increment
iiiiiiiiii
Your code should be
class array_output {
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = 'i';
System.out.print(array_variable[i] + "" );
// i++; // you are incrementing i again. No need to do if you want a jump of 1 step.
}
}
}
Ok. After reading again here is the answer for the question. When you enter forloop for the first time your i is 0 and after entering you said i++ which will be 1 and then ++i which becomes 2 so for every i you are making a jump of 2 steps so that's the reason after 5 iterations you are reaching 10 and your for loop condition i<10 fails. So, the loop further won't execute and exit successfully.
Sorry for the wrong output in my previous answer. Here is the right output. .
i = 0
i = 2
i = 4
i = 6
i = 8
Related
I wrote the below code to split the numbers and add them together, it is working fine if my number is not starting with 1 eg, 123456 -- not working, 234567 -- working, can anyone tell me what I am doing wrong here?
public class Basic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sum =0;
for (int i = 0; i <input; i++) {
int A = input%10;
System.out.println("test1 " +A);
input = input/10;
System.out.println("test " +input);
sum = sum + A;
}
System.out.println(sum);
}
It's the loop:
for (int i = 0; i <input; i++) {
You are dividing the int input into its digits. So the loop should run until all digits are eaten up:
while (input > 0) {
That should fix it
In every iteration, you're updating input, so for example, step by step:
input = 123
i = 0
sum = 0
input = 12
i = 1
sum = 3
input = 1
i = 2
sum = 5
Then check the condition i < input it's 2 < 1, it's not, so it's skipping the last digit, the same happens for 234 it returns 7 rather than 9, because of the same thing.
You could change your for-loop for a do-while:
do {
//Your code here
} while (input > 0);
The problem is in i < input; i++ in your loop. It's not problem with only numbers starting with 1, for example 23445352 isn't work correctly too. I see 26 instead of 28.
Check the next steps in the loop, for 123 input, after two steps, you have sum = 5, input = 1 and... i = 2. So the condition for exiting the loop returns true without considering the last digit.
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.
The Return type is void
No input parameters
Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).
An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.
I honestly have no clue how to do this so I'm not going to lie about it so can someone help me code it and explain or just help me with it.
public class ForFogMe
{
public int a, b;
public String str;
public void addUp(){
for(a = 0; a <= 6; a ++){
System.out.print(a);
}
String s = Integer.toString(a);
System.out.println();
System.out.print(s.substring(0,2) );
}
public static void main(String args[]){
ForFogMe me = new ForFogMe();
me.addUp();
}
}
If you only want to print sum of the numbers from 0 to 6 you would do it simply like this:
public void addUp() {
for(a = 0; a < 6; a++) {
System.out.print(a+(a+1) + ",");
}
System.out.print("\b"); // to delete last comma
}
In first iteration a is 0 a+1 is 1 so you print their sum like (a+(a+1) + ",") which outputs "1,". It repeats until it reaches 6. At the end we have 1,3,5,7,9,11, so I used System.out.print("\b"); to delete last char, so we get 1,3,5,7,9,11
I believe this should do the trick:
public static void addUp(){
final int[] array = {0,1,2,3,4,5,6};
int[] result = new int[array.length-1];
for(int i = 0; i < array.length-1; i++) {
result[i]=array[i]+array[i+1];
}
result[3]=array[array.length-1];
for(int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
Test case (array):
0,1,2,3,4,5,6
Outputs:
1 3 5 6 9 11
Note: The array size does not matter.
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
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();
}
}