Solve problems with Java code Algorithms with Java.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Iterations for loop. Outcome Introduction to for loop The use of for loop instead of while loop Nested for loops.
Input review If review Common Errors in Selection Statement Logical Operators switch Statements Generating Random Numbers practice.
Chapter 17 Recursion.
Computer Science Recursion Yuting Zhang Allegheny College, 04/24/06.
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Recursion Prog #include <stdio.h> #include<conio.h> main()
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Firefly Synchronisation Java Demo in 1D Array. 1 Dimension Firefly in Java two neighbors 1. Initialization: 2.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Computer Programming Lab(7).
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Recursion and Recursive Algorithms
Lecture 12 Recursion part 1
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
By Senem Kumova Metin 1 DATA TYPES. by Senem Kumova Metin 2 DATA TYPE? …… x; // DECLARATION OF VARIABLE X printf(“Do you want to go on? \n”) printf(“Please.
Types of Recursive Methods
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Building Java Programs
Computer Programming Lab 8.
And now for something completely different: recursion.
Lecture 12 Oct 13, 2008 Some simple recursive programs recursive problem solving, connection to induction Some examples involving recursion Announcements.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
18 File handling1June File handling CE : Fundamental Programming Techniques.
Csci1300 Introduction to Programming Recursion Dan Feng.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
The Power of Calling a Method from Itself Svetlin Nakov Telerik Corporation
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
M180: Data Structures & Algorithms in Java
Chapter 15 Recursion INTRODUCTION Recursion is a program-solving technique that expresses the solution of a problem in terms of the solutions of.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Recursion Chapter What is recursion? Recursion occurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive.
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems © 2004 Pearson Addison-Wesley.
Topic:- ALGORITHM Incharge Faculty – Lokesh Sir.
Recursion: The Mirrors
Java Software Structures: John Lewis & Joseph Chase
Chapter 12 Recursion (methods calling themselves)
The Power of Calling a Method from Itself
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Recursion (part 1) October 24, 2007 ComS 207: Programming I (in Java)
Unit 3 Test: Friday.
Review of Previous Lesson
Recursion.
Presentation transcript:

Solve problems with Java code Algorithms with Java

Sum 1..N – Example Calculate and print the sum of the first N positive numbers Calculate and print the sum of the first N positive numbers 2 Scanner input = new Scanner(System.in); System.out.print("n = "); int n = input.nextInt(); int num = 1; int sum = 1; System.out.print("The sum 1"); while (num < n) { num++; num++; sum += num; sum += num; System.out.printf("+%d", num); System.out.printf("+%d", num);} System.out.printf(" = %d%n", sum);

Calculating Sum 1..N Live Demo

Prime Number – Example Checking if a number is prime or not Checking if a number is prime or not 4 Scanner input = new Scanner(System.in); System.out.print("Enter a positive integer: "); int num = input.nextInt(); int divider = 2; int maxDivider = (int) Math.sqrt(num); boolean prime = true; while (prime && (divider <= maxDivider)) { if (num % divider == 0) { if (num % divider == 0) { prime = false; prime = false; } divider++; divider++;} System.out.println("Prime? " + prime);

Checking If a Number Is Prime Live Demo

Using break Operator break operator exits the inner-most loop break operator exits the inner-most loop 6 Scanner input = new Scanner(System.in); int n = input.nextInt(); // "long" is the biggest integer type long factorial = 1; // Perform an infinite loop while (true) { if (n == 1) { if (n == 1) { break; break; } factorial *= n; factorial *= n; n--; n--;} System.out.println("n! = " + factorial);

Calculating Factorial Live Demo

Factorial – Example Calculating N factorial Calculating N factorial 8 Scanner input = new Scanner(System.in); System.out.print("n = "); int n = input.nextInt(); long factorial = 1; do { factorial *= n; factorial *= n; n--; n--;} while (n > 0); System.out.println("n! = " + factorial);

Factorial (do... while) Live Demo

Recursion Calling a Method by Itself

What is Recursion? Recursion is calling a method by itselfRecursion is calling a method by itself Very powerful technique for implementing combinatorial algorithmsVery powerful technique for implementing combinatorial algorithms Recursion should haveRecursion should have Direct or indirect recursive callsDirect or indirect recursive calls The method calls itself directly or through other methodsThe method calls itself directly or through other methods Exit criteria (bottom)Exit criteria (bottom) Prevent infinite recursionPrevent infinite recursion

Factorial – Example N! (N Factorial)N! (N Factorial) N! = N * (N – 1)! for N >= 0 and 0! = 1N! = N * (N – 1)! for N >= 0 and 0! = 1 5! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 1205! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 120 4! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 244! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 24 3! = 3 * 2! or 3 * 2 * 1 * 1 = 63! = 3 * 2! or 3 * 2 * 1 * 1 = 6 2! = 2 * 1! or 2 * 1 * 1 = 22! = 2 * 1! or 2 * 1 * 1 = 2 1! = 1 * 0! or 1 * 1 = 11! = 1 * 0! or 1 * 1 = 1 0! = 10! = 1

Factorial – Example Calculating factorial:Calculating factorial: 0! = 10! = 1 n! = n* (n-1)!, n>0n! = n* (n-1)!, n>0 Don't do this at home!Don't do this at home! Use iteration insteadUse iteration instead Recursive call: the method calls itself The bottom of the recursion public static int factorial(int n) { if (n == 0) return 1; else return 1; else return n * factorial(n - 1); } return n * factorial(n - 1); }

