[Go to site: main page, start]

0% found this document useful (0 votes)
8 views3 pages

Java Methods: Loops & Logic Exercises

The document outlines a Java worksheet with exercises focused on methods, loops, and logical operators. It includes tasks for calculating sums, checking for prime numbers, printing multiplication tables, calculating factorials, checking for palindromes, and counting vowels in strings, each with hints and example usages. The exercises emphasize using loops and logical operators to solve problems effectively.

Uploaded by

haressh02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Java Methods: Loops & Logic Exercises

The document outlines a Java worksheet with exercises focused on methods, loops, and logical operators. It includes tasks for calculating sums, checking for prime numbers, printing multiplication tables, calculating factorials, checking for palindromes, and counting vowels in strings, each with hints and example usages. The exercises emphasize using loops and logical operators to solve problems effectively.

Uploaded by

haressh02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Methods Worksheet: Loops and Logical

Operators
Exercise 1: Sum of Numbers
Task:
Write a method named sumUpTo that takes a single integer parameter n and returns the sum of all
numbers from 1 to n (inclusive). Use a loop (either a for loop or a while loop) to compute the
sum.

Hints:

 Validate that n is positive; if n is less than 1, you may return 0.


 Use a loop to iterate through numbers from 1 to n.

Example Usage:

public static void main(String[] args) {


[Link]("Sum of numbers up to 5: " + sumUpTo(5));

// Expected output: 15
}

Exercise 2: Check for Prime Number


Task:
Create a method called isPrime that takes an integer parameter num and returns a boolean
indicating whether num is a prime number. A prime number is a number greater than 1 that has
no positive divisors other than 1 and itself.

Hints:

 Use a loop to check divisibility from 2 up to the square root of num (or up to num - 1 for
simplicity).
 Use logical operators to combine conditions (e.g., if (num < 2)).

Example Usage:

public static void main(String[] args) {


[Link]("Is 7 prime? " + isPrime(7)); // Expected output: true
[Link]("Is 8 prime? " + isPrime(8)); // Expected output: false
}
Exercise 3: Multiplication Table
Task:
Write a method named printMultiplicationTable that accepts an integer n and prints the
multiplication table for that number from 1 to 10.

Hints:

 Use a loop (e.g., a for loop) to iterate from 1 to 10.


 Use formatted printing to display the result neatly.

Example Usage:

public static void main(String[] args) {


printMultiplicationTable(3);
}
/* Expected output:
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30
*/

Exercise 4: Factorial Calculation


Task:
Create a method called factorial that calculates and returns the factorial of a non-negative
integer n. The factorial of n (written as n!) is the product of all positive integers less than or
equal to n. (By definition, 0! = 1.)

Hints:

 Use a loop to multiply numbers from 1 to n.


 Handle the special case when n is 0.

Example Usage:

public static void main(String[] args) {


[Link]("Factorial of 5: " + factorial(5)); // Expected output:
120
}
Exercise 5: Palindrome Checker
Task:
Develop a method named isPalindrome that takes a String as a parameter and returns true if
the string is a palindrome (reads the same forward and backward) and false otherwise. Ignore
case differences when comparing characters.

Hints:

 Use a loop to compare characters from the beginning and the end of the string.
 Use logical operators to continue checking until the middle of the string is reached.
 Consider using the toLowerCase() method for case-insensitive comparison.

Example Usage:

public static void main(String[] args) {


[Link]("Is 'Racecar' a palindrome? " +
isPalindrome("Racecar")); // Expected: true
[Link]("Is 'Java' a palindrome? " + isPalindrome("Java"));
// Expected: false
}

Exercise 6: Counting Vowels in a String


Task:
Write a method named countVowels that takes a String as input and returns the number of
vowels (a, e, i, o, u) present in the string. Treat uppercase and lowercase vowels as equivalent.

Hints:

 Use a loop to iterate over each character of the string.


 Use charAt(i) inside a loop to retrieve each character from the string so you can
compare it with vowels.
 Use a conditional statement with logical operators to check if a character is a vowel.

Example Usage:

public static void main(String[] args) {


[Link]("Number of vowels in 'Hello World': " +
countVowels("Hello World")); // Expected: 3
}

Common questions

Powered by AI

The 'isPalindrome' method converts the input string to lowercase to ensure case-insensitive comparison. It utilizes a loop to compare characters from the start and the end of the string, converging towards the center. If any pair of characters does not match, it returns false, indicating the string is not a palindrome. The method uses logical operators to continue these checks until it reaches the middle of the string, confirming all characters mirror around the center .

The 'printMultiplicationTable' method uses a loop to iterate from 1 to 10. For each iteration, it calculates the product of the given integer 'n' and the loop index, representing the multiplication operation for that step. Formatted printing is used to display each result neatly, following the format 'n x i = result' for values of 'i' from 1 to 10 .

The method 'sumUpTo' validates that the input integer 'n' is positive by checking if 'n' is less than 1. If 'n' is less than 1, the method returns 0, ensuring no calculations are performed on invalid input. For positive integers, it uses a loop to iterate from 1 to 'n', accumulating the sum of all numbers in that range .

The 'factorial' method must handle two main considerations: the special case of 0! which equals 1, and the potential for large numbers resulting from factorial operations. The method first checks if 'n' is 0 and returns 1 immediately. For other numbers, it uses a loop to multiply numbers from 1 to 'n', effectively calculating the factorial while maintaining computational efficiency. The method leverages the inherent iterative nature of loops to ensure accurate multiplication of the sequence of integers .

The 'countVowels' method processes the string using a loop that iterates over each character, retrieving characters with 'charAt(i)'. It converts each character to lowercase to simplify vowel checks. Using conditional statements with logical operators, it checks if each character is one of the vowels (a, e, i, o, u), incrementing a counter when it finds a match, thus accurately counting all vowels in the string regardless of casing .

The 'isPalindrome' method, as described, does not inherently handle spaces or punctuation, as it only addresses case insensitivity through toLowerCase conversion. Without additional logic to ignore non-alphanumeric characters, the method may inaccurately determine the palindrome status of phrases or sentences containing spaces or punctuation. This limitation means modifications are necessary for comprehensive palindrome checks in strings containing such characters, potentially affecting accuracy if not addressed .

The method 'isPrime' uses a logical approach by first checking if 'num' is less than 2, as numbers less than 2 are not prime. It then uses a loop to check divisibility of 'num' from 2 up to the square root of 'num' (a more efficient approach) or up to 'num - 1'. If 'num' is divisible by any of these numbers, it is not prime. This use of logical operators ensures a thorough and efficient primality test .

Formatted printing in the 'printMultiplicationTable' method is achieved by systematically organizing each line of output to follow a clear structure ('n x i = result'). By using controlled spacing and alignment, each line of the multiplication table is consistently presented, which enhances readability and ensures the output is user-friendly. This approach utilizes string formatting capabilities to manage alignment and spacing without manual adjustments .

Checking from 2 up to the square root of a number in the 'isPrime' method leverages mathematical properties that if a number is composite, it must have a divisor less than or equal to its square root. This significantly reduces the number of checks needed compared to iterating through all numbers up to 'num - 1'. Thus, this approach decreases complexity from O(n) to O(√n), improving performance especially for larger numbers by minimizing unnecessary computations .

Using a loop for calculating factorials has several advantages over recursion, including reduced risk of stack overflow and often better performance due to less overhead from function calls. Loops handle iterations iteratively in sequence rather than relying on the call stack, making them more efficient for large values of 'n'. Loops also generally provide easier debugging and readability, especially for iterative calculations like those needed in factorial computation .

You might also like