Computer Applications
The following code has some error(s). Rewrite the correct code and underlining all the corrections made.
integer counter = 0;
i = 10; num;
for (num = i; num >= 1; num--);
{
If i % num = 0
{
counter = counter + 1;
}
}
Answer
The correct code is as follows:
int counter = 0; //Correction 1
int i = 10, num; //Correction 2
for (num = i; num >= 1; num--) //Correction 3
{
if( i % num == 0) //Correction 4
{
counter = counter + 1;
}
}
Explanation
| Correction | Statement | Error |
|---|---|---|
| Correction 1 | integer counter = 0; | The datatype should be int |
| Correction 2 | i = 10; num; | variable declaration cannot be done without a data type. The syntax for variable declaration is datatype variablename = value/expression;. Multiple variables should be separated by comma not semicolon. |
| Correction 3 | for (num = i; num >= 1; num--); | If a semicolon is written at the end of the for loop, the block of the loop will not be executed. Thus, no semicolon should be written after for loop. |
| Correction 4 | If i % num = 0 | If should be written in lower case and the condition should be written within brackets. Equality operator (==) should be used instead of assignment operator (=). |
Related Questions
Write the values that will be assigned to x, y and t after executing the following code.
String s1, s2, x, y; int t; s1 = "classxii"; s2 = "cbseboard"; x = s1.substring(5, 8); y = s2.concat(s1); t = y.length(); System.out.println("x=" + x); System.out.println("y=" + y); System.out.println("t=" + t);Write the values that will be stored in variables num and sum after execution of the following code.
int sum = 0, num = -2; do { sum = sum + num; num++; } while (num < 1);Rewrite the following program segment using while instead of for loop.
int f = 1, i; for(i = 1; i <= 5 ; i++) { f *= i; System.out.println(f); }State the method that
(a) converts a string to a primitive float data type.
(b) determines if the specified character is an uppercase character.