Product[N..M] – Example Calculating the product of all numbers in the interval [n..m]: Calculating the product of all numbers in the interval [n..m]: 14 int n = input.nextInt(); int m = input.nextInt(); int num = n; long product = 1; do { product *= num; product *= num; num++; num++;} while(num <= m); System.out.println("product[n..m] = " + product);

Product of the Numbers in the Interval [n..m] Live Demo

N^M – Example Calculating n^m Calculating n^m 16 Scanner input = new Scanner(System.in); int n = input.nextInt(); int m = input.nextInt(); long result = 1; for (int i = 0; i < m; i++) { result *= n; result *= n;} System.out.println("n^m = " + result);

Calculating N^M Live Demo

Using continue Operator continue operator ends iteration of the inner-most loop continue operator ends iteration of the inner-most loop Example: Sum odd numbers p in [1, n] that are not divisors of 7: Example: Sum odd numbers p in [1, n] that are not divisors of 7: 18 int n = input.nextInt(); int sum = 0; for (int i = 1; i <= n; i += 2) { if (i % 7 == 0) if (i % 7 == 0) continue; continue; sum += i; sum += i;} System.out.println("sum = " + sum);

Using continue Operator Live Demo

Nested Loops Using Loop Inside a Loop

What Is Nested Loop? A composition of loops is called a nested loop A composition of loops is called a nested loop Example: Example: 21 for (initialization; test; update) { for (initialization; test; update) { for (initialization; test; update) { statements; statements; } …}

Nested Loops Examples

Triangle – Example Print the following triangle on the console: Print the following triangle on the console:1 1 2 … n 23 int n = input.nextInt(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); System.out.print(j + " "); } System.out.println(); System.out.println();}

Triangle Live Demo

Primes[N, M] – Example Print all prime numbers in [n, m] Print all prime numbers in [n, m] 25 int n = input.nextInt(); int m = input.nextInt(); for (int num = n; num <= m; num++) { boolean prime = true; boolean prime = true; int divider = 2; int divider = 2; int maxDivider = (int) Math.sqrt(num); int maxDivider = (int) Math.sqrt(num); while (divider <= maxDivider) { while (divider <= maxDivider) { if (num % divider == 0) { if (num % divider == 0) { prime = false; prime = false; break; break; } divider++; divider++; } if (prime) { if (prime) { System.out.printf("%d ", num); System.out.printf("%d ", num); }}

Primes in Range [n, m] Live Demo

Loops – More Examples

Nested Loops – Examples Print all four digit numbers ABCD such that A+B = C+D (happy numbers) Print all four digit numbers ABCD such that A+B = C+D (happy numbers) 28 for (int a = 1; a <= 9; a++) { for (int b = 0; b <= 9; b++) { for (int b = 0; b <= 9; b++) { for (int c = 0; c <= 9; c++) { for (int c = 0; c <= 9; c++) { for (int d = 0; d <= 9; d++) { for (int d = 0; d <= 9; d++) { if ((a + b) == (c + d)) { if ((a + b) == (c + d)) { System.out.printf("%d,%d,%d,%d", System.out.printf("%d,%d,%d,%d", a, b, c, d); a, b, c, d); }} } }} Can you improve this algorithm to use only 3 loops?

Happy Numbers Live Demo

TOTO 6/49 – Examples Print all combinations from TOTO 6/49 Print all combinations from TOTO 6/49 30 for (int i1 = 1; i1 <= 44; i1++) for (int i2 = i1 + 1; i2 <= 45; i2++) for (int i2 = i1 + 1; i2 <= 45; i2++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i6 = i5 + 1; i6 <= 49; i6++) for (int i6 = i5 + 1; i6 <= 49; i6++) System.out.printf( System.out.printf( "%d %d %d %d %d %d%n", "%d %d %d %d %d %d%n", i1, i2, i3, i4, i5, i6); i1, i2, i3, i4, i5, i6); How long will it take to finish this?

TOTO 6/49 Live Demo

Summary Loops could solve different problems Loops could solve different problems Recursion could be handy as well Recursion could be handy as well We can use nested loops to implement more complex logic We can use nested loops to implement more complex logic We can use continue and break operators to control the loop execution We can use continue and break operators to control the loop execution More to come with arrays' manipulation More to come with arrays' manipulation 32

Exercises 1.Write a program that prints all the numbers from 1 to N. 2.Write a program that prints all the numbers from 1 to N, that are not divisible by 3 and 7. 3.Write a program that reads from the console a sequence of N integer numbers and returns the minimal and maximal of them. 4.Write a program that calculates N!/K! for given N and K (1<N<K). 33

Exercises (3) 1.Write a program that reads a number N and calculates the sum of the first N members of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, … 2.In the combinatorial mathematics, the Catalan numbers are calculated by the following formula: Write a program to calculate the Catalan number by given N. 34

Exercises (4) 1. Write a program that reads from the console a positive integer number N (N < 20) and outputs a matrix like the following: N = 3N =

Exercises (5) Write a program that calculates for given N how many trailing zeros present at the end of the number N!. Examples: N = 10 N! = N = 20 N! = Does your program work for N = ? Hint: The trailing zeros in N! are equal to the number of its prime divisors 5. Think why!