Advertisements
Advertisements
प्रश्न
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 the ASCII codes of each character of the String. Example: CAВ 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))/1` |
कोड लेखन
Advertisements
उत्तर
class MethodOverloader {
// (i) Overloaded method with no parameters to print the nested loop pattern
void format() {
for (int i = 1; i <= 5; i++) {
for (int j = i; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
// (ii) Overloaded method to calculate and return the sum of ASCII codes
int format(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
sum += (int) ch;
}
return sum;
}
// (iii) Overloaded method to calculate and display the sum of natural numbers
void format(int n) {
int sum = (n * (n + 1)) / 2;
System.out.println("Sum of " + n + " natural numbers = " + sum);
}
}shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
