Page 318 - CA_Blue( J )_Class9
P. 318
(v) Convert while to for: [2]
int n=123, s=0;
while(n>0)
{
s=s+n%10;
n=n/10;
}
System.out.println(s);
Ans. int s=0;
for(int n = 123; n>0;)
{
s=s+n%10;
n=n/10;
}
System.out.println(s);
(vi) What will be the output? [2]
class for_practice
{
public static void main(String s[])
{
int sum = 0,i,j;
for( i = 1; i <= 2; i++ )
{
for( j = 2; j <= 4; j++ )
{
sum += ( i * j);
}
}
System.out.println("Result = " + sum);
}
}
Ans. Result = 27
(vii) Find the error. [2]
int a;
while(a<=10)
{
int b=2;
while(b<=4)
{
b++;
}
}
Ans. There are two mistakes:
1. variable "a" is not initialised
2. no increment for variable "a
(viii) Convert the following to switch case: [2]
int ch,a=7,b=2;
if(ch==1)
System.out.println("Sum " + (a+b));
else
if(ch==2)
System.out.println("Difference " +(a-b));
else
System.out.println("Product " +(a*b));
316 Touchpad Computer Applications-IX

