0% found this document useful (0 votes)
21 views21 pages

Recursive Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views21 pages

Recursive Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

RECURSIVE PROGRAMS

Question1)
Write a program to input a number and display the new number
after reversing its digits. Use a recursive function that returns a
number after reversing the digits of the number passed as argument.

ALGORITHM
1. The program prompts the user to enter a number using the Scanner
class.
2. The program passes the user’s input to the reverse() method, which is a
recursive function that takes a number as input and returns the reversed
number.
3. The reverse() method checks if the input number has only one digit. If it
does, the method returns the number itself
4. If the input number has more than one digit, the reverse() method
calculates the last digit of the number and the remaining digits.
5. The reverse() method calls itself recursively with the remaining digits to
get the reversed remaining digits.
6. The reverse() method calculates the reversed number by multiplying the
last digit with 10 raised to the power of the number of digits in the
reversed remaining digits,
7. And added it to the reversed remaining digits.
8. The reverse() method returns the reversed number.
9. The program then displays the reversed number to the user.

CODE
import java.util.Scanner;
public class ReverseNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int reversedNum = reverse(num);
System.out.println("Reversed number: " + reversedNum);
}
public static int reverse(int num) {
if (num < 10) {
return num;
} else {
int lastDigit = num % 10;
int remainingDigits = num / 10;
int reversedRemainingDigits = reverse(remainingDigits);
int reversedNum = lastDigit * (int)Math.pow(10,
(int)Math.log10(reversedRemainingDigits) + 1) + reversedRemainingDigits;
return reversedNum;
}
}
}

OUTPUT
VARIABLE DESCRIPTION
• num: an integer variable to store the user input number
• reversedNum: an integer variable to store the reversed number
returned by the reverse function
• input: a Scanner object to read input from the user
• lastDigit: an integer variable to store the last digit of the number
passed as argument to the reverse function
• remainingDigits: an integer variable to store the remaining digits
of the number passed as argument to the reverse function
• reversedRemainingDigits: an integer variable to store the
reversed remaining digits of the number passed as argument to
the reverse function
• reversedNum: an integer variable to store the reversed number
after combining the last digit and the reversed remaining digits.

Question2)
Write a program to input a number and display the sum of its digits
by using a recursive function.
ALGORITHM
1. Define a recursive function sumOfDigits() that takes an integer
number as input.
2. Check if the number is equal to 0. If yes, return 0 (base case).
3. If the number is not equal to 0, return the sum of the last digit of
number and the result of the recursive call to sumOfDigits() with
the remaining digits of number.
4. In the main() method, accept user input for an integer number.
5. Call the sumOfDigits() method with number as an argument and
store the result in an integer variable sum.
6. Print the sum variable to display the sum of digits of number.

CODE
import java.util.Scanner;
public class SumOfDigitsRecursive {
// Recursive function to calculate the sum of digits of a number
public static int sumOfDigits(int number) {
if (number == 0) { // base case
return 0;
}
else {
return (number % 10) + sumOfDigits(number / 10); // recursive call
}
}

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
input.close();
int sum = sumOfDigits(number);
System.out.println("Sum of digits of " + number + " = " + sum);
}
}

OUTPUT

VARIABLE DESCRIPTION
• number: an integer variable that stores the user input number
• sum: an integer variable that stores the sum of digits of number
• input: a Scanner object used to accept user input
• sumOfDigits(): a recursive function that takes an integer number
as input and returns an integer (the sum of digits of number) as
output.
Question3)
Write a program to extract digits and print them in words using
recursion .

Algoritham
1. Define a recursive function printDigitsInWords that takes an integer as input.
2. Base Case: If the integer is less than 10, print the word equivalent of the
integer and return.
3. Recursive Case: If the integer is greater than or equal to 10, call the
printDigitsInWords function with the integer divided by 10 as input.
4. Print the word equivalent of the last digit of the integer by calling another
function digitToWord that takes a digit as input and returns the word equivalent
of that digit.
5. Return.

