Reputation: 11
I'm writing this program with numbers, but I am stuck and need some help.
Code so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Oppgi øvre grense: ");
int Number = in.nextInt();
int tall = 1;
for(int t = 0; tall <=45; tall++){
System.out.println(" " + tall);
}
}
The objective: to get the first line to contain one number, the second to contain two numbers, third line contain three numbers, etc. The output should look like a pyramid, with different spacing between the numbers on each line.
If anybody can help me with the solution code. Thank you.
Oppgi øvre grense: 45 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
Upvotes: 0
Views: 25705
Reputation: 1
public class RareMile {
public static void main (String[] args){
printNum(5);
}
public static void printNum (int n){
int k=1, sum=0;
for (int i=1; i<=n; i++){
sum=0;
for(int j=1; j<=i; j++){
System.out.print(k);
sum = sum+k;
k++;
}
System.out.print(" =" + sum);
System.out.println();
}
}
}
The real question is that how to do it with only one for loop?
Upvotes: 0
Reputation: 1850
Keep track of the line number e.g.
int line = 1; // line number
int count = 0; // number of numbers on the line
for(int x = 0; x <= 45; x++){
if (count == line){
System.out.println(""); // move to a new line
count = 0; // set count back to 0
line++; // increment the line number by 1
}
System.out.print(x); // keep on printing on the same line
System.out.print(" "); // add a space after you printed your number
count++;
}
Upvotes: -1
Reputation: 24998
outer loop{
decides number of numbers in one line
inner loop{
prints actual numbers.
Please keep track of the numbers you have printed so far
Inner loop starts at numbers printed so far
It will have passes = number of numbers to print
}
}
You have two distinct tasks here:
1. Decide how many numbers to print in one line
2. Actually print the numbers
Since that is the case, one loop decides how many numbers to print: the outer loop. The Reason it is outer loop is because you need to have a clear picture of how many numbers you need to print before you actually print.
The other loop: inner loop does the actual printing.
So, once you start with the outer loop, your inner loop will begin printing.
It will then see if it has printed the maximum number of numbers for that pass.
If yes, stop. Then, you increment the outer loop. Come back in, print, check and then do the same.
Easy enough ?
Upvotes: 3