Hi mates :)

how are you? I hope everything is all-right.. ;)

I have a small question, it is my HW to be honest

here is the question:
"Write a method that calculates the following equation:
f(x) =
1 if x = 0,1
√ f(x-1) + √ f(x-2) if x > 1
Undefined if x < 0

using Iterative statement"

Here is my attempt:

``````import java.util.*;

public class Function
{
public void calculate()
{
Scanner scan = new Scanner( System.in );
int x, x1 = 0;

while(true)
{
System.out.println("Enter an integer (or \"00\" to exit) ");
x = scan.nextInt();

if( x == 00 )
break;
else
if( x == 0 || x == 1)
{
System.out.println("f(x) = 1");
}
else
if( x < 0 )
{
System.out.println("f(x) is undefined.");
}
else
if( x > 1 )
{
x1 = x;
}
}
}
}``````

see, in the line where ( x > 1 ) I've stopped :\ didn't know what to do!!

Any hints on how to do it?

Thanks :)

I did it, can anyone tells me if it is OK or not?

``````import java.util.*;

public class Function
{
public void calculate()
{
Scanner scan = new Scanner( System.in );
double x = 0;
double x1 = 0;
double  sqrt = 0.0;
double sqrt1 = 0.0;

System.out.println("Enter an integer (or \"0.01\" to exit) ");
x = scan.nextInt();

while( x != 0.9 )
{

if( x == 0 || x == 1)
{
System.out.println("f(x) = 1");
}
else
if( x < 0 )
{
System.out.println("f(x) is undefined.");
}
else
{
x1 = x;

while( true )
{
x1 = x1 - 1;
x = x - 2;
if( x < 0 || x1 < 0 )
{
System.out.println("f(x) is undefined.");
break;
}

if( x == 1 || x == 0 )
{
sqrt = Math.sqrt(x);
}

if( x1 == 1 || x1 == 0 )
{
sqrt1 = Math.sqrt(x1);
}

if( x1 == 1 || x1 == 0 && x == 1 || x == 0)
{
sqrt = sqrt + sqrt1;
System.out.println("f(x) = " + sqrt);
break;
}

}
}

System.out.println("Enter an integer (or \"00\" to exit) ");
x = scan.nextInt();
}
}
}``````

Thanks :)

I did it, haha Thanks mates and sorry for bothering :D

this is my final code:

``````import java.util.*;

public class Function
{
public void calculate()
{
Scanner scan = new Scanner( System.in );
double x = 0;
double x1 = 0;
double  sqrt = 0.0;
double sqrt1 = 0.0;
double sum;

System.out.println("Enter an integer (or \"0.1\" to exit) ");
x = scan.nextInt();

while( x != 0.1 )
{

if( x == 0 || x == 1)
{
System.out.println("f(x) = 1");
}
else
if( x < 0 )
{
System.out.println("f(x) is undefined.");
}
else
{
x1 = x;

while( true )
{
x1 = x1 - 1;
if( x1 < 0 )
{
System.out.println("f(x) is undefined.");
break;
}

if( x1 == 1 || x1 == 0 )
{
sqrt1 = Math.sqrt(x1);
break;
}

}
while( true )
{
x = x - 2;
if( x < 0 )
{
System.out.println("f(x) is undefined.");
break;
}

if( x == 1 || x == 0 )
{
sqrt = Math.sqrt(x);
break;
}
}
sum = sqrt + sqrt1;
System.out.println("f(x) = " + sum );
}

System.out.println("Enter an integer (or \"0.1\" to exit) ");
x = scan.nextInt();
}
}
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.