Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package folder1;
- public class iUebung {
- //beginn methode
- static int func(int n) { //ohne static nicht zugreifbar, es wird eine beliebige zahl in n eingesetzt, zB 4
- if (n == 0) { //wird überprüft ob n(4) == 0 ist
- return 1; //geht weiter zu else da n(4) nicht 0 ist
- }
- else {
- return n * func(n - 1); //hier wird ausgerechnet, siehe !!! 1. unten , diese Schleife wiederholt sich bis n == 0 ist
- }
- }
- //ende
- public static void main(String[] args) {
- System.out.println(func(4)); //hier wird die methode benutzt und ausgegeben
- }
- }
- /*
- !!! 1.
- Rechnung wenn man 4 einsetzt:
- "4" * func (4-1)
- 4 * func (3)
- n ist jetzt 3
- "3" * func (3-1)
- 3 * func (2)
- n ist jetzt 2
- "2" * func (2-1)
- 2 * func (1)
- n ist jetzt 1
- "1" * func (1-1)
- 1 * func (0)
- n ist jetzt 0
- ERGEBNIS: "4" * "3" * "2" * "1" = 24
- ----------------------------------------
- Rechnung wenn man 3 einsetzt:
- "3" * func (3-1)
- 3 * func (2)
- n ist jetzt 2
- "2" * func (2-1)
- 2 * func (1)
- n ist jetzt 1
- "1" * func (1-1)
- 1 * func (0)
- n ist jetzt 0
- ERGEBNIS: "3" * "2" * "1" = 6
- ----------------------------------------
- Rechnung wenn man 2 einsetzt:
- "2" * func (2-1)
- 2 * func (1)
- n ist jetzt 1
- "1" * func (1-1)
- 1 * func (0)
- n ist jetzt 0
- ERGEBNIS: "2" * "1" = 2
- ----------------------------------------
- Rechnung wenn man 1 einsetzt:
- "1" * func (1-1)
- 1 * func (0)
- n ist jetzt 0
- ERGEBNIS: "1" = 1
- */
- ZWEITE AUFGABE:
- package folder1;
- public class iUebung2 {
- //beginn methode
- static int meh(int a) { //beliebige zahl für a einsetzen, zb 5 , wird durch static erreichbar gemacht
- int b = 0;
- while (a-- > 0) { //solange 5 grösser als 0 ist, wird sich die schleife wiederholen und je durchgang wird 5-1, auch beim ersten
- b += a; //a-- wird zu b hinzugerechnet 4,3,2,1 = 10
- System.out.println(b);
- }
- return b; //b wird zurückgegeben
- }
- //ende
- public static void main(String[] args) {
- System.out.println("Endergebnis ist " + meh(5));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement