Printing the factors of 2-100 in java - java

I am trying to minimize the iteration so I used j<=i/j in the 2nd for loop. The code is working but I can't get the full output. I mean factors of 6 are 2 and 3, but it is only printing 2.
Can anyone help me? I am a beginner.
class factors{
public static void main (String args[]){
int i,j;
for(i=2;i<=100;i++){
System.out.print("\nFactors of "+i+" : ");
for(j=2; j <= i/j; j++){
if((i%j)==0){
System.out.print(j+" ");
}
}
}
}
}

After:
System.out.print(j+" ");
Add:
System.out.print((i/j)+" ");
The point of iterating until i/j is because the factors come in pairs, j and i/j, and you only need to iterate over half of them, and the others can be calculated from the ones you find.

You get an unexpected output because i/j will be evaluated every iteration of the loop.
When j=2, i/j is 3, so the condition is true, and the first iteration of the loop runs. The next iteration, j=3, i/j is 2, which less than j, the condition is false, so the loop terminates there, without running the second iteration.
I think what you meant to say is i / 2. So change i/j to i/2.

for(j=2; j <= i/j; j++)
Let run the code for i=6
So first it intialize j to 0 and then
J<=6/2 so it it true because 2<=3
But on next iteration
J=3 and then
J<=6/3 in this it is not true because 3<=2
So change the condition.

for(j=2; j <= i/j; j++){
if((i%j)==0){
System.out.print(j+" ");
}
}
There are two problems in this code.
First, you only print one factor (j) when you find pairs (both j and i/j). Already mentioned here.
Second, fixing that by printing j and i/j breaks the result for perfect squares, where j and i/j are the same (equal). It prints the square root as a factor twice. To fix that, you can stop the loop before you test a perfect square. Then you can test for that special case outside the loop.
for (j = 2; j < i/j; j++) {
if ((i%j) == 0) {
System.out.print(j + " " + i/j + " ");
}
}
if (j * j == i) {
System.out.print(j);
}
Another alternative would be to check if j and i/j were equal before printing i/j. Something like
System.out.print(j + " ");
if (j != i/j) {
System.out.print(i/j + " ");
}
But that requires more checks than is necessary, because equality will only happen once per the loop. But you have to check once for every factor pair that you find.

Related

Staircase is not working, there are bugs in my code

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
#
##
###
####
#####
######

Printing Simple Patterns in Java

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(" ");
}
}
}
}

Using nested for loops

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

Reverse printing of an array

(Java beginner)
I came up with a code that would display an int array in reverse and although I know there's probably a better way to do it, I think this logic should work:
for(int i = 0, j = numList.length - 1; i < j; i++, j--)
{
int temp = numList[i];
numList[i] = numList[j];
numList[j] = temp;
System.out.print("Reverse order: " + temp + " ");
}
What I don't understand is that when I enter 5 numbers, the console only shows the first two numbers and it ends there:
1
2
3
4
5
Reverse order: 1 2
What's wrong here and what can I do to fix it?
That code is just faulty. Use this instead.
for(int i = numList.Length - 1; i >= 0;i--)
{
int temp = numList[i];
System.out.print("Reverse order: " + temp + " ");
}
In your code, you increment i and decrement j, meaning that if you'd loop untill your condition is satisfied, you'd get about half the loop done. Try and create a table of the values of your loop step by step, you'll see what I mean :)
i++ and j-- along with the loop iteration condition of i < j would become false when i and j reach the middle of the array. So essentially your for loop is only working up the first half of the loop. I didnt run you code but this is the first observation i made.

Seems to be an extra output in nested for loop

This code:
for (i = 1; i <= 5; i++)
System.out.print(" i ");
for (j = 1; j <= i; j++)
System.out.print(" j ");
System.out.println();
Gives the following output:
i i i i i j j j j j j
I cannot understand why it gives 6 js instead of 5. Can anyone explain what I am missing?
for applies the increment every time the loop finishes. The condition is checked before beginning the next loop, so i will be 6 instead of 5 by the time your second loop starts.
Fix this by making the second condition j<i instead.
Your first loop's invariant is
i <= 5
therefore the loop will continue to iterate until that invariant no longer holds. So when you reach the second loop, you can be sure that i is not less than or equal 5; in other words, it is greater than 5.
The first loop stops when i failed the condition i <= 5, which means i=6.
So the second loop is exactly as
for (j = 1; j <= 6; j++) System.out.print(" j ");
Which print 6 j.
At the end of the "i for", i equals 6, that's why j is printed 6 times.
Use debug then you will realize this by your won. The moment first for loop exit i=6 and then your second will runs loop runs 6 times since upper limit for j is now 6. Then you get 6 js
The value of i is 6 when it finished the 1st loop. Read more about post increment operator and for loop.
i will be 6 when the j for-loop enters since the first loop would terminate at i==6 and not i==5 as you expect.

Categories