Propaganda!
Repeating a message repeatedly using recursion
/* Exercise: Propaganda! - Guided Solution Coder: ttg Date: 2/7/24 The main method is supplied; write the necessary code to get the program to work as described. Supply a copy of your output */ import java.util.Scanner; public class PropagandaDriver{ //no-touch main method public static void main(String[] args){ String defaultMsg = "Resistance is futile"; Scanner input = new Scanner(System.in); System.out.println("What is your message? ('Enter' for default)"); String msg = input.nextLine(); if(msg.length() == 0){ msg = defaultMsg; System.out.println(msg); } System.out.print("Say it how many times? "); int n = input.nextInt(); spreadPropaganda(msg, n); System.out.println(); spreadPropagandaRecursively(msg, n); System.out.println(); spreadPropagandaRecursively2(msg, n); System.out.println(); System.out.println("Welcome to Recursion!"); }//end main method public static void spreadPropaganda(String m, int n){ for(int i = 1; i <= n; i++){ System.out.println(i + ": " + m); }//end loop }//end method spreadPropaganda public static void spreadPropagandaRecursively(String m, int n){ //this is an example of 'tail recursion' because nothing happens //after the recursion call //'tail recursion' is typically the easiest to understand if(n == 0){ //the base case is a situation where the process will stop System.out.println("Base Case Reached!"); }else{ //recursion is the process whereby a method calls itself System.out.println(n + ": " + m); spreadPropagandaRecursively(m, n-1); } }//end spreadPropagandaRecursively public static void spreadPropagandaRecursively2(String m, int n){ //dwr! this is NOT tail recursion! This time, we are using 'the stack' //to keep track of stuff that has to be done if(n == 0){ //base case System.out.println("Base Case Reached!"); }else{ spreadPropagandaRecursively2(m, n-1); System.out.println(n + ": " + m); } }//end spreadPropagandaRecursively2 //Note that recursion often (if not always!) requires some sort of //parameter manipulation in order to reach 'the base case' }//end class PropagandaDriver /* ----- Sample output ------------------------------------------------------------ What is your message? ('Enter' for default) Resistance is futile Say it how many times? 5 1: Resistance is futile 2: Resistance is futile 3: Resistance is futile 4: Resistance is futile 5: Resistance is futile End of propaganda stream! 5: Resistance is futile 4: Resistance is futile 3: Resistance is futile 2: Resistance is futile 1: Resistance is futile Base Case Reached! Base Case Reached! 1: Resistance is futile 2: Resistance is futile 3: Resistance is futile 4: Resistance is futile 5: Resistance is futile Welcome to Recursion! */