Today, I have taken an exam, and there was a question:
Write a method which prints integer numbers in the ascending order recursively from 1 to n:
public class PrintIntegersAscendingOrder {
static int counter = 0;
public static void PrintIntegersAscendingOrder (int n)
{
if (n == 1)
{
System.out.printf("%d\n", ++counter);
}
else
{
System.out.printf("%d ", ++counter);
PrintIntegersAscendingOrder(n-1);
}
}
public static void main (String args[])
{
PrintIntegersAscendingOrder(5);
}
}
Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?
You can do it like this:
public class IntegerAscendingOrder {
public static void main(String[] args) throws Exception {
printIntegersAscendingOrder(n);
}
private static void printIntegersAscendingOrder(int i) {
if (i < 1) {
return;
}
printIntegersAscendingOrder(i-1);
System.out.println(i);
}
}
You don't need the counter variable in the class, using recursion you can limit the method call within the method itself.
Notice the if (i < 1) {return;} line, this will terminate the recursive method call(s).
This article should help you Getting started with recursion
Do it as follows:
public class Main {
public static void printIntegersAscendingOrder(int n) {
if (n == 0) {
return;
}
printIntegersAscendingOrder(n - 1);
System.out.printf("%d ", n);
}
public static void main(String args[]) {
printIntegersAscendingOrder(5);
}
}
Output:
1 2 3 4 5
As #RobOhRob has already pointed out, the counter defeats the purpose of recursion in your code. When you are calling a function recursively, you need to analyse three important things:
When to stop the recursive call
Processing before making the recursive call
Processing before making the recursive call
Since you are already decreasing the parameter by 1 and passing it to the method to call it recursively, you can simply make use of this parameter instead of creating an additional variable (e.g. counter).
In your code you have defined in your class a method PrintIntegersAscendingOrder having the same name of the class PrintIntegersAscendingOrder containing it. This is an error that can be avoided for example renaming the including class to PrintIntegers. Below the code of class without the error and with the recursive method:
public class PrintIntegers {
public static void PrintIntegersAscendingOrder(int n) {
if (n > 0) {
PrintIntegersAscendingOrder(n - 1);
System.out.printf("%d\n", n);
}
}
public static void main (String args[]) {
PrintIntegersAscendingOrder(5);
}
}
Related
I want to implement this program but it throws errors on every function call and runs an infinite loop.
class abc
{
public static void main(String[] args) {
int n=16;
calll(n);
}
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
n=n+5;
calll(n);
return n;
}
}
}
There is no end condition to your function.
Whether n is greater than 5 or not you run the calll function, which then runs the calll function again to infinite.
You need a conditon that will end the recursion, for instance changing the call function to this:
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
return n;
}
}
However the function is still rather pointless as you don't actually do anything with n. Keep in mind that the n that you define in the main function is never modified.
I want to write a program that keeps track of how many times a bus is late.
So the user is asked to enter an int value, indicating how many minutes late.
Once a negative int is entered, the program should stop.
What I’m having trouble with is making the program repeat only for inputs of 0 or more.
The program repeats regardless of what int is inputted.
I did something like below:
import java.util.Scanner;
public class LateBus {
public static void main(String[] args) {
int enter_minutes = enterMinutes();
loop(enter_minutes);
}
public static int enterMinutes() {
Scanner enter = new Scanner(System.in);
System.out.print("How many minutes late was the bus? ");
int late = enter.nextInt();
return late;
}
public static void loop(int a) {
while (a >= 0) {
enterMinutes();
}
}
}
Let's look at this function:
public static void loop(int a) {
while (a >= 0) {
enterMinutes();
}
}
The value of a never changes. a >= 0 will always be true or never be true depending on the initial value for a. Since a is used internally to this function, you should not pass it in as a parameter. And you should be sure to change it:
public static void loop() {
int a = enterMinutes();
while (a >= 0) {
a = enterMinutes();
}
}
Now you call the function like this:
public static void main(String[] args) {
loop();
}
Note:
Everyone makes logic mistakes in their code as they write it. To find them, you need to learn how to debug. I suggest that you read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for some tips on how to debug your code so that you can find these kinds of problems on your own.
The while loop will stop when a is negative, but you do not change its value.
Do it like this
while (a >= 0) {
a = enterMinutes();
}
now the value changes to what the user inputs.
public class Interpolation_search {
public static void main(String...s) {
int rr[]= {1,2,3,4,9,10,15,80};
System.out.println(search(rr,0,7,3));
}
static int search(int ar[], int lo, int hi,int X) {
if(lo<hi&&ar[lo]!=ar[hi]) {
int mid=lo + ((hi-lo)/(ar[hi]-ar[lo]))*(X-ar[lo]);
if(X==ar[mid])
return 1; //l1
else if(X>ar[mid])
search(ar,mid+1,hi,X);
else search(ar,lo,mid-1,X);
}
return 0; //l2
}
}
return is executing twice first at l1 and second at l2.
It seems that you have difficulties understanding recursion.
Your method search() is supposed to return an int result. And the method itself calls itself (using different arguments) repeatedly. Thing is: you are all ignoring these recursive calls.
In other words: the real answer is for you to step back and understand what recursion is meant to be, and how to properly use it. As a starter, you could try to change
search(ar,mid+1,hi,X);
to
return search(ar,mid+1,hi,X);
So let's say I have a main class with a while loop:
public class Main {
public static void main(String[] args) throws InterruptedException {
int one = 1;
int counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
Function.Move();
one++;
}
The counter variable in this loop is counting each second elapsed.
There is a separate class called Function:
public class Function {
public static int Move (int result){
result = 1 + counter;
return result;
}
}
So as you can see, inside the Function class's Move method, I want to be able to use the counter variable's new value, which increases with each passing second, to calculate the value of a different variable which will then be returned to the main method.
The problem is that I can't figure out how to pass the value of counter to the Move method inside the Function class to begin with.
I'm not shure if i understand what you want to do correctly, depending on where exactly you will need that result variable later i think your coude should look something like this:
public class Main {
int counter;
public static void main(String[] args) throws InterruptedException {
int one = 1;
counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
one++;
}
}
public int getCounter() {
return counter;
}
}
public class Function {
public static int move (int result, Main main){
result = 1 + main.getCounter();
return result;
}
}
You can use Function.move() anywhere you need it's value in your Programm now.
Beware, though, that you will need your code using the Function.move() to run in a different Thread as the Main Thread. Otherwise it will always return 101 or 1, as the while loop will always be running before or after your call to Function.move(), depending on where you call it (except if you call it from within the while loop, but then you counld just use counter++ without the need to have an extra class)
I am a new learner of Java. I learned some of the Java core concepts. I got the identifier expected error when run my following code:
class Sekar {
public static int i,j,k;
i = 900;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
When I compile my code, I get the following error:
error: identifier expected
i = 900;
^
Can any one explain why this error happens here?
When I google about identifier expected error, I found that this error happens when variables are declared without datatype, but I declared that for all my variables i,j,k.
When I redeclare the data type again while setting value to "i" like int i = 900 it works. Why does it?
i = 900;
This is a statement in Java, it can be inside Constructor or method, or initialization block.
In your case, you may move that inside the max() method
When I re declare the data type again while setting value to "i" like
int i = 900 it works. Why does it?
Here, you are declaring and assigning the value to the variable in the same time, same line.
Check here for more details and here about java statements, expressions
Statements
Statements are roughly equivalent to sentences in natural languages. A
statement forms a complete unit of execution. The following types of
expressions can be made into a statement by terminating the expression
with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
Hava a look at Java: Identifier expected :
i = 900;
is a statement as any other. You can't write statement anywhere. It must be in methods/constructors body. Initializing variable in declaration is called definition and is exception to this rule.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
If you want to initialize static variable you can do it 2 (sane) ways:
Initialize variable right where you are declaring it:
class Sekar {
public static int i = 900, j,k;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
or do it in static constructor:
class Sekar {
public static int i, j,k;
static {
i = 900;
}
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
Also, if you want to define a constant I recommend using final keyword.
j could be converted to local variable.
class Sekar {
public static final int I = 900;
static void max()
{
int k;
int j = 100;
if(I>j)
{
k=I;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+I+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
What you probably want to do is this:
class Sekar {
public static int i=900,j=100,k;
static void max()
{
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
However I would discourage you from using static fields in this case. I would suggest you to make i, j and k parameters to your method. And give them descriptive names while you're at it.
Also note that k is not initialised explicitly and is therefore set to 0 by default, so your else clause is never reached.