JavaScript: For loop that will iterate from 0 to 15 to find even and odd numbers
JavaScript Conditional Statement and loops: Exercise-5 with Solution
Write a JavaScript for loop that will iterate from 0 to 15. For each iteration, it will check if the current number is odd or even, and display a message to the screen.
Sample Output:
"0 is even"
"1 is odd"
"2 is even"
----------
----------
Calculate a Even Number:
Even Numbers between 1 to 100:
Calculate a Odd Number:
Odd Numbers between 1 to 100:
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>For loop that will iterate from 0 to 15</title>
</head>
<body>
</body>
</html>
JavaScript Code:
for (var x=0; x<=15; x++) {
if (x === 0) {
console.log(x + " is even");
}
else if (x % 2 === 0) {
console.log(x + " is even");
}
else {
console.log(x + " is odd");
}
}
Sample Output:
0 is even 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even 11 is odd 12 is even 13 is odd 14 is even 15 is odd
Flowchart:
Live Demo:
See the Pen javascript-conditional-statements-and-loops-exercise-5 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript conditional statement to find the largest of five numbers.
Next: Write a JavaScript program which compute, the average marks of the following students Then, this average is used to determine the corresponding grade.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
How to insert an item into an array at a specific index (JavaScript)?
What you want is the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
Ref: https://bit.ly/2BXbp04
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework