Simple Java Pyramid using nested for loops - java

I am having a great deal of trouble trying to figure out a way to create a pyramid using a user's input. Here is what it is suppose to look like.
Enter a number between 1 and 9: 4
O
O
O
O
OOOO
OOOO
OOOO
OOOO
O
OO
OOO
OOOO
This is what I have so far
public static void main(String[] args) {
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number between 1 and 9: ");
number = keyboard.nextInt();
for (int i = 1; i < 10; i++){
for (int rows = number; number < i; rows++){
System.out.print("O");
}
System.out.println();
}
}
I completely understand of what I am trying to accomplish, but I do not completely understand how for loops work. Any help would be greatly appreciated as I am completely lost!

Basically a for loop works like this
// Take this example (and also try it)
for (int i = 0; i < 10; i++)
{
System.out.println(i);
}
// Explanation
for(int i = 0; // the value to start at - in this example 0
i < 10; // the looping conditions - in this example if i is less than 10 continue
// looping executing the code inclosed in the { }
// Once this condition is false, the loop will exit
i++) // the increment of each loop - in this exampleafter each execution of the
// code in the { } i is increments by one
{
System.out.println(i); // The code to execute
}
Experiment using different starting value, conditions and increments, Try these:
for (int i = 5; i < 10; i++){System.out.println(i);}
for (int i = 5; i > 0; i--){System.out.println(i);}

Replace the for-loops with:
for (int i = 0; i < number ; i++){
System.out.println("O");
}
for (int i = 0; i < number ; i++){
for (int j = 0; j < number ; j++){
System.out.print("O");
}
System.out.println();
}
for (int i = 1; i <= number ; i++){
for (int j = 0; j < i ; j++){
System.out.print("O");
}
System.out.println();
}
OUTPUT (for number = 6):
O
O
O
O
O
O
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
O
OO
OOO
OOOO
OOOOO
OOOOOO

Some for insight..
for(INIT_A_VARIABLE*; CONDITION_TO_ITERATE; AN_OPERATION_AT_THE_END_OF_THE_ITERATION)
You can init more than one variable or call any methods. In java you can init or call the same type of variable/method.
These are valid code statements:
for (int i = 0; i <= 5; i++) // inits i as 0, increases i by 1 and stops if i<=5 is false.
for (int i = 0, j=1, k=2; i <= 5; i++) //inits i as 0, j as 1 and k as 2.
for (main(args),main(args); i <= 5; i++) //Calls main(args) twice before starting the for statement. IT IS NONSENSE, but you can do that kind of calls there.
for (int i = 0; getRandomBoolean(); i++) //You can add methods to determine de condition or the after iteration statement.
Now.. about your homework.. I'd use something like this:
Iterate through the limit of rows and add spaces and the desired character to its position. The position will be determined by the row you are in.
for (int i = 0; i <= 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(' ');
}
for (int j = 0; j < i; j++) {
System.out.print("O ");
}
System.out.println();
}

Related

Using For Loop to Print Pattern in Java

I need to print this:
I need to print this square using a for loop in java.
This is what I have so far:
public static void main(String [] args)
{
for(int i = 0; i < 5; i++){
System.out.print("O ");
}
System.out.println();
for(int i = 0; i < 4; i++){
System.out.print("O ");
}
}
The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,
int size = 5;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
System.out.print("O ");
}
for (int j = 0; j < i; j++) {
System.out.print(". ");
}
System.out.println();
}
Which outputs (as requested)
O O O O O
O O O O .
O O O . .
O O . . .
O . . . .
Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.
int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("O ");
}
for (int i = 0; i < size; i++) {
System.out.println(sb);
sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}
And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,
int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(arr[j] ? ". " : "O ");
}
System.out.println();
arr[size - i - 1] = true;
}
This is not a 'design pattern' problem. You just need to use the logic with loops.
Here's the logic.
In a square of n x n cells, the ith row contains (n-i) ovals and i
dots, where 0 <= i < n.
Refer to the other answer to see a working snippet.

Printing diamonds from *'s

I am trying to System.out.print() a diamond out of *'s. So far I have spent a good 5 hours on trying to figure out how to reverse print the bottom triangle of the diamond.
I can worry about the spacing to complete the diamond later. (I have it worked for the most part).
If someone could explain to me what I am doing wrong and how the right way works I would greatly appreciate it.
private static void diamond()
{
int numLines = 0;
System.out.println("How many lines would you like in the Diamond?");
numLines = scan.nextInt();
if (numLines / 2 == 0) //if number is even, make odd.
{
numLines++;
}
for(int i = 0; i <= numLines ; i++) // Controls #Lines
{
if(i <= numLines / 2)
{
for(int j = 0; j < i * 2 - 1; j++) // Controls #Stars small upright triangle
{
System.out.print("*");
}
}
else
{
for(int k = numLines; k > i / 2; k--) // Controls # of spaces
{
System.out.print("*");
}
/*for(int j = numLines/2 - i, l = i; l > j; j++) // Controls #Stars small upright triangle
{
String stars = "*";
System.out.print(stars);
}*/
}
System.out.println("");
}
}
`
What happens to your attempt is that you loop through the half (of the lines) of your diamond [the number of lines in second/first half] times.
You'd want to do a if-statement each loop, not an if and a for in each loop
Probably you want this
Just adjust it for user input values
public static void main(String[] args) {
System.out.print("Reverse diamond: \n");
for (int i = 1; i < 10; 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");
}
System.out.print("\n\nDiamond from starts: \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:

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();
}
}

java pyramid/triangle using for loop

i want to print a triangle/pyramid style like:
1
323
54345
7654567
here is my code:
int lines = 5;
for (int i = 1; i < lines; i++) {
for (int j = 1; j < lines-i; j++) {
System.out.print(" ");
}
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
for (int j = i; j < i+i; j++) {
System.out.print(j);
}
System.out.println();
}
what i got is
1
223
32345
4324567
i been studying codes while working at office and i think week long i still could not find a solution to this even i use search in Google.
i am only into enhancing my logic through conditionals and no heavy object oriented or recursion yet.
The problem in your first loop is a problem you figured out in your second one! (and it has something to do with the largest number in the loop)
for (int j = i; j > 1; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
Look at the numbers on the left of the pyramid. They start where the ones on the right end (every line of the pyramid is symmetrical). And the general formula for that number is i + i - 1, where i is the line number from your outer loop.
The second row starts at 2 * i - 1 = 2 * 2 - 1 = 3. The third row starts at 2 * 3 - 1 = 5 etc.
Your second inner loop should therefore look like this:
for (int j = i + i - 1; j > i; j--) {
System.out.print(j);
}
Here is the complete fixed source.
You have to start at the i-th odd number. This is i*2-1. And you stop at i. This also fixes a spacing difference introduced by changing it to lines = 4.
int lines = 4;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j < lines-i+1; j++) {
System.out.print(" ");
}
for (int j = i*2-1; j > i; j--) { //this for loop is my problem. any solution?
System.out.print(j);
}
for (int j = i; j < i+i; j++) {
System.out.print(j);
}
System.out.println();
}
Run it here: http://ideone.com/AKsc1f
int lines = 4;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j < lines-i+1; j++) {
System.out.print(" ");
}
//replace this
for(int j=0; j<i-1; j++) System.out.print(i*2-j-1);
System.out.print(i);
for(int j=; j<i-1;j++) System.out.print(i+j+1);
//==========
System.out.println();
}

Categories

Resources