// recursive func to print a series of natural nos. upto (x-1)
import java.io.*;
public class RecFUNCseries
{
public static void main(String args[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an integer: ");
int x=Integer.parseInt(br.readLine());
series(x);
}
public static void series(int x)
{
if(x>0)
series(--x);
if(x!=0)
System.out.print(x+" ");
}
}
Showing posts with label recursive function. Show all posts
Showing posts with label recursive function. Show all posts
Friday, February 10, 2012
Wednesday, February 8, 2012
java program: Recursive function to multiply two numbers
// to multiply 2 nos. using recursive functions
import java.io.*;
class recursiveMultiplication
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number: ");
String s=br.readLine();
System.out.print("Enter another number: ");
String S=br.readLine();
int a=Integer.parseInt(s);
int b=Integer.parseInt(S);
if((a<0&&b>0)||(a>0&&b<0))
System.out.print(-Mult(Math.abs(a),Math.abs(b)));
else System.out.print(Mult(Math.abs(a),Math.abs(b)));
}
public static int Mult(int a, int b)
{
if(a==0||b==0)
return 0;
else if(b==1)
return a;
return(a+Mult(a,(b-1)));
}
}
import java.io.*;
class recursiveMultiplication
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number: ");
String s=br.readLine();
System.out.print("Enter another number: ");
String S=br.readLine();
int a=Integer.parseInt(s);
int b=Integer.parseInt(S);
if((a<0&&b>0)||(a>0&&b<0))
System.out.print(-Mult(Math.abs(a),Math.abs(b)));
else System.out.print(Mult(Math.abs(a),Math.abs(b)));
}
public static int Mult(int a, int b)
{
if(a==0||b==0)
return 0;
else if(b==1)
return a;
return(a+Mult(a,(b-1)));
}
}
java program To print a String in reverse order using recursion
// to print a string in reverse order using recursion
import java.io.*;
class reverseString
{
public static void main(String args[])throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String: ");
String s=br.readLine();
reverse(s, s.length());
}
public static void reverse(String S, int a)throws IOException
{
System.out.print(S.charAt(--a));
if(a>0)
reverse(S,a);
}
}
import java.io.*;
class reverseString
{
public static void main(String args[])throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String: ");
String s=br.readLine();
reverse(s, s.length());
}
public static void reverse(String S, int a)throws IOException
{
System.out.print(S.charAt(--a));
if(a>0)
reverse(S,a);
}
}
Subscribe to:
Posts (Atom)