I am trying to write code that goes from 10-1 and back:
10
9
8
7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
10
I cannot figure it out. I've got this so far:
package numbers;
class Numbers {
protected static Object Numbers;
public static void main(String[] args) {
int n;
for(n=10; n>=0; n--) { //count BACKWARDS
//if n <=0 n = 1
System.out.println(n);
}
}
}
You can use two for loops.
for(int i = 10; i > 0; i--) System.out.println(i);
for(int i = 0; i <= 10; i++) System.out.println(i);
Here is one way. Based on your expected output I presume you mean from ten to zero and back. Go from -10 to 10 inclusive and change the sign when < 0.
uses the ternary operater (?:) (e.g) a ? b : c
given a conditional, if a is true, do b, else to c
for (int i = -10; i <= 10 ; i++) {
System.out.printf("%d ",i < 0 ? -i : i);
}
Prints
10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10
You can also change the print statement to to use the absolute value.
System.out.printf("%d ",Math.abs(i));
But here is the fun one. A recursive solution. Just not very efficient. It keeps printing the adjusted value and calling itself until the condition is met, then returns and prints values on the call stack in ascending order.
tenToOneToTen(10);
public static void tenToOneToTen(int i) {
if (i > 0) {
System.out.printf("%d ",i);
tenToOneToTen(i-1);
}
System.out.printf("%d ", i);
}
Related
i do not the understand the part of (e--),if i remove it or type (e++) instead i get wrong answer
i replaced e-- with e++,the result was like this
2 to the 0 power is 1
2 to the 1 power is 0
2 to the 2 power is 0
2 to the 3 power is 0
2 to the 4 power is 0
2 to the 5 power is 0
2 to the 6 power is 0
2 to the 7 power is 0
2 to the 8 power is 0
2 to the 9 power is 0
public static void main(String[] args) throws IOException {
int e;
int result;
for(int i=0;i<10;i++){
result=1;
e=i;
while(e>0){
result*=2;
e--;
}
System.out.println("2 to the "+ i +" power is "+result);
}
}
}
i thought what was the purpose of doing e--,so i removed it and included (e++) as it supports while condition
Try to see what is going on by reading the code.
The e variable is the exponent basically. You set it each time to the index i, and try to calculate the 2^e value.
So your(?) code does a while loop, e times.
The part
e=i;
while(e>0){
result*=2;
e--;
}
is equivalent to
for(int e = i; e > 0; e--) {
result*=2; // which is a shorthand for result = result * 2;
}
So the goal was to use a nested for loop to output 6 rows and 10 columns. The thing was though that the inner for loop was supposed to check to see whether the number was even or odd as, if it was even, we would add 2 to it and then print out that number 10 times before moving onto the next output. So this is what were were supposed to get
1 1 1 1 1 1 1 1 1 1
4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3
6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
8 8 8 8 8 8 8 8 8 8
I thought I was on the right track but my output is a complete mess, here's what I have. Thank you to anyone willing to help.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 1; nestedE < 10; nestedE++)
{
if (numberE%2 == 0)
{
numberE += 2;
System.out.printf("%2d", numberE);
} else {
System.out.printf("%2d", numberE);
}
}
System.out.printf("%2d\n", numberE);
}
well to start with your inner loop will only iterate nine times. second you don't need a nested loop, you need one loop and a guard determining when to print.
Don't modify numberE inside the loops. Instead just print numberE + 2.
Also, if your inner loop runs from 0 to <10 you will get 10 iterations and you don't need to print the number again - just a newline.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 0; nestedE < 10; nestedE++) // <-- start at 0 and end <10 for 10 iterations
{
if (numberE%2 == 0)
{
System.out.printf("%2d", numberE + 2); // <-- print the number + 2
} else {
System.out.printf("%2d", numberE);
}
}
System.out.println(); // <-- don't print the value again here
}
I would do it this way. Gives the required result.
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++)
{
int temp = i;
if(temp%2 == 0) {
temp +=2;
}
for(int j=1;j<=10;j++) {
System.out.print(temp+" ");
}
System.out.println();
}
}
}
A brief description of what is happening here:
So, since we need 6 rows, we use the value of 6 as a row counter. The variable i takes care of keeping a count of the rows. Here since the target is 6, we start from row number 1 and go until row no 6. Inside each value of the loop, we save the value of i to temp because we don't want the value of i to change before incrementing in the main for loop. We then check if this temp value is even by doing a modulo division by 2. If it is even, we increment the temp value by 2.
Then, we run a loop from 1 to 10 since we need 10 columns to print the value temp(either the original i or incremented because it was even). After exiting the loop, finally to move to the next row, we do a System.out.println().
I would suggest using a temporary variable to store the current intended value.
The issue with your solution was that you were modifying the value of numberE by using numberE += 2; inside the second for loop, this changes the value globally.
Moving the final column in to the nested for loops also makes it easier as you wouldn't need to define the temporary variable outside of the loop. Using this also meant changing the <10 to <=10.
for (int numberE = 1; numberE <= 6; numberE++) {
for (int nestedE = 1; nestedE <= 10; nestedE++) {
int current = (numberE % 2 == 0) ? numberE + 2 : numberE;
System.out.printf("%2d", current);
}
System.out.printf("\n");
}
You were pretty close though, with practise you'll get better.
Hey guys so I'm working on a problem where I need to print
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
public class Set_5_P5_18b {
public static void main(String[] args) {
int x;
String y;
x = 1;
y = "";
System.out.println("Pattern B:");
while (x < 7) {
y = y + x + " ";
x++;
}
System.out.println(y);
}
}
What I wrote above print's the first line but I can't figure out how to modify it to print the second, could anyone help me please?
Yuo need the outer for loop to run for say x ranging from values 6 to 1. For each value of x you need a inner loop that runs for values 1 ... x and prints out values in a line.
Keep this in mind and try to come up with pseudo code first and then the implementation code.
you'd have to reset the variables x, when you quit while :P
So commonly when you are writing a for loop and you realize that you want a certain aspect of the for loop to change each time the program iterates, 9/10 times you want to use nested for loops (for loop within a for loop).
So essentially every time that you iterate through the for loop you want to have the duration of the for loop decrease. So...
for (int num =1; num < <number that you want to change>; num++) {}
Here is the code method.
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
This is how you would do call the method.
public class print
{
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
public static void main (String[] args) {
print(6);
}
}
Your output can be observed like a 2-dimensional array where:
index i grows top-to-bottom and represents row index
index j grows left-to-right and represents column index
What you are doing right now is iterating over the columns of the first row and that is it.
As mentioned in the comments, you should add a second loop to iterate over the rows as well.
Here is how you can achieve this with two for loops:
int colSize = 6;
int rowSize = 6;
for(int i = 1; i <= rowSize; i++) {
for(int j = 1; j <= colSize; j++) {
System.out.print(j + " "); // print individual column values
}
System.out.println(); // print new line for the next row
colSize--; // decrement column size since column size decreases after each row
}
java-8 solution:
public static void printPattern(int rows) {
IntStream.range(0, rows).map(r -> rows - r).forEach(x -> {
IntStream.rangeClosed(1, x).forEach(y -> {
System.out.print(String.format("%3d", y));
});
System.out.println();
});
}
Usage:
printPattern(9);
Output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}
I understand that there is a similar post to this one, but based on the answers I can not both apply the answers to my current class, or understand the rest of the answers.
I need to create a program using nested "for loops" that creates an output like this one (just symmetrical). I have been trying to get this to work for two whole evenings now, and can't figure it out...
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I would GREATLY appreciate any help!!!
public class PyramidOfDoom {
public static void main(String[] args)
int k = 2;
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
} else {
System.out.print(k);;
}
}
System.out.println();
}
}
}
I thinks it can be done in simple steps as 1. print leading spaces 2. print increasing numbers 3. print decreasing number 4. print trailing spaces 5 print new line.
Sample code(concept) as below.
int row = 10;
for(int i=1; i<=numRow ; i++){
int num = 1;
for(int j=0; j<numRow- i; j++ ){
System.out.print(" ");
}
for(int j=numRow-i+1; j<=numRow ; j++ ){
System.out.print(num+" ");
num=num*2;
}
num=num/2;
for(int j=numRow+1; j<numRow+i; j++ ){
num=num/2;
System.out.print(num+" ");
}
for(int j=numRow+i+1; j<=numRow*2; j++ ){
System.out.print(" ");
}
System.out.print("\n");
}
You're not changing k at all. You need to keep multiplying it by 2 until you get to the middle of the row, then start dividing it by 2. As it stands, in your System.out.println(k), how can you expect it to print anything but 2 if you never manipulate it? :)
Also, you have two semicolons in your System.out.println(k);;. That seems odd to me, but I suppose it actually makes sense that it would compile.