Java loops how to make incremental with jump? - java

Trying to make a loop in java that goes like this
1
2
3
4
5
1000
1010
1020
1030
1040
Right now my code is
for(int j = 1; j <=5; j += 1){
for(int i = 1000; i <=1040; i += 10){
System.out.println(+ j );
System.out.println(+ i );
}
}
And this is not working at all as its printing every number 5 times.

Two separate loops since there is no relation between first 5 and last 5 numbers.
for(int j = 1; j <=5; j += 1) {
System.out.println(j);
}
for(int i = 1000; i <=1040; i += 10){
System.out.println(i);
}

Or if you really really really want to do it in one loop:
int i=1;
while(i<=1040)
{
System.out.println(i);
if(i<5){i++; continue;}
else if(i==5){i=1000; continue;}
else i+=10;
}
Output:
1
2
3
4
5
1000
1010
1020
1030
1040
Otherwise just use 2 for loops (the first with +1 increment, the second with +10 increments) in sequence and not nested.
for(int j=1; j<=5; j++) {
System.out.println(j);
}
for(int j=1000; j<=1040; j+=10){
System.out.println(j);
}

Please try this.
If your purpose is to only display the number like above.
Then you can do that with one for statement.
public class HelloWorld
{
public static void main(String[] args)
{
for(int j = 1; j <=5; j += 1){
System.out.println(j);
}
for(int i = 1000; i <=1040; i += 10){
System.out.println(i);
}
}
}

Related

For loop java making the output into 2 columns

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
and the output should be like this:
0 1
2 3
4 5
6 7
8 9
Just use next line only for odd numbers:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
System.out.format("%2d", i);
else
System.out.format(" %2d\n", i);
}
Output:
0 1
2 3
4 5
6 7
8 9
P.S. For more general usage, I would extract it into separate method
public static void printTwoColumns(int min, int max) {
int width = String.valueOf(max).length();
for (int i = min; i < max; i++) {
String str = String.format("%" + width + 'd', i);
if (i % 2 == 0)
System.out.print(str);
else {
System.out.print(' ');
System.out.println(str);
}
}
}
You can do something like this:
for (int i = 0; i < 10; i++) {
System.out.print(i);
System.out.println(++i);
}
The first print uses the current i value and using System.out.print.
The second
print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.
Each loop iteration is printing two values and advances i by total of 2.
To do what you want you can either do something like this:
for(int i = 0; i < 10; i ++){
if(i % 2 == 0){
System.out.print(i); //Only for evens
}else{
System.out.println(i); //Only for odds
}
}
Or you could simplify it even more with something like this:
for(int i = 0; i < 5; i += 2){
System.out.println(i + " " + (i + 1));
}

How to make a number triangle java

I need to produce a triangle as shown:
***4
**34
*234
1234
My code is this:
for(int i=3; i>0 ;i--)
for(int j=0; j < i; j++){
System.out.print("*");
}
for(int s3 = 5; s3 >= 0; s3 -- ){
for ( int n2 = s3 + 1; n2 <= 4; n2 ++){
System.out.print(n2);
}
System.out.println();
}
}
which gives me this:
***
4
34
234
1234
**
4
34
234
1234
*
4
34
234
1234
Can anybody help me with this?
Just do it like this:
for(int i=3; i>=0 ;i--) {
for(int j=0; j < i; j++) {
System.out.print("*");
}
for ( int k = i+1; k < 5; k++ ) {
System.out.print(k);
}
System.out.println();
}
You just need an outer loop and 2 inner loops. The outer loops counts back from 3 to 0 (the number of stars for this line). The first inner loop prints that many stars. The second one fills the rest with digits.
Note that whether you start from 3 to 0 or 4 to 1 and then use a +1 or not and a -1 or not doesn't really matter. Also whether the first loop count forwards or backwards doesn't matter.
I just started with 3 because I find it easier to understand if i is the number of stars in the line. And I count forward (from 0 to i-1) in the first loop, just because I myself find it more intuitive to count in this direction than in the reverse one.
Achieve it by using two levels of nested loop.
for(int i=4;i>0;i--){
for(int j=i-1;j>0;j--){
System.out.print("*");
}
System.out.print(i);
for(int k =i+1;k<=4;k++){
System.out.print(k);
}
System.out.println();
}
final int NUM = 4;
for (int i = NUM; i >= 1; i--) {
for (int star = 1; star < i; star++) {
System.out.print("*");
}
for (int j = i; j <= NUM; j++) {
System.out.print(j);
}
System.out.println();
}
actually it just occurred to me why do we even use nested loops to solve problems like this especially when drawing something like
*
**
***
****
why cant we just build Strings as we go something like:
StringBuilder stars = new StringBuilder("****");
for (int i = 3; i >= 0; --i) {
stars.setCharAt(i, (char) (i + 49));
System.out.println(stars);
}
btw the code above will only work if you 9 or less stars, but I am just opening your mind to new ideas that you could use and practice :)
you can try this:
int valeur=5;
for(int i=valeur; i>0 ;i--) {
for (int j=1;j<=valeur;j++) {
System.out.print(j<i?"*":(j+""));
}
System.out.println("");
}
Try This
for(int i=4; i>0; i--){
for(int j=i-1; j>0; j--){
System.out.print("*");
}
System.out.print(i);
for(int k=i+1; k<=4; k++){
System.out.print(k);
}
System.out.println();
}

