Java Recursion, how is it printing when it should be done? - recursion

Ok so I have a recursive code from my instructor. I understand how the stack functions (first in last out, last in first out, etc). What I don't get is how the instructor was able to print the popping off of the stack without telling the computer to do so. For example, how does this code displaying the popping without the a command to do so?
Here is the code:
public class Recursion{
public static void main(String [] args){
printParam(1);
}
public static void printParam(int i) {
System.out.println("i = " + i);
if(i < 10) {
printParam(i + 1);
}
System.out.println("i = " + i);
}
}
Looking at the code it looks like it should top at ten, end the program, and trash the stack.

printParam(1);
printParam(); <- invokes itself again
2nd Sys out is "skipped" for this session but added to the stack // but it is still invoked above, just "held"
Once the first forced recursive sys outs (the first sys out) is executed, it still "remembers"
that it has 10 "hit me in the faces" to print. showWhatHappens

Related

Recursive function in java?

public class Main {
public static void main(String[] args) {
printDollars(7);
}
public static void printDollars(int n) {
if (n > 1) {
printDollars(n - 1);
}
for (int i = 0; i < n; i++) {
System.out.print("$");
}
}
}
How does the value of n get incremented after printDollars() function gets executed.
The value of n is actually decreased by one on every iteration.
When 7 enters the function for the first time, the logic checks whether the value is more than 1. Since 7 > 1, the value (7-1)=6 enters the next level of the recursive function. It happens several times (6 to 5, 5 to 4, etc), until the function reaches one.
One important thing to note, if you're just starting with recursion is that the dollar signs start to be printed when the code got to the point where n =1, since to reach that part of code, the machine has to get over all of the recursive calls. So the first '$' printed is actually one that comes from the call with n=1, then n=2, etc.
I suggest you try printing out n instead of '$', so that you get a clearer understanding of the way it works.

Getting positive integer using recursion

I'm confused i'm suppose to get a positive int from user using recursion, the user can input words, and also numbers.(Words and negative numbers are invalid), Not sure what i'm doing wrong.
I'm sorry forgot to ask the question, well i'm getting compiler error, when I try to compile it, something is wrong with my Scanner, I was reading an it says I have to use an argument for the users input, I'm not sure how to, and the second question was, how do I let the code to repeat if the user inputs n<0 or a word, such as taxes. thank you
import java.util.*;
public class Recursion {
private static int getPositiveInt(Scanner keyboard) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a positive interger, n");
int n = keyboard.nextInt();
if (n > 0) {
return n;
}
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
}
}
If I understood your question correctly, you want this function to run untill it will read a valid number.
To do this all you need to change is:
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
to:
else {
//call the function again
return getPositiveInt(Scanner keyboard)
}

Making smaller lower-higher console game

So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.

How does fork and pipe work in a unix process system?

I'm trying to study for an exam and I'm just not able to figure out a simple fork program.
I have this piece of code and have to add code to it In order for the parent process to send through a PIPE the value n to the child. The child should double the value, not print anything and return it to the parent.
Then the parent should print it on the screen.
int main() {
int n=1;
if(fork() == 0) {
}
printf(ā€œ%d\nā€, n);
return 1;
}
I don't really know how PIPEs work and how to use them. Can anyone help me?
pid_t cp;
int fi[2],st;
int n;
if(pipe(fi)==-1) {perror("pipe error");exit(0);}
if((cp=fork())==-1) {perror("fork"); exit(0);}
else if(cp==0)
{
sleep(2);
close(fi[1]);
read(fi[0],&n,2);
n*=2;
close(fi[0]);
exit(n);
}
else
{
close(fi[0]);
write(fi[1],n,2);
close(fi[1]);
waitpid(cp,&st,0);
printf("%d",st);
exit(0);
}}
The working of pipes is very simple. A PIPE contains two ends, 1 for reading and another for writing. You have to close the appropriate end while reading or writing. After that you use it as a regular file with read() and write() functions. Forgive me for my formatting, I'm typing on a mobile.

Scintilla (QScintilla) 3rd marker define fails

In my class I attempt to define 3 markers, one for errors, one for warnings, and one for breakpoints. This worked well when I was only attempting to define 2 markers, but for some reason the third of these markers doesn't appear when added to a line. If you switch the ordering of the definitions, it is always the third one that fails to appear when markerAdd() is called. The pixmaps are valid, and Scintilla's return values appear to be correct for both defining and adding markers. This is more of a general Scintilla question rather than a QScintilla question I believe, because QScintilla simply does some checks before calling the underlying scintilla code. I have no idea where to even begin in debugging this code. If anyone can shed some light on this, whether it is a known scintilla quirk or it is my fault, I would be eternally grateful.
m_errorIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_red.png"));
m_breakIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_black.png"));
m_warningIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_yellow.png"));
void SourceFile::on_actionAddBreakpoint_triggered()
{
qWarning() << "Added breakpoint to " << m_currentLine;
qWarning() << ui_editor->markerAdd(m_currentLine, m_breakIndicator);
m_breakpoints.append(m_currentLine);
}
void SourceFile::on_actionRemoveBreakpoint_triggered()
{
ui_editor->markerDelete(m_currentLine, m_breakIndicator);
m_breakpoints.removeAll(m_currentLine);
}
void SourceFile::clearProblems()
{
ui_editor->markerDeleteAll(m_errorIndicator);
ui_editor->markerDeleteAll(m_warningIndicator);
}
void SourceFile::markProblems(const QStringList& errors, const QStringList& warnings)
{
foreach(const QString& error, errors) {
int line = error.section(":", 1, 1).toInt();
if(--line < 0) continue;
ui_editor->markerAdd(line, m_errorIndicator);
}
foreach(const QString& warning, warnings) {
int line = warning.section(":", 1, 1).toInt();
if(--line < 0) continue;
ui_editor->markerAdd(line, m_warningIndicator);
}
}
There should be a yellow bullet next to the printf statement. If the warning and breakpoint definitions are switched, the yellow bullet will show up and the black bullet will disappear.
Aha! After days of looking, I finally found the problem.
ui_editor->setMarginMarkerMask(1, m_breakpointMarker);
Was being called in a setup method, which was causing funky behavior. Removing this fixed everything.

Resources