Patterns using for loops - java

I am supposed to create this pattern based on the number a user enters. The number the user enters corresponds to the number of rows and stars in each row.
*
**
***
****
*****
I was told to only use nested for loops and cannot use printf(). This is only part of the code that I am working on.
for (int row = 1; row <= size; row++) {
for (int column = 1; column <row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
I cannot seem to make my output as shown above. Instead I get this:
*
**
***
****
*****
Could someone give me a hint as to what I am supposed to do? I have spent 2 hours but still can't figure it out.

For each row, you should output maximum size characters; so if size = 5, on third row, if output three stars, then you need size-row spaces => 5 - 3 = 2.
In code:
for (int row = 1; row <= size; row++) {
for (int column = 1; column <= size-row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
Sample: http://ideone.com/hC5HDQ

You want to start with more spaces, then remove them until there is not more left. But while removing spaces, you also want to add and additional " * ". So for every space removed you will add an " * "

Try this
int i=5;
do{
int j=5;
while(j>i){
System.out.print("*");
j--;
}
System.out.println();
i--;
}while(i>0);

Related

How to display first column and row only?

I have created a multiplication table. However, it cannot display the first row and column with my code. Is this even achievable via loop? Herr is my code:
int a;
int b;
for (a=1; a<=3; a++)
{
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
System.out.println();
}
The output of this code is:
1 2 3
2 4 6
3 6 9
However, i want the 123 on a row and column to display only. Is this achievable?
Desired output:
1 2 3
2
3
A basic approach is to know where your outer loop is at and print accordingly to your desired result.
public class StackOverflow {
public static void main(String[] args) {
int a;
int b;
for (a=1; a<=3; a++)
{
// Only print the first row
if (a == 1) {
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
// Ends the first row
System.out.println("");
} else {
// Prints the rest of the first column
System.out.println(a);
}
}
}
}
Result:
1 2 3
2
3
UPDATE
If I understand your comment, here's an approach with just one loop. It assumes that the size of the row will equal the size of the column. This means that the number of digits you'll display will be an odd number (rowColLength * 2 - 1) which makes the first digit a pivot point.
public class StackOverflow {
public static void main(String[] args) {
int a = 0;
int rowColLength = 3;
int numberOfDigits = rowColLength * 2 - 1;
for (int i = 0; i < numberOfDigits; i++) {
if (i < rowColLength) {
// Prints the first row
System.out.print(++a + " ");
} else if (i == rowColLength){
// Decrements the last number from the first row
// to continue the column count for printing
System.out.print("\r\n" + --a);
} else {
// Prints the rest of the column
System.out.print("\r\n" + ++a);
}
}
}
}
Result:
1 2 3
2
3
I think you want the upper bounds to be limited.
Better readable would be:
int rows = 3; // 1?
int columns = 10; // 1?
for (int row = 1; row <= rows; ++row) {
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
The printf prints digits, padded to the left upto 3 positions with spaces.
If you want a header row and column à la Excel:
// Header row:
System.out.print("AxB ");
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", column);
}
System.out.println();
System.out.print("---|");
for (int column = 1; column <= columns; ++column) {
System.out.print("---");
}
System.out.println();
// Data rows
for (int row = 1; row <= rows; ++row) {
System.out.printf("%3d|", row); // Column header
for (int column = 1; column <= columns; ++column) {
System.out.printf("%3d", row * column);
}
System.out.println();
}
Print header and columns labels in 2 different loops:
int a;
int b;
// Print header label
for (b=1; b<=3; b++) {
System.out.print(b + " ");
}
System.out.println();
// Print column label
for (b=2; b<=3; b++) {
System.out.println(b);
}
The output:
1 2 3
2
3
Several possibilities, you could for example save the result to a variable and not print it if bigger than 3.
int temp = a*b
if (temp < 4){
System.out.print(temp);
else {
System.out.print(" ");
}

Pyramids using asterisks

One of my questions was a problem asked by my prof and that is write a loop that will display the following patterns
I have figured out A but my problem is B the second one
My code for A
for( row = 10; row >= 0; row--) // number of rows
{
for( cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print( "*");
}
System.out.println();
}
I have done multiple different ways and have came to the conclusion that A)
is going
row(10)1.2.3.4.5.6.7.8.9.10
row(9) 1.2.3.4.5.6.7.8.9
row(8) 1.2.3.4.5.6.7.8
and B) is doing something in the lines of
row(10) 1.2.3.4.5.6.7.8.9.10
row(9) 2.3.4.5.6.7.8.9.10
row(8) 3.4.5.6.7.8.9.10
Can anyone help me with what I am missing in my code to turn it into the mirror image.
The easy way to handle such a problem is to know how many lines you have and base your code on that. The first for loop represents how many lines the pyramid has, in this case, 10. The way to base the number of stars or spaces on the line is the following.
Basically the formula is:
Rate of change*(line) + X = Amount of stars/spaces at that line
Start by getting rate of change, then you get the X and implement it in your code.
In the first line you have 10 stars, then on the second 9 stars, on the third 8 stars, so on and so forth. In order to get rate of change, you subtract the second amount of stars with the first, or the third with the second (you get the same result, since it is decreasing at the same rate). Try 9-10 or 8-9 you get -1. So if you pick the first line, by using the formula you get -1*1 + X = 10, where X will be equal 11. If you would check the "-1*line +11" inside the second for loop, and take line = 1, the answer you get will be 10, which is the amount of stars you have on line 1. You will get the same formula if you take line 2 or 3. Take line 3, you get -1*3 + X = 8 which results in X = 11.
Note that what you use in your code is left hand side of the formula i.e Rate of change*(line) + X
Next you have the number of spaces. I do not know how many spaces you have on the first line, therefore I assumed you have 10 spaces, and incremented by 3. So 10 on the first line, 13 on the second and so on. Again you do the same steps. You need to base your calculations on the amount of lines, first by getting the rate of change by subtracting the amount of spaces on the second line by the first (13- 10). Take line 1. 3*1 + X = 10 (since on the first line we have 10 spaces). X = 7. Try line number 2, 3*2 + X = 13, you still get X = 7. Now you know you have a solid constant formula you can use in your code.
We implement it in the code.
public class Pyramid {
public static void main (String [] args){
for(int line = 1; line <=10; line++){
//j is decreasing since number of stars are decreasing
for(int j = -1*line + 11; j >=1; j--){
System.out.print("*");
}
//k is decreasing since number of spaces are increasing
for(int k = line; k <= 3*line +7; k++ ){
System.out.print(" ");
}
for(int j = -1*line + 11; j >=1; j--){
System.out.print("*");
}
//End of line, start new one
System.out.println();
}
}
look into String.format() where you can pad (left or right) any string to a certain width like so:
String stars = //use your loop from (a) to produce a number of stars
String toOutput = String.format("%10s", stars);
You want to try something like this:
for( int row = 10; row >= 0; row--) // number of rows
{
for( int cnt = 10; cnt - row >= 0; cnt--) // number of stars
System.out.print(" ");
for (int cnt = 0; cnt <= row; cnt++)
System.out.print( "*");
System.out.println();
}
Hope that helps.
There you go ! I put everything into a class for you so that you can run the program directly..
I am not implementing it very efficiently probably.
As you can see I am printing spaces which start from 10, and for every line I add 2 more spaces in order to mirror the "asterisk" effect
public class asterisk {
public static void main(String[] args) {
int spaces=10;
for( int row = 10; row >= 0; row--) // number of rows
{
for( int cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print( "*");
}
for( int cnt = 0; cnt < spaces; cnt++) {
System.out.print( " "); }
spaces=spaces+2;
for( int cnt = 0; cnt < row; cnt++) {
System.out.print( "*"); }
System.out.println();
}
}
}
If you want more or less than 10 spaces between A and B you just change the initial value that you set the variable "spaces" to !
Here is a complete code -
int main(){
char star = '*';
char space = ' ';
int noOfTimesToPrint = 10;
int noOfSpaceToPrint = 1;
int line = 0;
int starCount = 0;
int spaceCount = 1;
for(line=1; line<=10; line++){
for(starCount=1; starCount<=noOfTimesToPrint; starCount++){
printf("%c", star);
}
for(spaceCount=1; spaceCount<=noOfSpaceToPrint; spaceCount++){
printf("%c", space);
}
noOfSpaceToPrint = noOfSpaceToPrint+2 ;
for(starCount=1; starCount<=noOfTimesToPrint; starCount++){
printf("%c", star);
}
printf("\n");
--noOfTimesToPrint;
}
}
Some explanations -
You can adjust the initial no of space to print by setting noOfSpaceToPrint. Here it is set for printing 1 space. You can adjust according to your requirement.
The first inner for loop block print the A portion of your image
The second inner for loop block print the space portion of your image and
The last inner for loop portion print the B portion of your image
The outer for loop portion is used to print a line that is -
line 1 : ********** **********
and so on
Hope It will help.
Thanks a lot
Output of the code is :
Probably shouldn't word your question as asking for homework answers but nonetheless:
public class PyramidPrinter
public static void printPyramid(boolean mirrorize) {
for (int i = 10; i > 0; i--) {
if (mirrorize) {
for (int j = 10; j > 0; j--) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
} else {
for (int j = 0; j < 10; j++) {
if (i > j) {
System.out.print("*");
} else {
System.out.print(" "); // might not even need
}
}
}
System.out.println();
}
}
public static void main(String[] args) {
printPyramid(false); // A
printPyramid(true); // B
}
}
The key here is use of a combination of forward and backward incrementing for-loops, to essentially pad spaces with asterisks and pad asterisks with spaces.
Results:
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
This is my ending result for my code based on all the information I have gathered here, thank you all. `
for( row = 10; row >= 0; row--) // number of rows
{
for( cnt= 10; cnt - row >= 0; cnt--) // number of spaces before the asterisk
{
System.out.print( " ");
}
for( cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print("*");
}
System.out.println();
}
}
`
public class Printstar {
public static void main(String[] args){
int space=1;
for(int i=1;i<=10;i++)
{
for(int j=0;j<10-i;j++)
{
System.out.print("*");
}
for(int j=0;j<space;j++)
System.out.print(" ");
for(int j=0;j<10-i;j++)
System.out.print("*");
System.out.println();
space=space+2;
}
}}

Formatting array output into 9x9 box

I had to write a program for my class that creates a 9x9 multiplication table. I've written the program to where the numbers are correct but I don't know how to format it to where the output is in a 9x9 box. Thanks for the help in advance.
import java.io.*;
import java.util.Scanner;
public class MultTable
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int multTableSize = 9;
int[][] multTable = new int[multTableSize][multTableSize];
for (int row = 0; row < multTable.length; row++)
{
for (int column = 0; column < multTable[row].length; column++)
{
multTable[row][column] = (row + 1) * (column + 1);
System.out.print(multTable[row][column] + " ");
}
}
System.out.println();
}
}
First, you are adding the line break outside both of your loops, rather than at the end of the first loop, and second, for text formatting, you are better off using printf() than println().
Try something like this:
for (int row = 0; row < multTable.length; row++) {
for (int column = 0; column < multTable[row].length; column++) {
multTable[row][column] = (row + 1) * (column + 1);
System.out.printf("%3d", multTable[row][column]);
}
System.out.println();
}
%3d is a format string which will make your numbers appear in 3-character wide columns.
See the Formatter class docs to learn more about how to format output in Java.
Perhaps use a System.out.println(); after your inner loop?
for (int row = 0; row < multTable.length; row++)
{
for (int column = 0; column < multTable[row].length; column++)
{
multTable[row][column] = (row + 1) * (column + 1);
System.out.print(multTable[row][column] + " ");
}
System.out.println();
}
after the end of the second loop --> you need to skip one line..

Printing a centered pyramid in Java with ascending and descending numbers

I'm trying to print a centered pyramid of 2^n, where 2^row# is the centered number of each row, the numbers to the left are ascending to 2^row# and the numbers to the right are descending. I'm pretty new to Java and it took me a really long time to get this much. But now I'm stuck. The last row is the only row that is correct. I don't know how to make it so 64 is not printed on every line. Can anyone please give me a hint?
I've tried messing with every single parameter - starting the last loop with the first row, the last row, changing the starting power, etc. and I just can't figure it out.
Thank you for any hints!
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
}
}
Your problem lies in the fact you always start the right side of the pyramid at 2^7, since you hard code the power2 = 7 decleration and assignment. If you start this value instead at the current row - 1, you get the behavior you're looking for. Code:
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = row - 1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
This part is not right.
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
On row 2 you get power2=6 so you display 2^6=64.
You should instead be doing something like
int power2 = power1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
You are assigning constant to power2 instead of depending value on row. Can you try this please.
int power2 = row-1;

