Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}
Related
I did the stair case problem in java. I wrote it but it did not work. So I am posting it so that if anybody could check for my mistake. Thanks.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int f=n;
for(int i=0;i<n;i++)
{
for(int j=0;i<f;j++)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print("#");
}
f=f-1;
System.out.println(" ");
}
}
The input was 6
and the output pattern should be
#
##
###
####
#####
######
but mine is not producing anything
the code is fixed the code should have been
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int f=n;
for(int i=0;i<n;i++)
{
for(int j=1;j<f;j++)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print("#");
}
f=f-1;
System.out.println(" ");
}
}
thanks for all the help guys ...blessed to have a community like this..:)
This line is wrong
for(int j=0;i<f;j++)
{
System.out.print(" ");
}
Should be
for(int j=0;j<f;j++)
{
System.out.print(" ");
}
You switched i and j so your never exiting that for loop
Let's break down what each part of your code is doing, and see if the answer becomes obvious:
int n=sc.nextInt();
int f=n;
So, we read in a number (in this case 6) and set both n and f to be this value.
for(int i=0;i<n;i++)
{
Here, we're going to repeat the following block 6 times, with i equal to 0, then 1, then 2, 3, 4, and 5. We'll stop when i is no longer less than n, which is 6 in this case.
So, we start the loop, and i is 0. n and f are both still 6 because we haven't changed them.
for(int j=0;i<f;j++)
{
Another loop, this time we're starting with j at 0, and continuing until i is no longer less than f. What were i and f again? i is 0 (we're on the first time through that outer loop) and f is still 6. 0 is less than 6, so we start this loop.
System.out.print(" ");
}
We print a space, and find the end of the loop, so we go back around to the for(int j=0... loop, incrementing j (because we said j++ in the start of this loop).
So, now the values we have are: j = 1, i = 0 and f = 6. We check the loop condition - i<f - and 0 is still less than 6, so we repeat the loop again, and print another space, and again repeat the above.
Nothing within that loop is ever changing the values of i or f, so the condition for the loop (i<f) is always true, and we just end up in an infinite loop, printing spaces forever. j increments on each iteration, so it goes up to 1, 2, 3, etc, but as you never refer to it again, that's irrelevant.
So, the problem is that you need to change the loop condition, so that you can exit the loop, and move on to the other parts of your program.
Given that your loop is iterating over j, and you're incrementing that as you go, my guess is that you want to be using that to determine whether or not to end the loop - so, you probably want to make it the condition j<f instead of i<f, that is:
for(int j=0;j<f;j++)
{
System.out.print(" ");
}
I'm not sure if that will make your program perfect, or if you'll hit another similar problem, but hopefully by breaking it down like this you can see the sort of thought process you need to go through in order to solve whatever the next problem you encounter is. Basically, you need to pretend to be the computer and work through each line individually, writing down what the value of each variable is every time it changes. It's not hard, but it is time-consuming and annoying - welcome to programming!
I think this is plain easy and could be done with couple of lines. All you need is just two counters (one for rows, and another to split empty part and # part).
int rows = 6;
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ? ' ' : '#');
System.out.println();
}
With Java 8 streams, String.format you could solve the problem in a more succinct manner:
int limit = 6;
IntStream.rangeClosed(1, limit)
.forEach(i -> System.out.printf("%" + limit + "s%n", String.join("", Collections.nCopies(i, "#"))));
This is how the "#" gets repeated:
String.join("", Collections.nCopies(i, "#")
Using System.out.printf with "%" + digit + "s" right aligns a string.
you can do like this also for StairCase pattern.
for(int i=0;i<n;i++){
for(int j=n;j>=0;j--){
if(j<=i)
System.out.print("#");
else
System.out.print(" ");
}
System.out.println();
}
}
for input 6 the output is
#
##
###
####
#####
######
I have a short program that creates an array of integers and removes non-primes:
public class Main {
public static void main(String[] args){
int[] nums = new int[100];
for (int i = 0; i < nums.length; ++i){
nums[i] = i + 1;
}
int j = 0;
while(j < nums.length){
System.out.print(nums[j]);
System.out.print(" ");
j++;
}
for (int n = 1; n < nums.length / 10; n++){
for (int p = n; p < nums.length; p += nums[n]){
if(p > n){
nums[p] = 0;
System.out.println("p"+nums[p]);
}
}
}
//this code doesn't execute
System.out.println("x");
}
}
The statement which is supposed to simply print "x" doesn't execute, nor does any other statement I put after the for loop. The program does not enter an infinite loop, so what's going on? I feel like this is something obvious that I'm just missing.
Edit: it was an infinite loop, I just didn't realize it.
In your p loop, on the second iteration, p > n is true and you set nums[p] to 0. From that point forward, p will never increase, because your incrementer is p += nums[n] and nums[n] is 0, and so your loop never terminates.
This sort of problem is best solved by using a debugger. Using a debugger is a fundamental skill for a programmer. With a debugger, you can step through statements, inspect variables, and see exactly what your code is doing. It's not an advanced technique, it's essential from Day 1 so you can correctly diagnose issues with your code. If you don't currently know how to use a debugger, stop what you're doing and learn to use one, it will be incredibly valuable and time-saving to you. There's almost certainly one built into your IDE.
Are you falling into a infinite loop? In the console press cmd+c or ctrl+c and see what that does. If the program stops it is a sign of a infinite loop.
I have a specification as below:
Write a program that prints out all the permutations of two numbers that add up to 7. Hint: you can use two nested for loops.
I have done this but I know this is not correct. What numbers should I put in?
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=3; i++) {
for(int j=1; j<=i; j++) {
System.out.println(i+ " " +j);
}
}
}
}
Try this (I am assuming you want non-negative numbers, otherwise you have infinite possibilities):
for(int i=0; i<=7, i++)
{
System.out.println(i + "+" + (7-i));
}
No need for two for loops.
If instead of non-negative you require positive numbers, this would become:
for(int i=1; i<7, i++)
{
System.out.println(i + "+" + (7-i));
}
You are almost there. Here are the things that you need to consider:
Assuming that the numbers are required to be positive, the outer loop should go from 1 to 6, inclusive, not from 1 to 3.
Numbers do not need to be in order. Hence, you should not stop the inner loop at i, also going from 1 to 6, inclusive
You need to add an if check before printing i and j.
Once you fix the three things above, your program should work. Good luck!
Your loops should both loop between 1 and 7. Then inside the last for loop you need to check if the sum of i and j equals 7. If it does, print those two numbers.
You really don't need a nested loop.
for (ii = 0; ii<8; ii++) {
System.out.printf("(%d, %d)\n",ii,7-ii);
}
Keep it simple.
I know the "hint" said you could use two nested loops; but in my experience a little bit of cleverness should not be ignored. When your problem gets much larger, being O(n) rather than O(N^2) is a huge difference...
Try this:
for(int i=0;i<7;i++){ //First Loop
for(int j=7;j>0;j--){//Send loop
if((i+j)==7) System.out.println(i+" , "+j); //Permutations printed to terminal
}
}
I guess it's self explaining, two loops going towards each other. Run it and see the lovely result ;)
In mathematics, the notion of permutation relates to the act of permuting (rearranging) objects or values.
A couple of adjustments: I'm taking the liberty of posting a solution but please make sure you understand it!
for (int i = 0; i <= 7/*Need to consider all numbers from 0 to 7*/ ; ++i) {
for (int j = 0; j <= i /*Don't overoptimise: this is good enough and will not generate duplicates*/; j++) {
if (i + j == 7){
System.out.println(i+ "," +j);
}
}
}
It's not the fastest way; spend some time optimising once you have a solution.
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=7; i++) {
for(int j=1; j<i; j++) {
if (i + j == 7 ) {
System.out.println(i+ " " +j);
}
}
}
}
}
Check if they add up to 7
if (i+j == 7)
{
//then they add to 7
}
They should both be between 1 and 7 though if you want all numbers between 1 and 7 that add up to 7. If you want to include 0 then start there.
for (int i=1; i<=7; i++)
...and you may want to exclude duplicates
for(int i=1; i<=7; i++) {
for(int j=i; j<=7; j++) { //starts at i, not 1
/* Only check j against numbers equal to or lower than itself
/* to avoid duplicates
*/
}
}
Additionally
Class names should start with a capitol letter, by convention, and in camel case (each word in a phrase has capitol letters
NestedFor
Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
public class Test{
public static void main(String args[]){
int counter = 0;
for(int i=0; i< 4; ++i){
for(int k=0; k< 4; ++k){
system.out.println("Hello - "+ ++counter);
if((k % 4) == 0)
break;
}
}
}
}
So the answer they give is "Hello-1" because 0 % 4 = 0
But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!
A for loop has the following structure:
for (initialization; condition; update)
The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {
and
for (int i = 0; i < 10; ++i) {
my question is should k not be 1 because its been pre-incremented?
The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.
So the answer they give is "Hello-1"
This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.
k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0.
Doing some homework in my CSC 2310 class and I can't figure out this one problem... it reads:
Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 '', the second line, 99
'’... the last line, only one '*'. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can't figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print i * characters on a single line, so you just need:
for (int j = 0 ; j < i ; j++) System.out.print("*");
System.out.println(); // newline at the end
Hence you will have:
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
Or equivalently,
for (int i = 100 ; i > 0 ; i--) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
EDIT Using only while loops:
int i = 100; // this is our outer loop control variable
while (i > 0) {
int j = 0; // this is our inner loop control variable
while (j < i) {
System.out.print("*");
j++;
}
System.out.println();
i--;
}
So to break it down:
We have an outer loop that loops from i = 100 downwards to i = 1.
Inside this outer while loop, we have another loop that loops from
0 to i - 1. So, on the first iteration, this would be from 0-99
(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a * character. But we do this i
times (because it's a loop), so the first time we have 100 *s, then 99, then 98 etc. (as
you can see from the point above).
Hence, the triangle pattern emerges.
You need two loops, one to determine how many characters to print on each line, and an inner nested loop to determine how many times to print a single character.
The hint is that the inner loop doesn't always count to a fixed number, rather it counts from 1 to (100 - something).
Try this:
public class PrintTriangle {
public static void main(String[] args) {
for(int i = 100; i >= 1; i--){
System.out.print("\n");
for(int j = 0; j < i; j++){
System.out.print("*");
}
}
}
}
Explanation: The nested for loop has a variable named j. j is the amount of times * has been printed. After printing it checks if it is equal to i. i is a variable in the big for loop. i keeps track of how many times a line has been printed. \n means newline.
You could come at it side ways...
StringBuilder sb = new StringBuilder(100);
int index = 0;
while (index < 100) {
sb.append("*");
index++;
}
index = 0;
while (index < 100) {
System.out.println(sb);
sb.deleteCharAt(0);
index++;
}
But I think I prefer the loop with loop approach personally ;)
You could improve the effiency of the first loop by increasing the number of stars you add per loop and reducing the number loops accordingly...
ie, add 2 starts, need 50 loops, add 4, need 25, add 5 need 20, add 10, need 10...
For example
while (index < 10) {
sb.append("**********");
index++;
}