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.
Related
I am learning how to do time complexity in school and the professor uploaded some examples. For the first example below, the answer is supposed to be O(n^3) but I do not understand how.
public static int fragment1 (int n)
{
int sum = 0;
for (int i = 1; i <= n*n; i++)
for (int j = 0; j*j < i; j++) sum++;
return sum;
} // end fragment1
When I attempt the problem I look at the first for loop and see that it runs n^2 times, then the inner for loop is also n^2. When added up I get O(n^4).
public static int fragment5 (int n)
{
int sum = 0;
for(int i=0; i < n*n*n; i++)
{
if(i%(n*n) == 0) {
for(int j=i*i; j > 0; j--)
sum++;
} // if
else
{
for(int k=0; k < i: k++)
sum++;
} // else
} // outer loop
}
For the problem above, the answer should be O(n^7). When I attempted it I got: first for loop runs n^3 times, inner for loop n^3*n^3 = n^6, and the for loop inside the else statement I get n with my final answer being O(n^10). Can someone give me tips on the above problem? I feel clueless when it comes to this one and I have been getting the other problems right so far.
One of the basic assumptions when calculating BigO is to drop non dominant terms.
Using the first example,
Outer Loop has order O(n^2)
Inner Loop has order O(n^3)
The inner loop independently runs for 'n' times but because it is nested, it will run for 'n * (n^2)
'
So, the BigO is of the form O((n^2) + (n^3)) which would suffice to O(n^3).
You can try using the same technique for the second problem.
If you still have some confusion, have a look at the following video:
Big O Notation
Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.
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(" ");
}
}
}
}
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.
I spend the last hour doing trial and error with this problem with no avail. We have to, using general coding guidelines (like scan.nextDouble) instead of actual numbers, find the max of a certain number of double values. The only catch is that we can only add code at a certain point. (where the ... is)
double value, valMax;
int n;
n = scan.nextInt();
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
...
}
Where the first value read in is an int and that is the amount of doubles to be entered.
It is difficult because I have to find a way to initialize valMax inside the loop without messing up anything else.
This is what I have been working with, but with nothing working for me.
for(int j = 0; j < n; j++)
{
value = scan.nextDouble();
if(j == 0)
{
valMax = scan.nextDouble();
j++;
}
else
{
continue;
}
if(value >= valMax)
{
valMax = value;
}
}
Example input:
5 -4.7 -9.2 -3.1 -8.6 -5.0
Where -3.1 is the max and 5 is the count of following numbers.
Your code seems like a good start.
To help solve your problem, consider:
Why did you put in the extra j++? Do you really need it? (Hint: no ;-) )
What will the loop do for j>0 (i.e. after the first iteration)?
That should quickly give you a working solution.
Are you allowed to set the valMax before the loop? Because in that case you can just do
valMax = Double.MIN_VALUE
and just forget about strange things by doing a normal comparison value > valMax.
If you are not your approach is how you should do but two things:
you shouldn't care about incrementing with j++ since the for loop will care about it by itself..
having a else { continue; } will make the body of the for jump to next iteration without caring about code that is after the continue. Are you sure that is what you want to do?
I think that you can initialize to Double.MIN_VALUE at first iteration (j == 0) and just behave normally afterwards: the only thing you need is that valMax is initialized before the first comparison with value, not before the scan from stdin..