Asterisk in Nested loops, Java

I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}

I'm having trouble making a diamond shape with loops

You have an input of n and that represents half the rows that the diamond will have. I was able to make the first half of the diamond but I'm EXTREMELY frustrated with the second half. I just can't seem to get it. I'm not here to ask for specific code I need, but can you point me in the right direction and give me some tips/tricks on how to write this? Also, if I'm going about this program the wrong way, feel free to tell me and tell me on how I should approach the program.
The diamonds at the bottom represent an input of 5. n-1 represents the spaces to the left of each asterisk. Thank you for your help!
public static void printDiamond(int n)
{
for(int i=0;i<n;i++)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
** What I need ** What I have currently
*--* *--*
*----* *----*
*------* *------*
*--------* *--------*
*--------*
*------*
*----*
*--*
**
public static void main(String[] args) {
int n = 10;
for (int i = 1 ; i < n ; i += 2) {
for (int j = 0 ; j < n - 1 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
for (int i = 7 ; i > 0 ; i -= 2) {
for (int j = 0 ; j < 9 - i / 2 ; j++)
System.out.print(" ");
for (int j = 0 ; j < i ; j++)
System.out.print("*");
System.out.print("\n");
}
}
output
*
***
*****
*******
*********
*******
*****
***
*
Just reverse your loop :
for(int i=n-1;i>=0;i--)
{
for(int a=0;a<(n-(i+1));a++)
{
System.out.print(" ");
}
System.out.print("*");
for(int b=0; b<(i*2);b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
Since you have half the diamond already formed, simply run the loop again, in reverse, eg:
public static void printDiamond(int n)
{
for (int i = 0; i < n; i++)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
for (int i = n-1; i >= 0; i--)
{
for (int a = 0; a < (n - (i + 1)); a++)
{
System.out.print(" ");
}
System.out.print("*");
for (int b = 0; b < (i * 2); b++)
{
System.out.print("-");
}
System.out.print("*");
System.out.println();
}
}
Whenever I see a symmetry of a kind, recursions ring to my head. I'm posting only for you and others interesting into learning more. When beginning, recursions can harder to grasp but since you already have loop based solutions, contrasting against recursion will clearly outline advantages and disadvantages. My advice, don't miss out on the chance to get into it :)
A recursive solution:
static int iteration = 0;
public static void printDiamond(int n) {
int numberOfBlanks = n - iteration;
int numberOfDashes = iteration * 2;
String blank = new String(new char[numberOfBlanks]).replace("\0", " ");
String dash = new String(new char[numberOfDashes]).replace("\0", "-");
String star = "*";
String row = blank + star + dash + star + blank;
// printing the rows forward
System.out.println(row);
iteration++;
if (iteration < n) {
printDiamond(n);
}
// printing the rows backward
System.out.println(row);
}
first, don't get confused with the strange new String(new char[numberOfBlanks]).replace("\0", " "); its a neat trick in java to construct a string with repeated chars, eg new String(new char[5]).replace("\0", "+"); would create the following String +++++
The recursion bit explained. The second println won't run until the recursion is stopped. The stop criteria is defined by iteration < n. Up until that point the rows up until that point will be printed. So something like this:
iteration 1. row = **
iteration 2. row = *--*
iteration 3. row = *----*
iteration 4. row = *------*
iteration 5. row = *--------*
than the recursion stops, and the rest of the code is executed but in reversed order. So only the second println is printed, and the value of row variable is like as follows
continuing after 5 iteration row = *--------*
continuing after 4 iteration row = *------*
continuing after 3 iteration row = *----*
continuing after 2 iteration row = *--*
continuing after 1 iteration row = **
I didn't go into mechanics behind it, plenty of resource, this is just to get you intrigued. Hope it helps, best

Missing int in nested for loops

The following code:
for (i = 1; i <= 5; i++)
{
System.out.println();
for (j = 1; j <= i; j++) {
System.out.print(" ");
System.out.print(j);
}
}
produces:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Removing in the brace:
int i = 0;
int j = 0;
for (i = 1; i <= 5; i++)
{
System.out.println();
for (j = 1; j <= i; j++)
System.out.print(" ");
System.out.print(j);
}
produces:
2
3
4
5
6
I can understand that the nested for loop is iterating through the " " and printing them, then just printing one j, but I don't understand what happens to j = 1.
THe first time it goes through your for loop
it sets j = 1, checks j <= i
prints out the space
increments j, checks j < = i this fails because i = 1 and j = 2
exits the loop, and prints j and j = 2
For-loop without brace. Code you mentioned below:
for (j = 1; j <= i; j++)
System.out.print(" ");
System.out.print(j);
It is equal to the following code:
for (j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(j);
That's the problem, have a try and go ahead.
You can change it as follows:
for (j = 1; j <= i; j++) {
System.out.print(" ");
System.out.print(j);
}
The output will be expecte, like:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
I worked it out
System.out.println();
for (j = 1; j <= i; j++)
System.out.print(" ");
System.out.print(j);
The j is incremented j++ before being printed, as the loop has gone through an iteration befoe arriving at the System.out.print(j);
Since it only executes one statement, the value of j when it gets printed is one greater than the upper bound of your inner loop (2, 3, 4, 5, 6).

Categories

Resources