Define a class to overload the method format as follows: void format() - To print the following pattern using Nested for loops only: 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5 int format(String s) - To calculate and return the sum of ASCII codes of each character of the String. Example: CAB Output: 67 + 65 + 66 = 198 void format(int n) - To calculate and display the sum of natural numbers up to n given by the formula n(n + 1) / 2.
Topic: Method overloading — three versions of format()
Answer
class FormatOverload { void format() { for(int i = 1; i <= 5; i++) { for(int j = i; j <= 5; j++) System.out.print(j + " "); System.out.println(); } }
int format(String s) { int sum = 0; for(int i = 0; i < s.length(); i++) sum = sum + (int)s.charAt(i); return sum; }
void format(int n) { int sum = n * (n + 1) / 2; System.out.println("Sum of natural numbers up to " + n + " = " + sum); }
public static void main(String args[]) { FormatOverload ob = new FormatOverload(); ob.format(); System.out.println("ASCII sum = " + ob.format("CAB")); ob.format(10); } }
Three methods share the name format() and are told apart by their parameter lists — no parameter, a String, an int. That is method overloading.
The pattern: each row starts one higher than the row before and always ends at 5, so the inner loop starts at i rather than at 1 — for(int j = i; j <= 5; j++). That one substitution produces the whole shrinking triangle. Whenever a pattern loses its first element each row, look for an inner loop starting at the outer variable.
The ASCII sum: charAt(i) gives each character, and the cast (int) converts it to its code. The cast is optional, since char is promoted automatically in arithmetic, but writing it makes your intention clear. CAB gives 67 + 65 + 66 = 198, matching the example.
The natural-number sum uses the formula directly rather than a loop. Note that n * (n + 1) is always even, so the integer division by 2 is exact and no double is needed. For n = 10 the answer is 55.
ob FormatOverload - object of the class used to invoke the methods i, j int - loop variables controlling the rows and columns s String - the string whose ASCII codes are to be totalled n int - the limit up to which natural numbers are summed sum int - running total, of ASCII codes or of natural numbers