[Week 3] Important Practice Questions for ICSE and ISC
This week we have a few questions which deals with converting from one type of loop to another type, for the ICSE as well as ISC students preparing for their 2013 Computer Applications and Computer Science Examinations respectively.
This week we have a few questions which deals with converting from one type of loop to another type, for the ICSE as well as ISC students preparing for their 2013 Computer Applications and Computer Science Examinations respectively.
[To know more about these weekly practice questions, Click Here]
You need to answer the given questions, and reply it as comments by filling the "Leave a Reply" section below this post.
The correct answers will be posted next week.
Question 1. Write an equivalent ‘For Loop’ for the ‘While Loop’ given below: public void sum (int n) { int s=0; while(n>0) { s=s+n%10; n/=10; } System.out.println(“Sum of digits = “+s); } Question 2. What will happen if the keyword ‘break’ is replaced by ‘continue’ in the below code? int i=60; while (true) { if (i <= 12 ) break; i = i – 12; } System.out.println(“i = “+i); Question 3. Convert the following ‘For Loop’ into ‘While Loop’ public void calc (int n) { int f = 1; for(int i = 1; i <=n; i++) f = f * i; System.out.println(“Factorial = “+f); }Answers
1. public void sum (int n) { int s=0; for(int i=n ; i>0; i=i/10) { s=s+i%10; } System.out.println(“Sum of digits = “+s); }2. If the keyword ‘break’ is replaced by ‘continue’ in the given code, then the loop will become infinite.
[Reason: First, when the value of i = 60, then, the condition (60 <= 12) is not satisfied, hence value of i = 60 -12 = 48. Again, (48 <= 12) is not satisfied, hence value of i = 48 - 12 = 36. Again, (36 <= 12) is not satisfied, hence value of i = 36 - 12 = 24. Again, (24 <= 12) is not satisfied, hence value of i = 24 - 12 = 12. Now, since (12 <= 12) is satisfied, it will encounter 'continue'. this will cause the loop to execute again without executing the statement i = i – 12, as only 'continue' is inside 'if'. So the value of i will remain 12. Then it will again satisfy the condition (12 <= 12) and hence it will again continue. And this process will go on infinitely.]
3. public void calc (int n) { int f = 1; i = 1; while(i<=n) { f=f*i; i++; } System.out.println(“Factorial = "+f);Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.