Mark As Completed Discussion

Logical errors, also known as bugs, occur when the code runs without any syntax or runtime errors, but the output is not what we expected. These errors are often caused by mistakes in the logic or algorithm of the program.

Imagine you're a basketball coach and you want to write a program that prints the numbers from 1 to 100. However, for multiples of 3, you want to print 'Slam Dunk' instead of the number, and for multiples of 5, you want to print 'Three-Pointer'. For numbers that are both multiples of 3 and 5, you want to print 'And-One'.

Let's take a look at the code below:

JAVASCRIPT
1for (let i = 1; i <= 100; i++) {
2  if (i % 3 === 0) {
3    console.log('Slam Dunk');
4  } else if (i % 5 === 0) {
5    console.log('Three-Pointer');
6  } else if (i % 3 === 0 && i % 5 === 0) {
7    console.log('And-One');
8  } else {
9    console.log(i);
10  }
11}

You might expect the output to be:

1 2 Slam Dunk 4 Three-Pointer Slam Dunk ...

However, if you run the code, you'll notice that it only prints 'Slam Dunk' for multiples of 3 and 'Three-Pointer' for multiples of 5, but it never prints 'And-One'. This is because the condition i % 3 === 0 is checked before the condition i % 5 === 0 && i % 3 === 0, so the code never reaches the 'And-One' condition.

To fix this logical error, we need to change the order of the conditions. Let's update the code:

JAVASCRIPT
1for (let i = 1; i <= 100; i++) {
2  if (i % 3 === 0 && i % 5 === 0) {
3    console.log('And-One');
4  } else if (i % 3 === 0) {
5    console.log('Slam Dunk');
6  } else if (i % 5 === 0) {
7    console.log('Three-Pointer');
8  } else {
9    console.log(i);
10  }
11}

Now, if you run the updated code, you'll get the expected output:

1 2 Slam Dunk 4 Three-Pointer Slam Dunk ...

By carefully analyzing the logic of the program, we were able to identify the logical error and fix it. Remember, logical errors can be tricky to spot, but with practice and careful debugging, you'll become more proficient at finding and fixing them.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment