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 ..
Related
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));
}
I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890
I need to be able to get this pattern using for loops:
Q. Write a program to complete the first N rows of the following output. The number of rows N should be read from the keyboard.
Intended output:
1
2 4
3 6 9
4 8 12 16
Result:
1
24
399
4161616
525252525
Attempt:
(I haven't used scanner yet, because I wanted to try understand how to do it without scanner.)
import java.util.Scanner;
public class Test {
public static void main(String [] args){
int odd = 1;
for(int i=1;i<=5;i++)
{
int no=i;
for(int j=1; j<=i;j++)
{
System.out.print(no);
no = i*i;
}
System.out.println();
}
}
}
You were very close!
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
See demo
I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}
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;
}
}}