Reputation: 13
I want to learn how to working with while loop. But I don't understand, how it works. I watched many examples, but all to no avail. My problem is that I want show each letter in new line from vowel
with the help at while loop
. I don't know how ...
// I know that's example is wrong.
function while_loop() {
var vowel = ["a", "e", "o", "u", "i", "A", "E", "O", "U", "I"];
var cout = 1;
while (cout < vowel.length) {
console.log(vowel);
cout++;
}
}
// * I could do so with the help `For Loop`. But my goal is learning how to work with while loop
function for_loop() {
var vowel = ["a", "e", "o", "u", "i"];
for (var i = 0; i < vowel.length; i++) {
console.log(vowel[i]);
}
}
while_loop()
for_loop()
Upvotes: 0
Views: 138
Reputation: 71
In this case, for-loop and while-loop are almost the same. It's just that in the for-loop you "make" the variable (i) in the for-loop function, and for the while-loop, you make the variable (cout, which you probably misspelled and meant count) outside of the loop. So basically, it's the same but it's named differently and it's "made" in a different place.
Cout++ is the same case, you add 1 to the cout variable in both loops, it's just in a different place.
The problem with your code is that in the while-loop, you have console.log(vowel) instead of console.log(vowel[cout]), which you correctly put in the for-loop. And there's another little mistake, that arrays are indexed from 0 (as you did it in the for-loop), and not from 1 (as you did it in the while-loop).
So the code should look like this:
function while_loop() {
var vowel = ["a", "e", "o", "u", "i", "A", "E", "O", "U", "I"];
var cout = 0;
while (cout < vowel.length) {
console.log(vowel[cout]);
cout++;
}
}
function for_loop() {
var vowel = ["a", "e", "o", "u", "i"];
for (var i = 0; i < vowel.length; i++) {
console.log(vowel[i]);
}
}
while_loop()
for_loop()
Upvotes: 0
Reputation: 11
You just have to include the index while console logging so it prints the element at specific index and not the whole array.
function while_loop() {
var vowel = ["a", "e", "o", "u", "i", "A", "E", "O", "U", "I"];
var cout = 0;
while (cout < vowel.length) {
console.log(vowel[cout]);
cout++;
}
}
while_loop();
and start cout from 0 so that first element is included.
Now to the working of while loops - The purpose of a while loop is to execute a code block again and again as long as an expression is true. Once the expression becomes false, the loop ends. In most cases, you will have to update something(like cout here) to make the expresssion false. Otherwise the loop will run infinite number of times.
Upvotes: 0
Reputation: 68
The problem is that you're console logging the entire array vowel, instead of vowel[cout]. Additionally, cout should start at 0; this is the solution:
function while_loop() {
var vowel = ["a", "e", "o", "u", "i", "A", "E", "O", "U", "I"];
var cout = 0;
while (cout < vowel.length) {
console.log(vowel[cout]);
cout++;
}
}
while_loop();
Upvotes: 2