Reputation: 3
I'm trying to create a nested for loop that uses two user input values where value 1 equals the number of rows and value 2 equals the number to increment by. If the user enters 5 for both values, the output should be like this:
0
5 10
15 20 25
30 35 40 45
50 55 60 65 70
So far I have this:
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
System.out.println("Please enter the number of rows: ");
int number= myScan.nextInt();
System.out.println("Please enter the number to increment by: ");
int number2= myScan.nextInt();
for(int i = 0; i <= number; i++){
for(int j = 0; j < i; j++){
for(int k = 0; k <=number2 + number; k++)
System.out.print(number + " ");
System.out.println(" ");
}
}}}
I know that I messed up somewhere within my coding. Help will be appreciated.
Upvotes: 0
Views: 1574
Reputation: 1
import java.util.Scanner;
public class lem;
{
public static void main(String[] args)
{
int i,j,n=1,m=0;
Scanner ab=new Scanner(System.in);
System.out.println("Enter the number : ");
int num=ab.nextInt();
for(i=1;i<=num;i++)
{
for(j=0;j
n=5*m;
m++;
System.out.print(n+" ");
}
System.out.println();
}}}
Upvotes: 0
Reputation: 692
Assuming that 'inc' is the amount to increment by and that 'rows' is the number of rows
int num = 0;
for(int row = 0; row < rows; row++) {
for(int nIndex = 0; nIndex <= row; nIndex++) {
System.out.print(num + " ");
num += inc;
}
System.out.println("");
}
Upvotes: 0
Reputation: 4623
You don't need the third for
loop (the one with int k
).
You can write it this way:
int incr = 0;
for(int i = 0; i <= number; i++){
for(int j = 0; j < i; j++){
System.out.print((incr++) * number2 + " ");
}
System.out.println("");
}
Upvotes: 1