Skip to main content

Posts

Showing posts from January, 2023

Recursion Class 2 | Recursion in One Shot | 9 Best Problems

Recursion Class 2 :- Recursion is a powerful programming technique that is used in many algorithms and data structures. In Java, recursion is implemented using methods that call themselves. Tower of Hanoi: The Tower of Hanoi is a mathematical puzzle that consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. Q1. Tower of Hanoi - Transfer n disks from source to destination over 3 towers. public class Recursion2 { public static void towerOfHanoi(int n, String src, String helper, String dest) { if(n == 1) { System.out.println("transfer disk " + n + " from " + src + " to " + dest); return; } //transfer top n-1 from src to helper using dest as 'helper' towerOfHanoi(n-1, src, dest, helper); //transfer nth from src to dest Sy...

Recursion in One Shot | Theory + Question Practice + Code | Level 1 - Easy

JAVA Recursion Class 1 (Codes) Q1. Print numbers from 5 to 1. public static void printNumbers(int n) { if(n == 0) { return; } System.out.println(n); printNumbers(n-1); } Q2. Print numbers from 1 to 5. public static void printNumbers(int n) { if(n == 6) { return; } System.out.println(n); printNumbers(n+1); } Q3. Print the sum of first n natural numbers. class Recursion1 { public static void printSum(int n, int sum) { if(n == 0) { System.out.println(sum); return; } sum += n; printSum(n-1, sum); } public static void main(String args[]) { printSum(5, 0); } } Q4. Print factorial of a number n. class Recursion1 { public static void printFactorial(int n, int fact) { if(n == 0) { System.out.println(fact); return; } fact *= n; printFactorial(n-1, fact); } public static void main(String args[]) { printFactorial(5, 1); } } Q5. Print the fibonacci sequence till nth term. class Recursion1 { public static void printFactorial(int a, int b, int n) { if(n == 0) { return; } System.out.println(a); printF...

Bit Manipulation |Get Bit | Set Bit | Update Bit | Lecture 14

Java - Introduction to Programming Lecture 14 Bit Manipulation Get Bit import java . util .*;   public class Bits {     public static void main ( String args []) {        int n = 5 ; //0101        int pos = 3 ;        int bitMask = 1 << pos ;          if (( bitMask & n ) == 0 ) {            System . out . println ( "bit was zero" );       } else {            System . out . println ( "bit was one" );       }    } }   Set Bit import java . util .*;   public class Bits {     public static void main ( String args []) {        int n = 5 ; //0101        int p...