How many natural numbers less than 300 are neither multiples of 2 or multiples of 3
You need to do these exercises by yourself. Please don't ask me for solutions! Show
Getting Started ExercisesHelloWorld
CheckPassFail (if-else)Write a program called HintsUse public class CheckPassFail { public static void main(String[] args) { int mark = 49; System.out.println("The mark is " + mark); if ( ...... ) { System.out.println( ...... ); } else { System.out.println( ...... ); } System.out.println( ...... ); } } Try Take note of the source-code indentation!!! Whenever you open a block with CheckOddEven (if-else)Write a program called Hints
public class CheckOddEven { public static void main(String[] args) { int number = 49; System.out.println("The number is " + number); if ( ...... ) { System.out.println( ...... ); } else { System.out.println( ...... ); } System.out.println( ...... ); } } Try Again, take note of the source-code identation! Make it a good habit to ident your code properly, for ease of reading your program. PrintNumberInWord (nested-if, switch-case)Write a program called Hintspublic class PrintNumberInWord { public static void main(String[] args) { int number = 5; if (number == 1) { System.out.println( ...... ); } else if ( ...... ) { ...... } else if ( ...... ) { ...... ...... ...... } else { ...... } switch(number) { case 1: System.out.println( ...... ); break; case 2: System.out.println( ...... ); break; ...... ...... default: System.out.println( ...... ); } } } Try PrintDayInWord (nested-if, switch-case)Write a program called Try Exercises on Number Systems (for Science/Engineering Students)To be proficient in programming, you need to be able to operate on these number systems:
Read "Number Systems" section of "Data Representation", and complete the exercises. Writing Good ProgramsThe only way to learn programming is program, program and program. Learning programming is like learning cycling, swimming or any other sports. You can't learn by watching or reading books. Start to program immediately. On the other hands, to improve your programming, you need to read many books and study how the masters program. It is easy to write programs that work. It is much harder to write programs that not only work but also easy to maintain and understood by others – I call these good programs. In the real world, writing program is not meaningful. You have to write good programs, so that others can understand and maintain your programs. Pay particular attention to:
Exercises on Decision and LoopSumAverageRunningInt (Decision & Loop)Write a program called The sum of 1 to 100 is 5050 The average is 50.5 Hintspublic class SumAverageRunningInt { public static void main (String[] args) { int sum = 0; double average; final int LOWERBOUND = 1; final int UPPERBOUND = 100; for (int number = LOWERBOUND; number <= UPPERBOUND; ++number) { sum += number; } ...... ...... } } Try
Product1ToN (or Factorial) (Decision & Loop)Write a program called HintsDeclare an int product = 1; final int LOWERBOUND = 1; final int UPPERBOUND = 10; Try
HarmonicSum (Decision & Loop)Write a program called Hintspublic class HarmonicSum { public static void main (String[] args) { final int MAX_DENOMINATOR = 50000; double sumL2R = 0.0; double sumR2L = 0.0; double absDiff; for (int denominator = 1; denominator <= MAX_DENOMINATOR; ++denominator) { ...... } System.out.println("The sum from left-to-right is: " + sumL2R); ...... if (sumL2R > sumR2L) ...... else ...... } } ComputePI (Decision & Loop)Write a program called HintsAdd to double sum = 0.0; int MAX_DENOMINATOR = 1000; for (int denominator = 1; denominator <= MAX_DENOMINATOR; denominator += 2) { if (denominator % 4 == 1) { sum += ......; } else if (denominator % 4 == 3) { sum -= ......; } else { System.out.println("Impossible!!!"); } } ...... Try
CozaLozaWoza (Decision & Loop)Write a program called 1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22 23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza ...... Hintspublic class CozaLozaWoza { public static void main(String[] args) { final int LOWERBOUND = 1, UPPERBOUND = 110; for (int number = LOWERBOUND; number <= UPPERBOUND; ++number) { if ( ...... ) { System.out.print("Coza"); } if ( ...... ) { System.out.print(.....); } ...... if ( ...... ) { ...... } if ( ...... ) { System.out.println(); } else { System.out.print( ...... ); } } } } Notes
Fibonacci (Decision & Loop)Write a program called The first 20 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 885.5 Hintspublic class Fibonacci { public static void main (String[] args) { int n = 3; int fn; int fnMinus1 = 1; int fnMinus2 = 1; int nMax = 20; int sum = fnMinus1 + fnMinus2; double average; System.out.println("The first " + nMax + " Fibonacci numbers are:"); ...... while (n <= nMax) { ...... ++n; fnMinus2 = fnMinus1; fnMinus1 = fn; } ...... } } Try
ExtractDigits (Decision & Loop)Write a program called HintsThe coding pattern for extracting individual digits from an
integer
Take note that int n = ...; while (n > 0) { int digit = n % 10; ...... n = n / 10; } Exercises on Input, Decision and LoopAdd2Integer (Input)Write a program called Enter first integer: 8 Enter second integer: 9 The sum is: 17 Hintsimport java.util.Scanner; public class Add2Integers { public static void main (String[] args) { int number1, number2, sum; Scanner in = new Scanner(System.in); System.out.print("Enter first integer: "); number1 = in.nextInt(); ...... in.close(); sum = ...... System.out.println("The sum is: " + sum); } } SumProductMinMax3 (Arithmetic & Min/Max)Write a program called Enter 1st integer: 8 Enter 2nd integer: 2 Enter 3rd integer: 9 The sum is: 19 The product is: 144 The min is: 2 The max is: 9 Hintsint number1, number2, number3; int sum, product, min, max; Scanner in = new Scanner(System.in); ...... ...... in.close(); sum = ...... product = ...... min = number1; if (number2 < min) { min = number2; } if (number3 < min) { min = number3; } ...... ...... Try
CircleComputation (double & printf())Write a program called diameter = 2.0 * radius; area = Math.PI * radius * radius; circumference = 2.0 * Math.PI * radius; Hintsdouble radius, diameter, circumference, area; ...... System.out.print("Enter the radius: "); radius = in.nextDouble(); ...... System.out.printf("Diameter is: %.2f%n", diameter); ...... Try
Swap2IntegersWrite a program called Enter first integer: 9 Enter second integer: -9 After the swap, first integer is: -9, second integer is: 9 HintsTo swap the contents of two variables IncomeTaxCalculator (Decision)The progressive income tax rate is mandated as follows:
For example, suppose that the taxable income is Write a program called Enter the taxable income: $41234 The income tax payable is: $2246.80 Enter the taxable income: $67891 Hintsfinal double TAX_RATE_ABOVE_20K = 0.1; final double TAX_RATE_ABOVE_40K = 0.2; final double TAX_RATE_ABOVE_60K = 0.3; int taxableIncome; double taxPayable; ...... if (taxableIncome <= 20000) { taxPayable = ......; } else if (taxableIncome <= 40000) { taxPayable = ......; } else if (taxableIncome <= 60000) { taxPayable = ......; } else { taxPayable = ......; } System.out.printf("The income tax payable is: $%.2f%n", ...); TrySuppose that a IncomeTaxCalculatorWithSentinel (Decision & Loop)Based on the previous exercise, write a program called Enter the taxable income (or -1 to end): $41000 The income tax payable is: $2200.00 Enter the taxable income (or -1 to end): $62000 The income tax payable is: $6600.00 Enter the taxable income (or -1 to end): $73123 The income tax payable is: $9936.90 Enter the taxable income (or -1 to end): $84328 The income tax payable is: $13298.40 Enter the taxable income: $-1 bye! The HintsThe coding pattern for handling input with sentinel value is as follows: final int SENTINEL = -1; ...... int taxableIncome; double taxPayable; ...... System.out.print("Enter the taxable income (or -1 to end): $"); taxableIncome = in.nextInt(); while (taxableIncome != SENTINEL) { ...... ...... System.out.print("Enter the taxable income (or -1 to end): $"); taxableIncome = in.nextInt(); } System.out.println("bye!"); Take note that we repeat the input statements inside and outside the loop. Repeating statements is NOT a good programming practice. This is because it is easy to repeat (Cntl-C/Cntl-V), but hard to maintain and synchronize the repeated statements. In this case, we have no better choices! PensionContributionCalculator (Decision)Both the employer and the employee are mandated to contribute a certain percentage of the employee's salary towards the employee's pension fund. The rate is tabulated as follows:
However, the contribution is subjected to a salary ceiling of Write a program called Enter the monthly salary: $3000 Enter the age: 30 The employee's contribution is: $600.00 The employer's contribution is: $510.00 The total contribution is: $1110.00 Hintsfinal int SALARY_CEILING = 6000; final double EMPLOYEE_RATE_55_AND_BELOW = 0.2; final double EMPLOYER_RATE_55_AND_BELOW = 0.17; final double EMPLOYEE_RATE_55_TO_60 = 0.13; final double EMPLOYER_RATE_55_TO_60 = 0.13; final double EMPLOYEE_RATE_60_TO_65 = 0.075; final double EMPLOYER_RATE_60_TO_65 = 0.09; final double EMPLOYEE_RATE_65_ABOVE = 0.05; final double EMPLOYER_RATE_65_ABOVE = 0.075; int salary, age; int contributableSalary; double employeeContribution, employerContribution, totalContribution; ...... contributableSalary = ...... if (age <= 55) { ...... } else if (age <= 60) { ...... } else if (age <= 65) { ...... } else { ...... } PensionContributionCalculatorWithSentinel (Decision & Loop)Based on the previous Enter the monthly salary (or -1 to end): $5123 Enter the age: 21 The employee's contribution is: $1024.60 The employer's contribution is: $870.91 The total contribution is: $1895.51 Enter the monthly salary (or -1 to end): $5123 Enter the age: 64 The employee's contribution is: $384.22 The employer's contribution is: $461.07 The total contribution is: $845.30 Enter the monthly salary (or -1 to end): $-1 bye! HintsSystem.out.print("Enter the monthly salary (or -1 to end): $"); salary = in.nextInt(); while (salary != SENTINEL) { System.out.print("Enter the age: "); age = in.nextInt(); ...... ...... System.out.print("Enter the monthly salary (or -1 to end): $"); salary = in.nextInt(); } SalesTaxCalculator (Decision & Loop)A sales tax of Write a program using a loop to continuously input the tax-inclusive price (in Enter the tax-inclusive price in dollars (or -1 to end): 107 Actual Price is: $100.00, Sales Tax is: $7.00 Enter the tax-inclusive price in dollars (or -1 to end): 214 Actual Price is: $200.00, Sales Tax is: $14.00 Enter the tax-inclusive price in dollars (or -1 to end): 321 Actual Price is: $300.00, Sales Tax is: $21.00 Enter the tax-inclusive price in dollars (or -1 to end): -1 Total Price is: $642.00 Total Actual Price is: $600.00 Total Sales Tax is: $42.00 Hintsfinal double SALES_TAX_RATE = 0.07; final int SENTINEL = -1; double price, actualPrice, salesTax; double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; ...... System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): "); price = in.nextDouble(); while (price != SENTINEL) { ...... ...... ...... System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): "); price = in.nextDouble(); } ...... ReverseInt (Loop with Modulus/Divide)Write a program that prompts user for a positive integer. The program shall read the input as Enter a positive integer: 12345 The reverse is: 54321 HintsUse the following coding pattern which uses a while-loop with repeated modulus/divide operations to extract and drop the last digit of a positive integer. int inNumber; int inDigit; ...... while (inNumber > 0) { inDigit = inNumber % 10; ...... inNumber /= 10; } ...... SumOfDigitsInt (Loop with Modulus/Divide)Write a program that prompts user for a positive integer. The program shall read the input as Enter a positive integer: 12345 The sum of all digits is: 15 HintsSee " InputValidation (Loop with boolean flag)Your program often needs to validate the user's inputs, e.g., marks shall be between 0 and 100. Write a program that prompts user for an integer between Enter a number between 0-10 or 90-100: -1 Invalid input, try again... Enter a number between 0-10 or 90-100: 50 Invalid input, try again... Enter a number between 0-10 or 90-100: 101 Invalid input, try again... Enter a number between 0-10 or 90-100: 95 You have entered: 95 HintsUse the following coding pattern which uses a do-while loop controlled by a int numberIn; boolean isValid; ...... isValid = false; // default assuming input is not valid do { ...... if (numberIn ......) { isValid = true; } else { System.out.println(......); } } while (!isValid); ...... AverageWithInputValidation (Loop with boolean flag)Write
a program that prompts user for the mark (between Enter the mark (0-100) for student 1: 56 Enter the mark (0-100) for student 2: 101 Invalid input, try again... Enter the mark (0-100) for student 2: -1 Invalid input, try again... Enter the mark (0-100) for student 2: 99 Enter the mark (0-100) for student 3: 45 The average is: 66.67 Hintsfinal int NUM_STUDENTS = 3; int numberIn; boolean isValid; int sum = 0; double average; ...... for (int studentNo = 1; studentNo <= NUM_STUDENTS; ++studentNo) { ...... isValid = false; do { ...... } while (!isValid); sum += ......; } ...... Exercises on Nested-LoopsSquarePattern (nested-loop)Write a program called Enter the size: 5 # # # # # # # # # # # # # # # # # # # # # # # # # HintsThe code pattern for printing 2D patterns using nested loops is: for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { System.out.print( ...... ); ...... } System.out.println(); } Notes
TryRewrite the above program using nested while-do loops. CheckerPattern (nested-loop)Write a program called Enter the size: 7 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Hintsfor (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { if ((row % 2) == 0) { ...... } System.out.print( ...... ); ...... } System.out.println(); } TimeTable (nested-loop)Write a program called Enter the size: 10 * | 1 2 3 4 5 6 7 8 9 10 -------------------------------------------- 1 | 1 2 3 4 5 6 7 8 9 10 2 | 2 4 6 8 10 12 14 16 18 20 3 | 3 6 9 12 15 18 21 24 27 30 4 | 4 8 12 16 20 24 28 32 36 40 5 | 5 10 15 20 25 30 35 40 45 50 6 | 6 12 18 24 30 36 42 48 54 60 7 | 7 14 21 28 35 42 49 56 63 70 8 | 8 16 24 32 40 48 56 64 72 80 9 | 9 18 27 36 45 54 63 72 81 90 10 | 10 20 30 40 50 60 70 80 90 100 Hints
TriangularPattern (nested-loop)Write 4 programs called Enter the size: 8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (a) (b) (c) (d) Hints
BoxPattern (nested-loop)Write 4 programs called Enter the size: 8 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (a) (b) (c) (d) (e) Hints
HillPattern (nested-loop)Write 3 programs called Enter the rows: 6 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (a) (b) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (c) (d) Hints
NumberPattern (nested-loop)Write 4
programs called Enter the size: 8 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1 1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1 1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1 1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1 1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1 1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1 (a) (b) (c) (d) Hints[TODO] Debugging/Tracing Programs using a Graphic DebuggerFactorial (Using a graphic debugger)The following program computes and prints the factorial of Use the graphic debugger of Eclipse/NetBeans to debug the program by single-step through the program and tabulating the values of You should try out debugging features such as "Breakpoint", "Step Over", "Watch variables", "Run-to-Line", "Resume", "Terminate", among others. (Read "Eclipse for Java" or "NetBeans for Java" for details). public class Factorial { public static void main(String[] args) { int n = 20; int factorial = 1; for (int i = 1; i <= n; i++) { factorial = factorial * i; } System.out.println("The Factorial of " + n + " is " + factorial); } } Exercises on String and char OperationsReverseString (String & char)Write a
program called Enter a String: abcdef The reverse of the String "abcdef" is "fedcba". HintsFor a String inStr; int inStrLen; ...... System.out.print("Enter a String: "); inStr = in.next(); inStrLen = inStr.length(); for (int charIdx = inStrLen - 1; charIdx >= 0; --charIdx) { ...... } CountVowelsDigits (String & char)Write a program called Enter a String: testing12345 Number of vowels: 2 (16.67%) Number of digits: 5 (41.67%) Hints
PhoneKeyPad (String & char)On your phone keypad, the alphabets are mapped to digits as follows: Hints
Caesar's Code (String & char)Caesar's Code is one of the simplest encryption techniques. Each letter in the plaintext is replaced by a letter some fixed number of position ( Write a program called Enter a plaintext string: Testing The ciphertext string is: WHVWLQJ Hints
Decipher Caesar's Code (String & char)Write a program called Enter a ciphertext string: wHVwLQJ The plaintext string is: TESTING Exchange Cipher (String & char)This simple cipher exchanges Write a program called Enter a plaintext string: abcXYZ The ciphertext string is: ZYXCBA Hints
TestPalindromicWord and TestPalindromicPhrase (String & char)A word that reads
the same backward as forward is called a palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a program called A phrase that reads the same backward as forward is also called a palindrome, e.g., "Madam, I'm Adam", "A man, a plan, a canal - Panama!" (ignoring punctuation and capitalization). Modify your program (called Hints
CheckBinStr (String & char)The binary number system uses 2 symbols, 0 and 1. Write a program called
Enter a binary string: 10101100 "10101100" is a binary string Enter a binary string: 10120000 "10120000" is NOT a binary string HintsUse the following coding pattern which involves a String inStr; int inStrLen; char inChar; boolean isValid; ...... isValid = true; for (......) { inChar = ......; if (!(inChar == '0' || inChar == '1')) { isValid = false; break; } } if (isValid) { System.out.println(......); } else { System.out.println(......); } //System.out.println(isValid ? ... : ...); CheckHexStr (String & char)The hexadecimal (hex) number system uses 16 symbols, Enter a hex string: 123aBc "123aBc" is a hex string Enter a hex string: 123aBcx "123aBcx" is NOT a hex string Hintsif (!((inChar >= '0' && inChar <= '9') || (inChar >= 'A' && inChar <= 'F') || (inChar >= 'a' && inChar <= 'f'))) { ...... } Bin2Dec (String & char)Write a program called Enter a Binary string: 1011 The equivalent decimal number for binary "1011" is: 11 Enter a Binary string: 1234 error: invalid binary string "1234" HintsSee "Code Example". Hex2Dec (String & char)Write
a program called Enter a Hexadecimal string: 1a The equivalent decimal number for hexadecimal "1a" is: 26 Enter a Hexadecimal string: 1y3 error: invalid hexadecimal string "1y3" HintsSee "Code Example". Oct2Dec (String & char)Write a program called Enter an Octal string: 147 The equivalent decimal number "147" is: 103 RadixN2Dec (String & char)Write a program called Enter the radix: 16 Enter the string: 1a The equivalent decimal number "1a" is: 26 Exercises on ArrayPrintArray (Array)Write a program called Enter the number of items: 5 Enter the value of all items (separated by space): 3 2 5 6 9 The values are: [3, 2, 5, 6, 9] Hintstinal int NUM_ITEMS; int[] items; ...... ...... NUM_ITEMS = ...... items = new int[NUM_ITEMS]; if (items.length > 0) { ...... for (int i = 0; i < items.length; ++i) { ...... } } ...... for (int i = 0; i < items.length; ++i) { if (i == 0) { ...... } else { ...... } //System.out.print((i == 0) ? ...... : ......); } PrintArrayInStars (Array)Write a program called Enter the number of items: 5 Enter the value of all items (separated by space): 7 4 3 0 7 0: *******(7) 1: ****(4) 2: ***(3) 3: (0) 4: *******(7) Hintsfinal int NUM_ITEMS; int[] items; ...... ...... for (int idx = 0; idx < items.length; ++idx) { System.out.print(idx + ": "); for (int starNo = 1; starNo <= items[idx]; ++starNo) { System.out.print("*"); } ...... } ...... GradesStatistics (Array)Write a program which prompts user for the number of students in a class (a non-negative integer), and saves it in an Enter the number of students: 5 Enter the grade for student 1: 98 Enter the grade for student 2: 78 Enter the grade for student 3: 78 Enter the grade for student 4: 87 Enter the grade for student 5: 76 The average is: 83.40 The minimum is: 76 The maximum is: 98 Hex2Bin (Array for Table Lookup)Write a program called Enter a Hexadecimal string: 1abc The equivalent binary for hexadecimal "1abc" is: 0001 1010 1011 1100 Hints
Dec2Hex (Array for Table Lookup)Write a program called Enter a decimal number: 1234 The equivalent hexadecimal number is 4D2 HintsSee "Code Example". Exercises on Methodexponent() (method)Write a method called public static int exponent(int base, int exp); Assume that Also write the Enter the base: 3 Enter the exponent: 4 3 raises to the power of 4 is: 81 Hints...... public class Exponent { public static void main(String[] args) { int exp; int base; ...... ...... System.out.println(base + " raises to the power of " + exp + " is: " + exponent(base, exp)); } public static int exponent(int base, int exp) { int product = 1; for (......) { product *= base; } return product; } } isOdd() (method)Write a public static boolean isOdd(int number); Also write the Enter a number: 9 9 is an odd number Enter a number: 8 8 is an even number Enter a number: -5 -5 is an odd number HintsSee Notes. hasEight() (method)Write a public static boolean hasEight(int number); Write a program called Enter a positive integer (or -1 to end): 1 Enter a positive integer (or -1 to end): 2 Enter a positive integer (or -1 to end): 3 Enter a positive integer (or -1 to end): 8 Enter a positive integer (or -1 to end): 88 Enter a positive integer (or -1 to end): -1 The magic sum is: 96 Hints
print() (Array & Method)Write a method called public static void print(int[] array); Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array). How to handle public static void print(double[] array) public static void print(float[] array) The above is known as method overloading, where the same method name can have many versions, differentiated by its parameter list. Hints
arrayToString() (Array & Method)Write a method called public static String arrayToString(int[] array); Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array). Notes: This is similar to the built-in function contains() (Array & Method)Write a public static boolean contains(int[] array, int key); Also write a test driver to test this method. search() (Array & Method)Write a method called public static int search(int[] array, int key); Also write a test driver to test this method. equals() (Array & Method)Write a public static boolean equals(int[] array1, int[] array2) Also write a test driver to test this method. copyOf() (Array & Method)Write a public static int[] copyOf(int[] array) Also write a test driver to test this method. Write another version for public static int[] copyOf(int[] array, int newLength) NOTES:
This is similar to the built-in function swap() (Array & Method)Write a method called public static boolean swap(int[] array1, int[] array2) Also write a test driver to test this method. HintsYou need to use a temporary location to swap two storage locations. int item1, item2, temp; temp = item1; item1 = item2; item2 = item1; reverse() (Array & Method)Write a method called public static void reverse(int[] array) Take note that the array passed into the method can be modified by the method (this is called "pass by reference"). On the other hand, primitives passed into a method cannot be modified. This is because a clone is created and passed into the method instead of the original copy (this is called "pass by value"). Also write a test driver to test this method. Hints
GradesStatistics (Array & Method)Write a program called Enter the number of students: 4 Enter the grade for student 1: 50 Enter the grade for student 2: 51 Enter the grade for student 3: 56 Enter the grade for student 4: 53 The grades are: [50, 51, 56, 53] The average is: 52.50 The median is: 52.00 The minimum is: 50 The maximum is: 56 The standard deviation is: 2.29 The formula for calculating standard deviation is: Hints: public class GradesStatistics { public static int[] grades; public static void main(String[] args) { readGrades(); System.out.println("The grades are: "); print(grades); System.out.println("The average is " + average(grades)); System.out.println("The median is " + median(grades)); System.out.println("The minimum is " + min(grades)); System.out.println("The maximum is " + max(grades)); System.out.println("The standard deviation is " + stdDev(grades)); } public static void readGrades() { ....... } public static void print(int[] array) { ....... } public static double average(int[] array) { ...... } public static double median(int[] array) { ...... } public static int max(int[] array) { int max = array[0]; ...... } public static int min(int[] array) { ....... } public static double stdDev(int[] array) { ....... } } Take note that besides GradesHistogram (Array & Method)Write a program called 0 - 9: *** 10 - 19: *** 20 - 29: 30 - 39: 40 - 49: * 50 - 59: ***** 60 - 69: 70 - 79: 80 - 89: * 90 -100: ** * * * * * * * * * * * * * * * 0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100 HintsSee "Code Example". Exercises on Command-line ArgumentsArithmetic (Command-Line Arguments)Write a program called java Arithmetic 3 2 + 3+2=5 java Arithmetic 3 2 - 3-2=1 java Arithmetic 3 2 / 3/2=1 HintsThe method java Arithmetic 12345 4567 + The three command-line arguments args is: {"12345", "4567", "+"} args.length is: 3 args[0] is: "12345" args[1] is: "4567" args[2] is: "+" args[0].length() is: 5 args[1].length() is: 4 args[2].length() is: 1 public class Arithmetic { public static void main (String[] args) { int operand1, operand2; char theOperator; if (args.length != 3) { System.err.println("Usage: java Arithmetic int1 int2 op"); return; } operand1 = Integer.parseInt(args[0]); operand2 = ...... theOperator = args[2].charAt(0); System.out.print(args[0] + args[2] + args[1] + "="); switch(theOperator) { case ('-'): System.out.println(operand1 - operand2); break; case ('+'): ...... case ('*'): ...... case ('/'): ...... default: System.err.println("Error: invalid operator!"); } } } Notes:
Question: Try " In Windows' CMD shell, SumDigits (Command-line Arguments)Write a program called java SumDigits 12345 The sum of digits = 1 + 2 + 3 + 4 + 5 = 15 More (Difficult) ExercisesJDK Source CodeExtract the source code of the class Also study the " Matrices (2D Arrays)Similar to Hintspublic class Matrix { public static void print(int[][] m); public static void print(double[][] m); public static boolean haveSameDimension(int[][] m1, int[][] m2); public static boolean haveSameDimension(double[][] m1, double[][] m2); public static int[][] add(int[][] m1, int[][] m2); public static double[][] add(double[][] m1, double[][] m2); public static int[][] subtract(int[][] m1, int[][] m2); public static double[][] subtract(double[][] m1, double[][] m2); public static int[][] multiply(int[][] m1, int[][] m2); public static double[][] multiply(double[][] m1, double[][] m2); ...... } PrintAnimalPattern (Special Characters and Escape Sequences)Write a program called '__' (©©) /========\/ / || %% || * ||----|| ¥¥ ¥¥ "" "" Hints
Try
Print Patterns (nested-loop)Write a method to print each of the followings patterns using nested loops in a class called public static void printPatternX(int size); # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # (a) (b) # # # # # # # # # # # # # # # # # # # # # # # # # (c) 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1 1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1 1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1 1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1 1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1 1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1 (d) (e) (f) (g) 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 (h) (i) 1 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 2 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 3 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 5 5 4 3 2 1 1 2 3 4 4 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 3 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 2 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 1 (j) (k) 1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5 6 7 8 9 0 1 0 9 8 7 6 7 8 9 0 1 2 3 2 1 0 9 8 7 8 9 0 1 2 3 4 5 4 3 2 1 0 9 8 (l) Print Triangles (nested-loop)Write a method to print each of the following patterns using nested-loops in a class called public static void printXxx(int numRows); 1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1 1 2 4 8 16 32 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 (a) PowerOf2Triangle 1 1 1 1 1 1 1 2 1 1 2 1 1 3 3 1 1 3 3 1 1 4 6 4 1 1 4 6 4 1 1 5 10 10 5 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 6 15 20 15 6 1 (b) PascalTriangle1 (c) PascalTriangle2 Trigonometric SeriesWrite a method to compute public static double sin(double x, int numTerms); public static double cos(double x, int numTerms); Compare the values computed using the series with the JDK methods HintsDo not use Exponential SeriesWrite a method to compute public static double exp(int numTerms); public static double exp(double x, int numTerms); Special SeriesWrite a method to compute the sum of the series in a class called public static double specialSeries(double x, int numTerms); FactorialInt (Handling Overflow)Write a program called The factorial of 1 is 1 The factorial of 2 is 2 ... The factorial of 12 is 479001600 The factorial of 13 is out of range HintsThe maximum and minimum values of a 32-bit System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE + 1); Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently wraps the
number around. Hence, you cannot use TryModify your program called FibonacciInt (Handling Overflow)Write a program called F(0) = 1 F(1) = 1 F(2) = 2 ... F(45) = 1836311903 F(46) is out of the range of int HintsThe maximum and minimum values of a 32-bit System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE + 1); Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently wraps the number around. Hence, you cannot use TryWrite a similar program called Number System ConversionWrite a method call public static String toRadix(String in, int inRadix, int outRadix) Write a program called Enter a number and radix: A1B2 Enter the input radix: 16 Enter the output radix: 2 "A1B2" in radix 16 is "1010000110110010" in radix 2. NumberGuessWrite a program called java NumberGuess Key in your guess: 50 Try higher 70 Try lower 65 Try lower 61 You got it in 4 trials! HintsUse final int SECRET_NUMBER = (int)(Math.random()*100); WordGuessWrite a program called java WordGuess testing Key in one character or your guess word: t Trial 1: t__t___ Key in one character or your guess word: g Trial 2: t__t__g Key in one character or your guess word: e Trial 3: te_t__g Key in one character or your guess word: testing Congratulation! You got in 4 trials Hints
TryTry retrieving the word to be guessed from a text file (or a dictionary) randomly. DateUtilComplete the following methods in a class called
HintsTo find the day of the week (Reference: Wiki "Determination of the day of the week"):
For example: 2012, Feb, 17 (6 + 12 + 12/4 + 2 + 17) % 7 = 5 (Fri) The skeleton of the program is as follows: public class DateUtil { public static String[] strMonths = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; public static int[] daysInMonths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public static boolean isLeapYear(int year) { ...... } public static boolean isValidDate(int year, int month, int day) { ...... } public static int getDayOfWeek(int year, int month, int day) { ...... } public static String printDate(int year, int month, int day) { ...... } public static void main(String[] args) { System.out.println(isLeapYear(1900)); System.out.println(isLeapYear(2000)); System.out.println(isLeapYear(2011)); System.out.println(isLeapYear(2012)); System.out.println(isValidDate(2012, 2, 29)); System.out.println(isValidDate(2011, 2, 29)); System.out.println(isValidDate(2099, 12, 31)); System.out.println(isValidDate(2099, 12, 32)); System.out.println(getDayOfWeek(1982, 4, 24)); System.out.println(getDayOfWeek(2000, 1, 1)); System.out.println(getDayOfWeek(2054, 6, 19)); System.out.println(getDayOfWeek(2012, 2, 17)); System.out.println(toString(2012, 2, 14)); } } NotesYou can compare the day obtained with the Java's Calendar cal = new GregorianCalendar(year, month - 1, day); int dayNumber = cal.get(Calendar.DAY_OF_WEEK); String[] calendarDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; System.out.println("It is " + calendarDays[dayNumber - 1]); The calendar we used today is known as Gregorian calendar, which came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400. Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st. This above algorithm work for Gregorian dates only. It is difficult to modify the above algorithm to handle pre-Gregorian dates. A better algorithm is to find the number of days from a known date. Exercises on RecursionIn programming, a recursive function (or method) calls itself. The classical example is factorial(n) = 1, for n = 0 factorial(n) = n * factorial(n-1), for all n > 1 For example, suppose factorial(5) = 5 * factorial(4) factorial(4) = 4 * factorial(3) factorial(3) = 3 * factorial(2) factorial(2) = 2 * factorial(1) factorial(1) = 1 * factorial(0) factorial(0) = 1 factorial(1) = 1 * 1 = 1 factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120 (DONE) Factorial RecusiveWrite a recursive method called public static int factorial(int n) The recursive algorithm is: factorial(n) = 1, if n = 0 factorial(n) = n * factorial(n-1), if n > 0 Compare your code with the iterative
version of the factorial(n) = 1*2*3*...*n HintsWriting recursive function is straight forward. You simply translate the recursive definition into code with public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n-1); } r // return (n == 0) ? 1 : n*factorial(n-1); } Notes
Fibonacci (Recursive)Write a recursive method to compute the Fibonacci number of n, defined as follows: F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) for n >= 2 Compare the recursive version with the iterative version written earlier. Hintspublic static int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci(n-1) + fibonacci(n-2); } } Length of a Running Number Sequence (Recursive)A special number sequence is defined as follows: S(1) = 1 S(2) = 12 S(3) = 123 S(4) = 1234 ...... S(9) = 123456789 S(10) = 12345678910 S(11) = 1234567891011 S(12) = 123456789101112 ...... Write a recursive method to compute the length of len(1) = 1 len(n) = len(n-1) + numOfDigits(n) Also write an iterative version. GCD (Recursive)Write a recursive
method called public static void int gcd(int a, int b) gcd(a,b) = a, if b = 0 gcd(a,b) = gcd(b, remainder(a,b)), if b > 0 Tower of Hanoi (Recursive)A classical recursive problem [TODO] Exercises on Algorithms - Sorting and SearchingEfficient sorting and searching are big topics, typically covered in a course called "Data Structures and Algorithms". There are many searching and sorting algorithms available, with their respective strengths and weaknesses. See Wikipedia "Sorting Algorithms" and "Searching Algorithms" for the algorithms, examples and illustrations. JDK provides searching and sorting utilities in the Linear SearchWrite the following linear search methods to search
for a public static boolean linearSearch(int[] array, int key) public static int linearSearchIndex(int[] array, int key) Also write a test driver to test the methods. Recursive Binary Search(Reference: Wikipedia "Binary Search") Binary search is only applicable to a sorted list. For example, suppose that we want to search for the item Create two indexes: firstIdx and lastIdx , initially pointing at the first and last elements [11 14 16 18 20 25 28 30 34 40 45] F M L Compute middleIdx = (firstIdx + lastIdx) / 2 Compare the key (K) with the middle element (M) If K = M, return true else if K < M, set firstIdx = middleIndex else if K > M, set firstIdx = middleIndex {11 14 16 18 20 25 28 30 34 40 45} F M L Recursively repeat the search between the new firstIndex and lastIndex. Terminate with not found when firstIndex = lastIndex. {11 14 16 18 20 25 28 30 34 40 45} F M L Write a recursive
function called public boolean binarySearch(int[] array, int key, int fromIdx, int toIdx) Use the following pseudocode implementation: If fromIdx = toIdx - 1 if key = array[fromIdx], return true else, return false (not found) else middleIdx = (fromIdx + toIdx) / 2 if key = array[middleIdx], return true else if key < array[middleIdx], toIdx = middleIdx else firstIdx = middleIdx + 1 binarySearch(array, key, fromIdx, toIdx) Also write an overloaded method which uses the above to search the entire array: public boolean binarySearch(int[] array, int key) Write a test driver to test the methods. Bubble Sort(Reference: Wikipedia "Bubble Sort") The principle of bubble sort is to scan the elements from left-to-right, and whenever two adjacent elements are out-of-order, they are swapped. Repeat the passes until no swap are needed. For
example, given the list Pass 1: 9 2 4 1 5 -> 2 9 4 1 5 2 9 4 1 5 -> 2 4 9 1 5 2 4 9 1 5 -> 2 4 1 9 5 2 4 1 9 5 -> 2 4 1 5 9 (After Pass 1, the largest item sorted on the right - bubble to the right) Pass 2: 2 4 1 5 9 -> 2 4 1 5 9 2 4 1 5 9 -> 2 1 4 5 9 2 1 4 5 9 -> 2 1 4 5 9 2 1 4 5 9 -> 2 1 4 5 9 (After Pass 2, the 2 largest items sorted on the right) Pass 3: 2 1 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 (After Pass 3, the 3 largest items sorted on the right) Pass 4: 1 2 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 1 2 4 5 9 -> 1 2 4 5 9 (After Pass 4, the 4 largest items sorted on the right) No Swap in Pass 4. Done. See Wikipedia "Bubble Sort" for more examples and illustration. Write a method to sort an public static void bubbleSort(int[] array) Use the following pesudocode implementation: function bubbleSort(array) n = length(array) boolean swapped do { swapped = false for (i = 1; i < n; ++i) { if array[i-1] > array[i] { swap( A[i-1], A[i] ) swapped = true } } n = n - 1 } while (swapped) Selection Sort(Reference: Wikipedia "Selection Sort") This algorithm divides the lists into two parts: the left-sublist of items already sorted, and the right-sublist for the remaining items. Initially, the left-sorted-sublist is empty, while the right-unsorted-sublist is the entire list. The algorithm proceeds by finding the smallest (or largest) items from the right-unsorted-sublist, swapping it with the leftmost element of the right-unsorted-sublist, and increase the left-sorted-sublist by one. For example, given the list {} {9 6 4 1 5} -> {} {1 6 4 9 5} {1} {6 4 9 5} -> {1} {4 6 9 5} {1 4} {6 9 5} -> {1 4} {5 9 6} {1 4 5} {9 6} -> {1 4 5} {6 9} {1 4 5 6} {9} -> DONE {1 4 5 6 9} Write a method to sort an public static void selectionSort(int[] array) Insertion Sort(Reference: Wikipedia "Insertion Sort") Similar to the selection sort, but extract the leftmost element from the right-unsorted-sublist, and insert into the correct location of the left-sorted-sublist. For example, given {} {9 6 4 1 5 2 7} -> {9} {6 4 1 5 2 7} {9} {6 4 1 5 2 7} -> {6 9} {4 1 5 2 7} {6 9} {4 1 5 2 7} -> {4 6 9} {1 5 2 7} {4 6 9} {1 5 2 7} -> {1 4 6 9} {5 2 7} {1 4 6 9} {5 2 7} -> {1 4 5 6 9} {2 7} {1 4 5 6 9} {2 7} -> {1 2 4 5 6 9} {7} {1 2 4 5 6 9} {7} -> {1 2 4 5 6 7 9} {} {1 2 4 5 6 7 9} {} -> Done Write a method to sort an public static void insertionSort(int[] array) Recursive Quick Sort(Reference: Wikipedia "Quick Sort") Quicksort is a recursive divide and conquer algorithm. It divides the list into two sublists - the low elements and the high element, and recursively sort the sublists. The steps are:
For example,
given Select the middle element as the pivot, place the pivot at the end of the list, by swapping with the last element {20 11 18 14 15 9 32 5 26} -> {20 11 18 14 26 9 32 5} {15} Partitioning: Initialize a variable swapPos (underlined), initially pointing to the leftmost element. Compare each element (in red) with the pivot, if the element is smaller than the pivot, swap with the element at the swapPos and increase swapPos by 1. otherwise, do nothing. {20 11 18 14 26 9 32 5} {15} -> larger, do nothing {20 11 18 14 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 20 18 14 26 9 32 5} {15} {11 20 18 14 26 9 32 5} {15} -> larger, do nothing {11 20 18 14 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 18 20 26 9 32 5} {15} {11 14 18 20 26 9 32 5} {15} -> larger, do nothing {11 14 18 20 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 9 20 26 18 32 5} {15} {11 14 9 20 26 18 32 5} {15} -> larger, do nothing {11 14 9 20 26 18 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 9 5 26 18 32 20} {15} Partitioning done. Swap the pivot. {11 14 9 5 15 18 32 20 26} All elements before the pivot are smaller; all elements after the pivot are larger. Pivot is sorted in the correct position. Recursively repeat the process for sublists {11 14 9 5} and {18 32 20 26} Write a recursive function called public boolean quickSort(int[] array, int fromIdx, int toIdx) public boolean quickSort(int[] array) HintsSee Binary Search. Merge Sort(Reference: Wikipedia "Merge Sort") [TODO] Heap Sort(Reference: Wikipedia "Heap Sort") [TODO] Exercises on Algorithms - Number TheoryPerfect and Deficient NumbersA positive integer is called a perfect number if the sum of all its factors
(excluding the number itself, i.e., proper divisor) is equal to its value. For example, the number A positive integer is called a deficient number if the sum of all its proper divisors is less than its value. For example, Write a public static boolean isPerfect(int aPosInt); public static boolean isDeficient(int aPosInt); Using the methods, write a program called Enter the upper bound: 1000 These numbers are perfect: 6 28 496 [3 perfect numbers found (0.30%)] These numbers are neither deficient nor perfect: 12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 ...... [246 numbers found (24.60%)] Prime NumbersA positive integer is a prime if it is divisible by Please enter the upper bound: 10000 1 2 3 ...... ...... 9967 9973 [1230 primes found (12.30%)] HintsTo check if a number Prime FactorsWrite a Write a program called Enter the upper bound: 100 These numbers are equal to the product of prime factors: 1 6 10 14 15 21 22 26 30 33 34 35 38 39 42 46 51 55 57 58 62 65 66 69 70 74 77 78 82 85 86 87 91 93 94 95 [36 numbers found (36.00%)] Greatest Common Divisor (GCD)One of the earlier known algorithms is the Euclid algorithm to find the GCD of two integers (developed by the Greek Mathematician Euclid around 300BC). By definition,
GCD(a, 0) = a GCD(a, b) = GCD(b, a mod b), where (a mod b) denotes the remainder of a divides by b. For example, GCD(15, 5) = GCD(5, 0) = 5 GCD(99,88) = GCD(88,11) = GCD(11,0) = 11 GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9 The pseudocode for the Euclid algorithm is as follows: GCD(a, b) while (b != 0) { temp ← b b ← a mod b a ← temp } GCD is a Write a method called public static int gcd(int a, int b) Your methods shall handle arbitrary values of TryWrite a
recursive version called Final NotesThe only way to learn programming is program, program and program on challenging problems. The problems in this tutorial are certainly NOT challenging. There are tens of thousands of challenging problems available – used in training for various programming contests (such as International Collegiate Programming Contest (ICPC), International Olympiad in Informatics (IOI)). Check out these sites:
What numbers are not multiples of 2 or 3?5,7,11,17,23,29,31……… These are only a few which are not a multiple of 2 & 3. Any prime number or number that is a multiple of any other two prime numbers, including squares of prime numbers, that are not 2 or 3.
What number is both a multiple of 2 and 3?What are some common multiples of 2 and 3? The multiples of 2 are 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, … The multiples of 3 are 3, 6, 9, 12, 15, 18, 21, …. Hence, some of the common multiples of 2 and 3 are 6, 12, 18, etc.
Which number is not multiple of 3?But the numbers 16, 22, 28, and 31 are not the multiples of 3 as they leave some remainder value.
How many natural numbers less than 300 are there which are neither divisible by 5 9 by 7?Therefore, there are 292 natural numbers less than 300 that are divisible neither by 5 nor by 7.
|