Pyramids using asterisks - java

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

Related

The code that I have tried is not displaying the expected output. How can I rectify my code which is related to patterns?

I need to print a square pattern where the number increases as per the row, for example consider variable 'i' which represents row value, if you initialize i=1 and increase the value till 'n' which is user input using while loop, the first row will print 1, second row will print 2 and so on till it reaches the value 'n'. Additionally I created variable for column and named it 'j' whose value also increases till it reaches n.
The output that I'm getting though is:
enter image description here
The code that I have written is: (java)
enter image description here
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i =1;
while(i<=n){
int j = 1;
while(j<=n){
System.out.println(i);
j=j+1;
}
System.out.println();
i=i+1;
}
Why is the output for the above code:
enter image description here instead of
1111
2222
3333
4444
Please help me out.
Problem
The doc states the following and you know it
Prints an integer and then terminates the line
Fix
Use print instead
while (i <= n) {
int j = 1;
while (j <= n) {
System.out.print(i);
++j;
}
System.out.println();
++i;
}
Improvements
Could be a little bit nicer with for loops
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
System.out.print(i);
}
System.out.println();
}
Using String.repeat
for (int i = 1; i <= n; ++i) {
System.out.println(Integer.toString(i).repeat(n));
}

java nested loop logic for triangle's left side

