1 Replies - 2654 Views - Last Post: 29 February 2012 - 07:21 AM Rate Topic: -----

#1 javaislife  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 28-February 12

Using nested foor loops to display a pattern

Posted 28 February 2012 - 09:33 PM

This is not homework. I have a midterm tomorrow and these kinds of questions might be on it.

(Printing numbers in a pyramid pattern) Write a nested for loop that prints the following output:
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've been trying to get the right answer the past few days but its just not working. I know how to print out a pattern like this:

1
12
123
1234
...

but doing the whole double-sided pyramid thing is stumping me. For now, my code is:

public class Pattern
{
	public static void main (String [] args)
	{
		int r;
		
		for (r = 1; r <= 128; r = r*2)
		{
			int c;
			for (c = r; c <= 128; c = c*2)
				System.out.print(c + " ");
			System.out.println("\n");
		}

	}
}



I know my code is outputting the wrong thing but that's the closest I've gotten to the right answer.

Can anyone help?

Is This A Good Question/Topic? 0
  • +

Replies To: Using nested foor loops to display a pattern

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5520
  • View blog
  • Posts: 11,829
  • Joined: 02-June 10

Re: Using nested foor loops to display a pattern

Posted 29 February 2012 - 07:21 AM

This assignment is one discussed in this article
This is the homework help thread you asked for.

Although the OP claims this is not his homework, this is a very common homework assignment. So slapping in completed code here would allow probably be ill advised, as numerous students will Google across it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1