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!
Related
i'm trying to print out a shape that looks something like this:
*
**
***
****
*****
To do that i'm using a for loop:
for (int i = 1; i <= 5; i++) {
System.out.print("*");
System.out.println;
}
but how do I get the line 2 to print i asterisks, instead of just the one asterisk as i have so far?
The logic you want to articulate here is that, for each row, print as many asterisks as the current row number. Nested loops can be used here:
for (int i=0; i < 5; i++) { // the row
for (int j=0; j <= i; ++j) { // the column
System.out.print("*");
}
System.out.println();
}
If you are using java 11 or greater you can use public String repeat​(int count).
for (int i = 1; i <= 5; i++) {
System.out.println("*".repeat(i));
}
You can use
for (int i = 1; i <= 5; i++ ){
System.out.println(new String(new char[i]).replace('\0', '*'));
}
to print * according to the value i contains each time it loops
It basically creates a new char array of size i and replaces all the nulls , i.e.('\0'), with * of that char array, and then it converts the char array into one single string and prints it.
I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######
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));
}
}
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;
}
}}
I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}