Code
public class NumberToWords {
private static final String[] digitWords = {"zero", "one", "two", "three",
"four", "five", "six", "seven", "eight", "nine"};

public static void main(String[] args) {


int number = 1234567890;
System.out.println(numberToWords(number));
}

public static String numberToWords(int number) {


if (number == 0) {
return digitWords[0];
} else {
int digit = number % 10;
String digitWord = digitWords[digit];
int remainingNumber = number / 10;
if (remainingNumber == 0) {
return digitWord;
} else {
return numberToWords(remainingNumber) + " " + digitWord;
}
}
}
}

OUTPUT

VARIABLE DESCRIPTION
Question4)
Write a program to input a String and reverse the original
String by using recursive function. Display the new String.

ALGORITHM
1. The program prompts the user to enter a String using Scanner class.
2. The program passes the user’s input to the reverse() method, which is a
recursive function that takes a String as input and returns the reversed
String.
3. The reverse() method checks if the input String is empty. If it is, the
method returns the empty String.
4. If the input String is not empty, the reverse() method calls itself with the
substring of the input string starting from the second character. This is
done recursively until the input string is empty.
5. Once the input String is empty, the reverse() method returns the
reversed String by concatenating the first character of the original
String(which is now the last character of the reversed String) to the
reversed substring.
6. The program then displays the reversed String to the user.

CODE
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String reversedStr = reverse(str);
System.out.println("Reversed string: " + reversedStr);
}
public static String reverse(String str) {
if (str.isEmpty()) {
return str;
} else {
return reverse(str.substring(1)) + str.charAt(0);
}
}
}

OUTPUT

VARIABLE DESCRIPTION
• scanner - A Scanner object used to get input from the user.
• input - A String variable that holds the user's input.
• reversed - A String variable that holds the reversed string.
• str - A String parameter for the reverseString method that holds
the string to be reversed.
GENERAL PROGRAMS

QUESTION1)
Write a program in Java to find the sum of the series after accepting
the value of ‘a’ and ‘n’ from the console:
𝑎2 𝑎4 𝑎6 𝑎𝑛
𝑆= − + −⋯+
2! 4! 6! 𝑛!

ALGORITHM
1. Declaring s, s1 and s2 of double data type and initializing them with their
initial values
2. Declaring integers a, i, j, f and n
3. Letting the user input the values for n and a that are important in
calculating the sum of the series
4. Creating the i-loop with the initial value as 2(the value increasing by 4
after every iteration), calculating the sum in that loop and then storing
the sum in s1
5. Creating another i-loop with initial value as 4(the value increasing by 4
after every iteration), calculating another sum in that loop and storing
the sum in s2
6. Calculating the difference between s1 and s2 at the end and storing it in
s
7. Printing s as that variable s is the sum of the given series

CODE
//to find the sum of the series
import java.util.*;
class Proj_GP1
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a,i,j,f,n;
double s=0.0,s1=0.0,s2=0.0;
System.out.println("Enter the value of n.");
n=in.nextInt();
System.out.println("Enter the value of a.");
a=in.nextInt();
for(i=2;i<=n;i=i+4)
{
f=1;
for(j=1;j<=i;j++)
f=f*j;
s1=s1+(double)(Math.pow(a,i)/f);
}
for(i=4;i<=n;i=i+4)
{
f=1;
for(j=1;j<=i;j++)
f=f*j;
s2=s2+(double)(Math.pow(a,i)/f);
}
s=s1-s2;
System.out.println("The sum of the series= "+s);
}
}

OUTPUT

VARIABLE DESCRIPTION
VARIABLE DATA TYPE PURPOSE
n int To enter its value which
is significant in the
series
a int To enter its value which
is significant in the
series
i int Acts as a counter in the
loop
f int Stores the factorial
j int Again acts as a counter
in a loop under the i-
loop
s1 double Stores the sum of a part
of the series
s2 double Stores the sum of the
another part of the
series
s double Stores the difference
between s1 and s2

QUESTION-2)
Wrire a program in Java to input a number from the user and
check whether it is a Magic number or not.

ALGORITHM
1. Declaring the integers a,b,c,s and n
2. Letting the user input the value of n after creating an object
3. Assigning the value of n in s
4. Creating a while loop which will keep running while the value of s is
greater than 9
5. The while loop keeps running until the it gets exhausted and the
condition becomes false,i.e., when s becomes less than 9
6. Under if condition, it is checked if the value of s is equal to 1
7. If the condition is satisfied, “Magic Number” is displayed, otherwise “Not
a Magic Number” is displayed.

