I'm working on a question where I need to print the values in a reverse way using for loop in java. I have tried using the while loop and the for loop but I'm not able to print the values till required.
Please find my code below:
Lets say: y=1000, w=150, z=100;
while(y>=w) {
y-=z;
System.out.println(y);
}
i need to print the values like:
1000
900
800
700 and so on.
Kindly help as im new to Java.
public class reverse {
public static void main(String args[]){
int start=1000, end=150, decrement=100;
while(y>=w){
System.out.println(y);
y-=z;
}
System.out.println(w);
}
}
When i Run the code output is as follows:
1000
900
800
700
600
500
400
300
200
150
It is better to use 'for' loop when you have decrement or increment operation.
Use 'while' loop if you want to iterate with a condition.
int y=1000;
int z=100;
int w=150;
//loop to print values
for(int i=y;i>=w;i-=z)
{
//print
System.out.println(i);
}
Related
I have been trying to figure out why the output is 321 and not 123. I have tried multiple times and looking out lecture slides but I still can't get the solution to this question.
public static void main(String[] args) {
printNumber(1);
}
public static void printNumber(int n) {
if(n!=4) {
printNumber(n + 1);
System.out.print(n);
}
}
Each call to printNumber calls printNumber(n+1) first, and then prints something out. So printNumber(n+1) has already finished before printNumber(n) prints its number out.
main():
printNumber(1):
printNumber(2):
printNumber(3):
printNumber(4) // does nothing
print(n) // "3"
// printNumber(3) completes, returning control to printNumber(2)
print(n) // "2"
// printNumber(2) completes, returning control to printNumber(1)
print(n) // "1"
// printNumber(1) completes, returning control to main()
// main() completes
The variable n is either 1 2 or 3.
What are you printing first, n or n + 1? You are printing n + 1 first, then n. So the numbers must come out in reverse order.
The reason for this result that you have placed the recursion call statement printNumber(n + 1)
before print statement System.out.print(n) so it will keep recursivly calling it until it reach 4 after that it will print numbers from last call n+1 to n as in our example from 3 to 1
try this :
public static void printNumber(int n) {
if(n!=4) {
System.out.print(n);
printNumber(n + 1);
}
}
you will find the output: 123
The reason for that is at each recursion call it will print the number n then it will call it another time for n+1 until it reach 4.
class LargestPrimeFactor{
public static void main(String args[]){
long p=0L;
long n=600851475143L;
for(long i=2L;i<(n/2);i++){
if((BigInteger.valueOf(i)).isProbablePrime(1)){
if(n%i==0){
p=i;
}
}
}
System.out.println(p);
}
}
It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?
It is working (just add a print method inside the loop to check i for example).
You are currently using the Brute-Force method:
http://www.mathblog.dk/project-euler-problem-3/
If you visit the link the guy tells you an alternative solution for it.
The problem I see without having much knowledge about this is
that the operations you currently do are way too many.
You got the value "600851475143" stored in a long datatype and you try to
reach the half (300425737571,5) using the int i (counter in your for-loop).
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE
This tells us: "A constant holding the maximum value an int can have,
2^(31)-1." = 2147483647
This is just 0,00715 (0,7%) of what you actually need.
So this leads us to an "Overflow".
Think of using the alternative method (first link)
and change the counter of your for-loop to type "long".
int maximum value is 2147483647 which is smaller than 600851475143/2
when index i reaches max value it will wrap around and start with negative number (-2147483648)
you should make your index i a long value
You have an infinite loop on the second for iteration you can only see it when you add logging before the end of the loop. It's not because it's not printing the value, when you stare at the console the iterator is still circling through 6857.
Try running the code with extra logging below.
public static void main(String args[]) {
int p = 0;
long n = 600851475143L;
for (int i = 2; i < (n / 2); i++) {
if ((BigInteger.valueOf(i)).isProbablePrime(1)) {
if (BigInteger.valueOf(n % i).compareTo(BigInteger.valueOf(0)) == 0) {
p = i;
System.out.println("Check == true Iteration"+p);
}
System.err.println("Second iterator"+p);
}
}
System.out.println("Final Value of P: "+p);
}
EDITED
The int data type can store values upto 2,147,483,647. To store numbers beyond that, use long.
long n = 600851475143L;
Not 600851475143 L, as that one space before L causes the system to not register it.
Also, int i in the for loop should be long i.
if i store a numbers in stack , and i want to print it in queue , should i store the same numbers in queue again to print it , or there is another way to do it ?
import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Scanner ;
public class Qa {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Stack<Integer> A =new Stack<Integer>();
System.out.println(" the numbers should be less than 99 ");
int x = input.nextInt() ;
while(x> 0 && x < 99){
A.push(x);
}
PriorityQueue<String> B =new PriorityQueue<String>();
}
Queue is basically FIFO. First store the elements in a Stack. Pop the elements and store it again in another Stack. Now pop the elements you will get it as FIFO(Queue).
You can initialize a List with the contents of the stack and then print from the List? You can print from last element in List till first
i don't know what you specific want to do, but if you have the numbers stored, you don't need to re-store again. You can just reed them in from the [first-->last] or [last-->first].
An example with code is here:
CodeExample
with that you save memory and time. :)
Is suppose that you utilizes the stack structure for some reason, but the results could be the same, storing data in a simple list, and then depending in what you wanna do, uses that list. You could save space and time, because doesn't be necessary duplicate data or make unnecessary loops on complex data structures.
Hope this helps.
java.util.Stack it is an ordered Iterable like a List. you can get the elements in order of insertion by iterating over the stack with a for loop (or .forEach in Java 8).
I'm pasting the example code and output below:
public class MyApp {
public static void main(String[] args) {
Stack<Integer> myInts = new Stack<>();
for (int i = 0; i < 5; i++) {
myInts.push(i);
}
System.out.println("ITERATING:");
myInts.forEach(System.out::println);
System.out.println("\nPOPPING:");
while(!myInts.isEmpty()) {
System.out.println(myInts.pop());
}
}
}
The output is:
ITERATING:
0
1
2
3
4
POPPING:
4
3
2
1
0
You see that if you iterate over the Stack it returns the numbers in order of insertion. If your intent is just print the contents of the stack this approach has the additional benefit of not having to mutate the stack by calling pop().
Why does this program need 2 for loops to function? Is there a way to write this without the 2 for loops?
Its purpose is to assign integer values 1-25 to an array with a length of 25. It then prints the array as five separate lines each containing five array elements separated by commas.
Its output is this:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
public class ArrayNums
{
static int[] arrayList = new int[25];
public static void main(String[] args)
{
for(int i=0; i<25; i++)
arrayList[i] = i + 1;
printArray();
}
public static void printArray()
{
int i;
for(i=1; i<=25; i++){
if (i % 5 != 0)
System.out.print(arrayList[i-1]+",");
else
System.out.println(arrayList[i-1]);
}
}
}
Of course, the main function would go like this :
public static void main(String[] args)
{
for(int i=0; i<25; i++){
arrayList[i] = i + 1;
if ((i+1) % 5 != 0)
System.out.print(arrayList[i]+",");
else
System.out.println(arrayList[i]);
}
}
Though, it's considered better practice to have one function doing only one thing at a time. It makes it much easier to understand, hence your first version I would rather advice to use.
Keep it separate because this enables Separation of Concerns and better usage and maintenance of the program. As #cricket_007 stated, it's better to "have buildArray() as a separate function from printArray()".
In this scenario, the output could be achieved using a single loop and you could print i instead of the arrayList contents, but I doubt you really have a critical need to print 1 to 25 on 5 lines - assume the build and print functions would change in practice. Consider a few scenarios:
Scenario 1
Let's say the program was later required to also output to a CSV file and return a JSON object (not at the same time but by different function calls). If you're building and printing in the same loop, now you need to put the building part into three different functions.
Scenario 2
Let's say you need to change the contents of the array from numbers to letters or inputted data or the ability for the program to do any of those three. Making this change within the loop makes it harder to see potential conflicts or errors.
Scenario 3
Both Scenario 1 and Scenario 2 happen.
I think this will help you.`You could easily add the printarray() method inside the first method.
public static void main(String[] args) {
for(int i=1;i<=25;i++){
arrayList[i-1]=i;
if(i%5==0){
System.out.println(i);
}else{
System.out.print(i+",");
}
}
}
I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,