Okay I am so tired of struggling with this and right off the bat I feel really stupid so please be gentle.. I've searched the stack overflow and web and still not finding anything. I am using a nested loop to create a triangle that looks like this:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
...etc. through 128 in the center column.
My loop for the left side renders to the right of my triangle instead of to the left. I'm pretty sure that after I receive an answer I will be hitting my head w/the palm of my hand and saying duh repeatedly. Anyway thanks for your help. I especially want an explanation of the logic. Here is the code.
public class Pyramid_center_x2_0519 {
public static void main(String[] args) {
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 1; j--) {
System.out.printf("%7s", "");
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
for (int leftSide = 2; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
System.out.println("");
}
}
}
Here is the way it renders:
Thanks again.......
UPDATED CODE 12 P.M. 5-31-16: I understand Java prints left to right. Below I have placed the left hand loop before the right side loop but my spacing in front of the triangle is not behaving. Thank you all... again
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 0; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
System.out.println("");
}
}
}
There is no way you can print left side after right and center side.
Java prints from left to the right.
(unless you use some arabic encoding)
Well, you already solved most of your Problems and your last updated version already prints the numbers correctly.
The only thing you still need to fix is the formatting to make it look nice.
Starting from your current code there are 2 things that need changing:
All your printed numbers are supposed to take up the same space (7). You already formatted your "right side" printed numbers in that way, all you have to do is do the same for the other numbers.
You currently allways add 8*7 spaces in front of the line, which of course isn't correct. If you look at the pyramid you can clearly see that 8*7 spaces is correct for the first line, but the second line would need 7*7 spaces in front, the third 6*7 etc. pp.
That means to get the correct formatting for you pyramid you have to modify your loop that prints the spaces to run 1 less time with each iteration of your main loop.
Here is one way how you could update your code to add those 2 changes (I added comments in front of the lines i changed as explanation):
public static void main (String[] args) throws java.lang.Exception
{
/** I added this counter to keep track
* of what iteration/line the loop currently is (see 2.)
*/
int iteration = 0;
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
/** Here we changed the loop condition
* from "j > 0" to "j > iteration"
* (So as iteration gets bigger, the loop runs less often)
*/
for (int j = 8; j > iteration; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
/** This should be self explanatory.
* You already did the same for rightSide.
* This will take care of 1.
*/
System.out.printf("%7d", leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
/** Here we increment our counter with each iteration aka line that is printed */
iteration++;
System.out.println("");
}
}
Try this
Edited: First try to put your spaces before putting your number in triangle(here my first inner for loop is doing) then apply some logic to print the number at its position accordingly.
static DecimalFormat df = new DecimalFormat("#");
public static void main(String[] args) {
for (int i = 1; i < 10; i += 2) {
for (int k = 0; k < (4 - i / 2); k++) { // first
System.out.print(" ");
}
for (int j = 0; j < i; j++) { // second
if (Math.pow(2, j) <= i)
System.out.print(df.format(Math.pow(2, j)));
else
System.out.print(df.format(Math.pow(2, i - j - 1)));
}
System.out.println("");
}
}
I think your approach is not good. Try this algorithm:
public class Main {
public static void main(String[] args) {
int levels = 8;
int lastLevelWidth = levels*2 + 1;
for (int i=0; i<levels; i++) {
int blankPositions = (lastLevelWidth - 1)/2 - i;
for (int j=0; j<blankPositions; j++)
print(" ");
int levelWidth = i*2 + 1;
int numberPositionsPerSide = (levelWidth-1)/2;
for (int j=0; j<numberPositionsPerSide; j++) {
print(Math.pow(2, j));
}
print(Math.pow(2, i));
for (int j=numberPositionsPerSide-1; j>=0; j--) {
print(Math.pow(2, j));
}
System.out.println();
}
}
public static void print(String string) {
System.out.print(string);
int spaces = 5 - string.length();
for (int i=0; i<spaces; i++)
System.out.print(" ");
}
public static void print(double n) {
print(Integer.toString((int)n));
}
}

Nested for loop in java to print the following

How would i print the following in Java:
5
55
555
55
5
using just nested for loop with no if statements.
What i have so far:
public static void main(String[] args) {
for(int i = 1; i < 6; i++) {
for(int k = 3; k > i; k--) {
System.out.print(" ");
}
for(int k = 3; k < i; k++) {
System.out.print(" ");
}
for(int j = i; j > 0; j--) {
System.out.print("5");
}
System.out.println();
}
}
As you can see, I got the spaces correct but not the number of 5's on each line yet.
I somehow feel that there must be possible to use just 1 for loop for all the spaces?
You need to first break the pattern in two parts :
Upper Half
5
55
555
Lower Half
55
5
In upper half there are 3 rows to be printed. Analyze each row.
For row no. 1 there are 2 blanks and 1 "5".
For row no. 2 there is 1 blank space and 2 "5"s.
For row no. 3 there is no blank space and 3 "5"s.
So if i represents my rows then when i is 1 i.e. row no. 1 no. of blank spaces to be printed is (3-i) i.e. 2 and no. of "5"s to be printed is i i.e. 1.
On similar lines you can break the complete problem.
Solution:
class Main{
public static void main(String args[]) {
for(int i=1;i<=3;i++) {
for(int j=1;j<=(3-i);j++) {
System.out.print(" ");
}
for(int j=1;j<=i;j++) {
System.out.print("5");
}
System.out.println();
}
for(int i=1;i<3;i++) {
for(int j=1;j<=i;j++) {
System.out.print(" ");
}
for(int j=1;j<=(3-i);j++) {
System.out.print("5");
}
System.out.println();
}
}
}
You want the number of spaces you print to decrease up to a point and then start increasing again, so one option is to use abs():
int n = 3; // number of columns
for (int i = 0; i < 2 * n - 1; i++) {
int k = Math.abs(n - i - 1);
for (int j = 0; j < k; j++)
System.out.print(' ');
for (int j = 0; j < n - k; j++)
System.out.print('5');
System.out.println();
}
5
55
555
55
5
Here, k is the number of spaces we want to print (hence n-k is the number of 5s, as can be seen in the second for-loop). k decreases as i approaches n - 1, at which point it becomes 0. As i increases further, the term inside abs() becomes increasingly negative meaning that its absolute value begins growing again.
You can use 1 for loop for the number of rows and a 2nd one for the number of columns. In this way you will need to use 4 for loop ..

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;

Java Homework - Printing a triangle pattern?

I'm struggling with an assignment. I understand that it is entirely my fault, but I've fallen behind in my classes and am struggling with this assignment.
My goal is to print the following pattern:
*
**
***
****
*****
******
*******
********
*********
**********
Using (nested) for loops.
Would anyone be able to give me hints on how I might go about this? I've managed to print a square of asterisks, but I'm having trouble figuring out how to make a triangle.
Thanks in advance for the help.
First figure out how many lines you need to print out. That's your first for loop. Then on each line, how many asterisks do you need to print out (suppose you are on line i, how many asterisks are on line i)? Answer those questions first and the program should come easily.
Review the following. It doesn't do exactly what you need to do but it will help get you started.
for (int x = 1; x <= 7; x++) {
for (int y = x; y <= 7; y++) {
System.out.print("(" + x + ", " + y + ")");
if (y == 7) {
System.out.print("\n");
}
}
}
Okay, so you basically have to print out as many asterisks as the line number, right?
I'm not allowed to give you code, as this is a homework assignment, but I can give you pseudocode.
start with variable i at 1, loop while i is less than or equal to 10, increment i
// The line of code that you just wrote will execute once per line.
// Now you can print out your asterisks.
// Make another loop and execute it once per asterisk. That's i times, right?
start with variable j at 1, loop while j is less than or equal to i, increment j
print out an asterisk
end loop
end loop
You need 2 loops for these type of problems . 1st loop is used for iteration and the second one for printing the stars. Here 1st u need to get the input from the user and store it in a variable suppose 'n' and the 1st loop should iterate till n .
for(i=1;i<=n;i++)
{for(j=1;j<=i;j++)
{ System.out.print("*");
}
System.out.println("");
}
java8 solution:
IntStream.rangeClosed(0, MAX)
.forEach(i -> IntStream.rangeClosed(0, i)
.mapToObj(j -> j == i ? "*\n" : "*")
.forEach(System.out::print)
);
here is an outline.
for (i = 1; i < 11; i++) {
String toPrint = "";
for (j = 1; j <= i; j++ {
// create string of asterisks here
}
// print a line here
}
since this is homework, you should do the rest yourself
Solution 1:
for(int i=1; i< 10; ++i) {
for (int j = 0; j<i; ++j) {
System.out.print("*");
}
System.out.println("");
}
Soulution 2:
String s = "*";
for (int i = 1; i< 10; i++) {
System.out.println(s);
s = s + "*";
}
Your choice.
class Program
{
static void Main(string[] args)
{
String var = "";
String exp_Str = "";
for (int i = 1; i < 8; i++)
{
for (int j = 1; j < i; j++)
{
if (i > j)
{
var = var + j;
//Console.WriteLine(j+"");
}
}
Console.WriteLine(var);
var = "";
}
Console.ReadLine();
}
}
use a for loop
for(i=0;i<10;i++){
for(int j=0;j<i;j++)
System.out.print("*");
System.out.println();
}
hope that helps!

Categories

Resources