little java help with loops

Hi I am doing some practice problems and trying to print a diagonal line like the example below. I have writen the program you see below and I honestly dont understand what I am doing wrong. I m a java beginner and I cant see how to find the error.
Example:
*
*
*
*
*
code:
class Diagonal{
public static void main(String args[]) {
int row, col;
for(row = 1; row < 6; row++) {
for(col = 1; col <= row; col++) {
if(col==row){
System.out.print("*");
} else{
System.out.print("");
}
System.out.println();
}
}
}
}
I am trying to learn for loops because they really confuse me. Another practice is to print a similar diagonal line but this time from right to left. I cant do that without getting this right however :( I believe they will be pretty similar?
Above my reasining is this: As long as the column # is the same as the row number the print the line or otherwise leave a blank....what's wrong with how i did it?
THANK YOU!
You never print any space character. You print an empty String. Replace
System.out.print("");
with
System.out.print(" ");
Also, you write a newline after each column rather than writing one after each row.
String spaces = "";
for(int row = 1; row < 6; row++) {
System.out.println(spaces+"*");
spaces += " ";
}
Print new lines when entering a star: System.out.println("*");
Add spaces: System.out.println(" ");
remove the line where you print new lines between columns.
as said before replace black with space and move the end line to the end of the FIRST for() like this:
class Diagonal{
public static void main(String args[]) {
int row, col;
for(row = 1; row < 6; row++) {
for(col = 1; col <= row; col++) {
if(col==row){
System.out.print("*");
} else{
System.out.print(" ");
}
}
System.out.println();
}
}
}

Categories

Resources