CODE

//to check if a number entered by the user is Magic number or not


import java.util.*;
class Proj_GP2
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a,b,c,s,n;
System.out.println("Enter a number.");
n=in.nextInt();
s=n;
while(s>9)
{
n=s;s=0;
while(n>0)
{
a=n/10;
b=a*10;
c=n-b;
s=s+c;
n=a;
}
}
if(s==1)
System.out.println("Magic Number.");
else
System.out.println("Not a magic Number.");
}
}

OUTPUT
VARIABLE DESCRIPTION
VARIABLE DATA TYPE PURPOSE
n int Stores the number
entered by the user
s int Stores the value of n in
itself
a int Stores the value of n
except its last digit at
every iteration
b int Stores the value of
(a*10) at every iteration
c int Stores the value of n
subtracted by b at every
iteration

FILE OPERATION

QUESTION1)
Write a Java program to create a text file “Sentence.txt” to
store N number of sentences. Open the file in appropriate
mode to read each sentence from the file. Display the
number of vowels available in each word.
ALGORITHM
1. Create a new file object with the file name
"Sentence.txt".
2. Create a FileWriter object to write to the file.
3. Ask the user to input N number of sentences and
write them to the file using FileWriter.
4. Close the FileWriter object.
5. Create a FileReader object to read the file.
6. Create a BufferedReader object to read the lines
of the file.
7. Read each line of the file and split it into words
using the String.split() method.
8. Loop through each word and count the number of
vowels.
9. Print the number of vowels in each word.

CODE
import java.io.*;
public class SentenceVowels {
public static void main(String[] args) {
int numSentences = 3;
String[] sentences = {"This is the first sentence.", "Here is the second
sentence.", "Finally, the third sentence!"};
try {
PrintWriter writer = new PrintWriter("Sentence.txt", "UTF-8"); // Create
a new file for writing
for (int i = 0; i < numSentences; i++) {
writer.println(sentences[i]);
}
writer.close(); // Close the file
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new
FileReader("Sentence.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split(" ");
for (String word : words) {
int numVowels = 0;
for (int j = 0; j < word.length(); j++) {
char c = word.charAt(j);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c
== 'E' || c == 'I' || c == 'O' || c == 'U') {
numVowels++;
}
}
System.out.println("Number of vowels in '" + word + "': " +
numVowels);
}
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}

OUTPUT

VARIABLE DESCRIPTION
• file - a File object that represents the file "Sentence.txt"
• fileWriter - a FileWriter object that writes to the file
• n - an integer that represents the number of sentences to be
written to the file
• fileReader - a FileReader object that reads the file
• bufferedReader - a BufferedReader object that reads the lines of
the file
• line - a String that represents a line of text read from the file
• words - a String array that contains the words of a line
• vowels - an integer that represents the number of vowels in a
word

QUESTION-2)
Java program to rename the file

ALGORITHM
• Create a new Java class named "RenameFile".
• Inside the class, create the main method.
• Declare and initialize two File objects named "F" and "T".
• Set the path of the "F" object to the existing file that needs to be
renamed.
• Set the path of the "T" object to the new name of the file.
• Use the renameTo() method of the "F" object to rename the file to the
new name.
• Print a success message if the file is renamed successfully.
• Catch any exceptions that occur during the renaming process and print
the error message.

CODE
import java.io.File;
import java.io.IOException;

public class RenameFile {


public static void main(String[] args) {
try
// Here F is the object of the Existing file named
// with Includehelp which is to be renamed
{
File F = new File("f:/Includehelp.txt");

// Here T is the object of the renamed file


// of Includehelp which is Include.txt
File T = new File("f:/Include.txt");

// Rename the file Includehelp.txt


// into Include.txt
F.renameTo(T);

// Print the result if file renamed


System.out.println("File Rename Successfully...");
}
// If any error occurs while renaming the file
catch (Exception e) {
System.out.println(e);
}
}
}

OUTPUT
Variable Descriptions:

"F": A File object that represents the existing file to be renamed.


"T": A File object that represents the new name of the file.
"e": An Exception object that represents any exceptions that occur during
the renaming process.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy