I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
enter code hereI have this number "811218-3476"as string,I want to multiply 8 by 2,1 by 1, 1 by2, 2 by1 and so on as following:
8 1 1 2 1 8 3 4 7 6
2 1 2 1 2 1 2 1 2 1 *
16 1 2 2 2 8 6 4 14 7 ----> Result
My question is how I kan do sum for the result, I did sum one number with another number like
16 + 1+2+2+2+8+6+4+14+7 = 62,
but I want to do sum as following:
1+6+1+2+2+2+8+6+4+1+4+7 = 47.
I do not need you to write a code I have wrote it, but I want to know how I kan sum 1+6 instead of 16 as example. my code is here and it works fine.
I hope help know.
Thanks.
enter code here
public static boolean checknumber(String s) {
if(checkPersonNummer(s)== true) {
char [] charray = s.toCharArray();
int newch = 0 ;
int j = 0;
int i = 0;
String sum= "";
int x = 0;
for( j = 2; j < 8 ; j++) {
System.out.print(" "+ charray[j] + " ");}
for( j = 9; j < charray.length ; j++) {
System.out.print(" "+ charray[j] + " ");}
System.out.println(" ");
for( j = 2; j < 8 ; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
// System.out.println(" ");
for( j = 9; j < charray.length; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
System.out.print("\n--------------------------------------------");
System.out.println("");
for( i = 2;i < 8;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 2;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 1;
sum += newch;
}
System.out.print(newch + " " );
}
for( i = 9;i < charray.length;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 1;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 2;
sum += newch;
}
System.out.print(newch + " " );
}
System.out.println();
System.out.print("Total = " + sum);
}
return true;
}
}
This sounds like a homework assignment, and we're not a homework writing team. But I'll give you some basic advice.
First, I had one person tell me, "programming is the art of editing the null program until it does what you want". By that he meant that we start with a program that does nothing and slowly built it up.
That's a good way to start.
So... Start your program. You need to get your data in. Do that, and figure out how to print it.
After that, think about printing out each number times either 1 or 2 as your problem requires, and print each calculation as you go.
Then all you have to do is keep a variable outside of this loop to store the sum, and add each mini-calculation to it, then print it at the end.
Start small. Work up to the final answer. Lots of debug output while working on it.
Lets say I have an array of numbers [2,3,4,5,6], Think of this question as you are multiplying the numbers with 1 those are at odd position in the array and multiplying the numbers with 2 those are at even position in the array.
Answer to How to add 1 + 6 instead of 16
Check if the number is less than 10, if it is than you don't have to
worry about it But,
If the number is greater than 10 you can use the % operator.
For instance
15 % 10 gives you 5 and 15 / 10 gives you 1 that way you can separate two individual digits.
∑i=1n1i
In other words, the method should generate the following sequence:
1+12+13+14+15+⋯
I've been stumped on this problem for quite a bit. Having a tough time understand what "n" stands for in the equation and applying it to my for loop.
Would a for loop be optimal for solving this? Or should I just use a formula and somehow solve it then?
public static void main(String[] args) {
//Chapter 4 Exercise 1
System.out.println("--Chapter 4, Exercise 1");
System.out.println("How many integers do you want?:");
Scanner console = new Scanner(System.in);
int numb = console.nextInt();
fractionSum(numb)
public static double fractionSum(int numb) {
for(int i = 1; i <numb; i++) {
if (i !=1)
System.out.print("1 + 1" + i);
else
System.out.print("1");
}
return(numb);
}
1+12+13+14+15+⋯
Should be the output.
My output is coming out as:
11 + 121 + 131 + 141 + 15
Answering the first part of your question:
∑i=1n1i is known as the Harmonic Sum - the output you give in your question is wrong, harmonic sum can be described as the sum of reciprocals of the positive integers - for example:
H1 = 1
H2 = 1 + 1/2 = 1.5
H3 = 1 + 1/2 + 1/3 = 1.8333
H4 = 1 + 1/2 + 1/3 + 1/4 = 2.0833
H(n) = 1 + 1/2 + 1/3 + 1/4 ... + 1/n = answer ---> see what n is now?
You should use a for-loop for this, and its not very complex. Hopefully, this answer will clear up the task for you (I assume homework from Chapter 4 Exercise 1) and you can try again.
Here:
class Harmonic {
public static void main(String… s) {
int n, i;
float sum = 0;
n = Integer.parseInt(s[0]);
for (i = 1; i <= n; i++) {
sum = sum + (float) 1 / i;
}
System.out.println(“nSum = ”+sum);
}
}
I am trying to finding the sum of each in the below code in java.What changes should i have to made in this code.
import java.io.IOException;
class as {
static void printSubsets(int set[]) {
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int set[] = { 1, 2, 3 };
printSubsets(set);
}
}
Output of above code is:
1
2
1 2
3
1 3
2 3
1 2 3
I want To Multiply each element of subset by its last number for e.g.
1*1=1
2*2=4
1*2+2*2=6
3*3=9
likewise all elements
and lastly generate sum of all these subset 1+4+6+9+.. and so on.
Above code also print null set and subset are in order.How this program can be edited to make changes such that it does'nt print null set and print random substring.
As far as I understand your question, you want to multiply all the elements with each other and print out each step of iteration with the result. Here you are:
static void printSubsets(int set[]) {
int sum = 0;
for (int i=0; i<set.length; i++) {
for (int j=i; j<set.length; j++) {
int var = set[i] * set[j];
sum += var;
System.out.println("( " + set[i] + " * " + set[j] + " = " + var + " ) -> sum=" + sum);
}
}
System.out.println("final sum=" + sum);
}
In case of input [1,2,3], the sum is supposed to grow according my algorithm by:
1, 3, 6, 10, 16 up to 20
Just a note about << shift operator which shifts a bit pattern to the left. Let's say that number 2 is understood as 10 in binary. Shifting this number by 2 << 4 will result 100000 in binary that is understood as 32 in decimal. I am not sure you really need this pattern.
I am looking for a way to run a "for" loop that will start with the user defined value "d" (between 1 and 7) and add 1 continuously until it reaches the other user defined value "n". Here's the catch...I need it to repeat the count back to "1" once the value "7" is reached without it being stuck in an infinite loop.
For example, my program prompts a user to input 2 numbers and it stores them as "d" and "n" respectively. The first number can be "1-7" and the second number can be anything. So, if the user inputs "5" and "10" I need my loop to start counting at "6" and count up "10" times, starting back over at "1" once the value has reached "7". It should look like this...
"6 7 1 2 3 4 5 6 7 1".
Right now I have it looking like this...
"6 7 8 9 10 11 12 13 14 15"
This is my current code and output with "5 = d" and "10 = n"
Code
public void incrementDay3()
{
int i;
for(i = (d + 1);i <= (d + n);i++)
{
System.out.print(i);
}
}
Output
"6789101112131415"
Any help is greatly appreciated!
Try this (modulo operator) :
public void incrementDay3()
{
int i;
for(i = d ; i < (d + n) ; i++)
{
System.out.print((i % 7) + 1);
}
}
For more information about what a modulo is, you can check this wikipedia article
public void incrementDay3()
{
int i;
int d = 5, n = 10;
int result;
result = d + 1;
for(i = result;i <= (d + n);i++)
{
result++;
if(result > 7)
result = 1;
System.out.print(result);
}
}
I find this variant easier to read. In particular, the "simple for loop that just counts to n" is instantly recognizable, and easier to parse than the loop condition in the current best answer.
public static void incrementMod7(int d, int n) {
for (int i=0; i<n; i++) {
d = (d%7) + 1;
System.err.print(d + " ");
}
}
int d=5;
for (int i = 0; i < 10; i++) {
d =(d==7)?1:d+1;
System.out.println(d);
}
easy.
I wrote a programm to get the cross sum of a number:
So when i type in 3457 for example it should output 3 + 4 + 5 + 7. But somehow my logik wont work. When i type in 68768 for example i get 6 + 0 + 7. But when i type in 97999 i get the correct output 9 + 7 + 9. I know that i have could do this task easily with diffrent methods but i tried to use loops . Here is my code: And thanks to all
import Prog1Tools.IOTools;
public class Aufgabe {
public static void main(String[] args){
System.out.print("Please type in a number: ");
int zahl = IOTools.readInteger();
int ten_thousand = 0;
int thousand = 0;
int hundret = 0;
for(int i = 0; i < 10; i++){
if((zahl / 10000) == i){
ten_thousand = i;
zahl = zahl - (ten_thousand * 10000);
}
for(int f = 0; f < 10; f++){
if((zahl / 1000) == f){
thousand = f;
zahl = zahl - (thousand * 1000);
}
for(int z = 0; z < 10; z++){
if((zahl / 100) == z){
hundret = z;
}
}
}
}
System.out.println( ten_thousand + " + " + thousand + " + " + hundret);
}
}
Is this what you want?
String s = Integer.toString(zahl);
for (int i = 0; i < s.length() - 1; i++) {
System.out.println(s.charAt(i) + " + ");
}
System.out.println(s.charAt(s.length()-1);
The problem with the code you've presented is that you have the inner loops nested. Instead, you should finish iterating over each loop before starting with the next one.
What's happening at the moment with 68768 is when the outer for loop gets to i=6, the ten_thousand term gets set to 6 and the inner loops proceed to the calculation of the 'thousand' and 'hundred' terms - and does set those as you expect (and leaving zahl equal to 768 - notice that you don't decrease zahl at the hundreds stage)
But then the outer loop continues looping, this time with i=7. With zahl=768, zahl/1000 = 0' so the 'thousand' term gets set to 0. The hundred term always gets reset to 7 with zahl=768.
The 97999 works because the thousand term is set on the final iteration of the 'i' loop, so never gets reset.
The remedy is to not nest the inner loops - and it'll perform a lot better too!
You should do something like this
input = 56789;
int sum = 0;
int remainder = input % 10 // = 9;
sum += remainder // now sum is sum + remainder
input /= 10; // this makes the input 5678
...
// repeat the process
To loop it, use a while loop instead of a for loop. This a great example of when to use a while loop. If this is for a class, it will show your understanding of when to use while loops: when the number of iterations is unknown, but is based on a condition.
int sum = 0;
while (input/10 != 0) {
int remainder = input % 10;
sum += remainder;
input /= 10;
}
// this is all you really need
Your sample is a little bit complicated. To extract the tenthousand, thousand and the hundreds you can simply do this:
private void testFunction(int zahl) {
int tenThousand = (zahl / 10000) % 10;
int thousand = (zahl / 1000) % 10;
int hundred = (zahl / 100) % 10;
System.out.println(tenThousand + "+" + thousand + "+" + hundred);
}
Bit as many devs reported you should convert it to string and process character by character.