Computer Applications
Give the output of the following program segment:
void encode()
{
String s= "DICe";
char ch;
for(i=0;i<4;i++)
{ ch=s.charAt(i);
if("AEIOUaeiou".indexOf(ch)>=0)
System.out.println("@");
else
System.out.println(ch);
}
Answer
The given code snippet is missing the closing curly brace } for the method encode().
The corrected code is as follows:
void encode()
{
String s= "DICe";
char ch;
for(i=0;i<4;i++)
{ ch=s.charAt(i);
if("AEIOUaeiou".indexOf(ch)>=0)
System.out.println("@");
else
System.out.println(ch);
}
}
Output
D
@
C
@
Explanation
1. void encode() — Declares a method named encode that does not return any value (void).
2. String s = "DICe"; — Inside the method, a String variable s is initialized with the value "DICe".
3. char ch; — Declares a variable ch of type char which will be used to store each character of the string during the loop.
4. for(i=0;i<4;i++) — Starts a for loop where the integer variable i begins at 0.
- The loop continues as long as
iis less than 4. - After each iteration,
iis incremented by 1.
5. ch = s.charAt(i); — Inside the loop, the character at position i in the string s is extracted using charAt(i) and stored in the variable ch.
6. if("AEIOUaeiou".indexOf(ch) >= 0) — This if statement checks whether the character ch is a vowel.
- The string
"AEIOUaeiou"contains all uppercase and lowercase vowels. - The method
indexOf(ch)returns the position ofchin this string if found; otherwise, it returns-1. - If the return value is 0 or greater (meaning
chis found in the string), the condition evaluates to true.
7. System.out.println("@"); — If the condition is true (i.e., ch is a vowel), this line prints the symbol "@". 8. System.out.println(ch); — If the character is not a vowel, the original character ch is printed.
Related Questions
Consider the following program which calculates the Norm of a matrix. Norm is square root of sum of squares of all elements.
Fill in the blanks (a) and (b) with appropriate java statements:
double norm() { int x[][]={{1,5,6},{4,2,9},{6,1,3}}; int r, c, sum=0; for(r=0;r<3;r++) { for(c=0;c<3;c++) sum=sum+_____(a)_____; } ____(b)________; }Give the output of the following program segment:
for(r=1;r<=3;r++) { for(c=1;c<r;c++) { System.out.println(r); } }Name the following:
(a) What is the main condition to perform binary search on an array?
(b) A sort method in which consecutive elements are NOT compared.
Answer the following:
(a) Scanner class method to accept a character.
(b) Jump statement which stops the execution of a construct.