Java for loop making asterisk matrix - java

I've currently trying to make this form with a for loop in Java:
**********
*********
********
*******
******
*****
****
***
**
*
My code looks like this:
for (int row = 1; row <= 10; row++) {
for (int star = 10; star >= 1; star--) {
if (star >= row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
The output looks like this:
**********
*********
********
*******
******
*****
****
***
**
*
I can't seem to figure out to make the whitespace go before the stars. I've tried switching the loop conditions, but it just gives me the same result.
There's something about these for-loops i'm not getting. Can someone point me in the right direction :)

So I tried to analyze your code and what I found is
Your Mistake:
Here we see that the desired output and your output becomes different from output line number 2 and the reason I found is the if condition that is star >= row so lets iterate the loop of star for the row value 2:
if(star >= row) //when star = 10 - condition true. * will be the output
if(star >= row) //when star = 9 - condition true. * will be the output
if(star >= row) //when star = 8 - condition true. * will be the output
so * will be the output untill the star>=row returns false which will be star = 1 scenario for this iteration.
Similarly for row = 3 the condition will be true unless the star value becomes <=2. So the problem is that you are printing * in the start and the condition for comes after printing the *.
Possible Solution:
Basically you need to print in the start, not in the end. So with the same condition you may need to reverse the iteration method for the columns in order to reverse your print order. if you change the order of your loop you can do the job. Lets iterate the loop for the row value of 2:
if(star >= row) //when star = 1 - condition false. ` ` will be the output
if(star >= row) //when star = 2 - condition true. * will be the output
if(star >= row) //when star = 8 - condition true. * will be the output
so in this case the will be printed first and the * will be printed later.
Updated Code:
I have updated your code. Have a look at the inner for loop.
for (int row = 1; row <= 10; row++)
{
for (int star = 1; star <= 10; star++)
{
if (star >= row)
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
Hope this helps :)

Change the inner loop to a standard 1 to 10 loop.
for (int row = 1; row <= 10; row++) {
for (int star = 1; star <= 10; star++) {
if (star >= row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}

The first job is to step away from the keyboard and think through the problem. It turns out that the condition for a star is "current row >= current column".
Implement that using
for (int row = 1; row <= 10; ++row){
for (int col = 1; col <= 10; ++col){
System.out.print( row >= col ? "*" : " ");
}
System.out.println();
}

Try this
int size = 10;
for (int row = 0; row < size; row++)
{
for (int i = 0; i < row; i++)
{
System.out.print(" ");
}
for (int i = size - row; i > 0; i--)
{
System.out.print("*");
}
System.out.println();
}

for(int i = 0 ; i < 10 ; i++){
for(int j = 0 ; j < 10 ; j++){
if(j >= i){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println("");
}

Related

Drawing stars up and down

I want to get this result, where _ space characters :
*___*
_*_*_
__*__
public static void main(String args[]) {
int level = 2; // quantity line
int stars = 5; //quantity drawing stars
for(int i = 1;i <= level ; i++){
for(int j =1 ;j <= i; j++){
System.out.print(" ");
}
System.out.println("*");
}
}
So far, I have drawn,
*__
_*_
__*
And I don't know how to draw up ?
Steps to solve these type of questions:
consider * as 1 and spaces as 0. Now i need this output :
10001
01010
00100
first 1 is appearing according to row no. Row 0 - 1 at Col 0, Row 1 - 1 at Col 1
Second 1 is appearing at (total columns-current Row index-1)
print 1 for above two condition otherwise zero.
int rows=3; // quantity line
int cols=5; //quantity drawing stars
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
int k=cols-i-1;
if(i==j || j==k)
System.out.print("*");
else System.out.print(" ");
}
System.out.println();
}
int size=10; // Only one parameter is required which is quantity drawing stars
int length= size%2==0?size/2:size/2+1; // in case of odd one more line need to be print at last on which one Asteric appears.
for (int i = 0; i < length; i++) {
for (int j = 0; j < size; j++) {
if (i == j || i + j == size - 1) { //condition for diagonals
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
Output :
when size = 10;
* *
* *
* *
* *
**
when size = 11
* *
* *
* *
* *
* *
*
You can try below code and output is what you want..
for(int i=3;i>=1;i--)
{
for(int j=i;j<3;j++)
{
System.out.print(" ");
}
for(int j=1;j<=(2*i-1);j++)
{
if(j==1 || j==(2*i-1))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}

How to print the right number of asterix in columns and rows?

I want to print asterix which is equals the number of rows - (they should begin from the right side). It should begin with 9 spaces and 1 * at the first line, then 2 * and 8 spaces at the second line and so on until the tenth row which should have 10 * and 0 spaces like the image below:
I can print the right number of spaces at each line and 1 * at the right position. For example it prints 9 spaces and 1 * at the first line. But then at the second line it prints 8 spaces and 1 * at the ninth position instead of two?? I can't see what I have missed in my code:
for (int row = 1; row <= 10; row++) {
for (int col = 10; col > row; col--) {
System.out.print(" ");
if (col <= row) {
System.out.print("*");
}
}
System.out.println("*");
}
There are several solutions:
1) Either you create two inner loops for each row: one to write the spaces and another to write the stars
final int rows = 10;
for(int row = 1; row <= rows; row++) {
for(int i = 0; i < (rows - row); i++) {
System.out.print(" ");
}
for(int i = 0; i < (row); i++) {
System.out.print("*");
}
System.out.println();
}
2) Or you create one inner loops for each row and check the index to consider if you have to print a star or a blank.
final int rows = 10;
for(int row = 1; row <= rows; row++) {
for(int col = 1; col <= rows; col++) {
System.out.print((col <=(rows - row))? " " : "*");
}
System.out.println();
}
3) Or you can use string manipulation with subString (this is ugly but why not):
final int rows = 10;
final String stars = "************************";
final String blanks = " ";
for(int row = 1; row <= rows; row++) {
System.out.print(blanks.substring(0, rows - row));
System.out.println(stars.substring(0, row));
}
This might also be helpful:
int n = 10;
int k = 2 * n - 2; // number of spaces
// outer loop to handle number of rows
for (int i = 1; i <= n; i++) {
// inner loop to handle number spaces
for (int j = 1; j <= k; j++) {
System.out.print(" "); // printing spaces
}
k = k - 2; // decrementing k after each loop
// inner loop to handle number of columns
for (int j = 1; j <= i; j++) {
System.out.print("* "); // printing stars
}
// ending line after each row
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

Regarding a star pattern

I am trying to print below star pattern
*
***
*****
***
*
I am using below logic to print :
*
***
*****
Code for first half:
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= i; j++)
System.out.print("*");
for (j = i - 1; j >= 1; j--)
System.out.print("*");
System.out.println();
}
But still I am not sure about how to print the whole structure.
You just have to write in reverse the loop, to start from the upperBound - 1. See the code bellow:
int numberOfLines = 3;
for (int i = 1; i <= numberOfLines; i++) {
for (int j = 1; j < 2*i; j++){
System.out.print("*");
}
System.out.println();
}
for (int i = numberOfLines - 1; i > 0; i--) {
for (int j = 1; j < 2*i; j++){
System.out.print("*");
}
System.out.println();
}
It will perhaps make sense to go in as simple steps as possible.
First, you need five lines, so
for (i = 1; i <= 5; i++) {
Next, on line i, determine the number of asterisks you are going to place. It is five asterisks on line 3, two less with each step above or below that line.
int len = 5 - Math.abs (i - 3) * 2;
Then, just place them in a single loop:
for (j = 1; j <= len; j++)
System.out.print("*");
And include a newline:
System.out.println();
}
The pattern consist of N * 2 - 1rows. For each row columns are in increasing order till Nth row. After Nth row columns are printed in descending order.
Step by step descriptive logic to print half diamond star pattern.
Input number of columns to print from user. Store it in a variable say N.
Declare a variable as loop counter for each column, say columns = 1.
To iterate through rows, run an outer loop from 1 to N * 2 - 1. The loop structure should look like for(i=1; i<N*2; i++).
To iterate through columns, run an inner loop from 1 to columns. The loop structure should look like for(j=1; j<=columns; j++). Inside this loop print star.
After printing all columns of a row, move to next line.
After inner loop check if(i <= N) then increment columns otherwise decrement by 1.
int columns = 1;
int N = 3;
for (int i = 1; i < N * 2; i++) {
for (int j = 1; j <= columns; j++) {
System.out.print("*");
}
if (i < N) {
/* Increment number of columns per row for upper part */
columns++;
} else {
/* Decrement number of columns per row for lower part */
columns--;
}
/* Move to next line */
System.out.print("\n");
}
Output:
*
**
***
**
*

Categories

Resources