In: Computer Science
Using JavaScript
You must submit a file, called indentation.js
indentation.js: program to indent
The following program is difficult to follow because of its
indentation:
print ( "binary");
var n = Math.pow (2, 31) - 1;
var bits = 0;
while (n> 0) {
bits + = n & 1;
n >> = 1;
}
print ("Number of bits at 1:" + bits);
for (var i = 1; i <= bits; i ++) {
var str = "";
if (i% 3 == 0) {str + = "Fizz";}
if (i% 5 == 0) {str + = "Buzz";}
if (i% 3! = 0) if (i% 5! = 0)
str + = i;
print (str);
}
var x = 2;
var y = 4;
var z = 4;
for (var i = 0; i <x; i ++) {
for (var j = 0; j <y; j ++) {str = ""; for (var k = 0; k <z;
k ++) {
str + = j == k? 'x': '';
}
print (str);} if (i <x - 1) print ("");
You must make the program above more readable by indenting
each line correctly.
Remember that:
* The content of a conditional structure (for, if, while, ...) should be indented by one more level (4 spaces or a tab)
* There should be only one statement per line (and we do not put a "}" on the same line as an instruction)
* Nested structures require to indent more deeply the code:
// Code excluding conditional structures
print ( "test");
if (condition) {
// Everything in this if should be indented
by 4 spaces
print ( "Hello");
while (condition) {
// Everything in
this while is already indented
// of 4 spaces and
is indented by 4 other spaces = 8 spaces
print (
"...");
}
}
Please find the indented code (follow the screenshot) below.
CODE
print ( "binary");
var n = Math.pow (2, 31) - 1;
var bits = 0;
while (n > 0) {
bits += n & 1;
n >>= 1;
}
print ("Number of bits at 1:" + bits);
for (var i = 1; i <= bits; i ++) {
var str = "";
if (i % 3 == 0) {
str += "Fizz";
}
if (i% 5 == 0) {
str += "Buzz";
}
if (i % 3 != 0) {
if (i % 5 != 0) {
str += i;
}
print (str);
}
}
var x = 2;
var y = 4;
var z = 4;
for (var i = 0; i < x; i ++) {
for (var j = 0; j < y; j ++) {
str = "";
for (var k = 0; k < z; k ++) {
str += j == k ? 'x' : '';
}
print (str);
}
if (i < x - 1) {
print ("");
}
}