JavaScript · Syntax · Beginner
while loop
Exercises on the while loop in JavaScript: repetition of actions, counters, sums of numbers, input to the desired condition, break, string sorting, and basic character processing.
Quick topic start and explanations before exercises (exercises below):
Counters, accumulators, and the sentinel pattern
#Iterating through strings with while
#Exercises:
Numbers from 1 to 10.
#Print the numbers from 1 to 10 using a while loop.
let i = 1;
Solution
let i = 1;
while (i <= 10) {
console.log(i);
i += 1;
}
// or you can do this: place the stopping condition inside the loop
let i = 1;
while (true) {
if (i > 10) {
break;
}
console.log(i);
i += 1;
}
Countdown from 10.
#Print the numbers from 10 to 1 in reverse order.
let i = 10;
Solution
let i = 10;
while (i >= 1) {
console.log(i);
i -= 1;
}
// or you can do this: use a condition greater than zero
let i = 10;
while (i > 0) {
console.log(i);
i -= 1;
}
Numbers up to the entered value.
#The user enters a number. Print all numbers from 1 to this number.
let n = 5; let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= n) {
console.log(i);
i += 1;
}
Only even numbers up to a number.
#The user enters a number. Print only even numbers from 1 to this number.
let n = 5; let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= n) {
if (i % 2 === 0) {
console.log(i);
}
i += 1;
}
// second option: immediately iterate only through even numbers
let n = 10;
let i = 2;
while (i <= n) {
console.log(i);
i += 2;
}
Sum from 1 to 100.
#Find the sum of all numbers from 1 to 100 using a while loop.
let i = 1; let total = 0;
Solution
let i = 1;
let total = 0;
while (i <= 100) {
total += i;
i += 1;
}
console.log("Sum:", total);
// or you can do this using the formula for the sum from 1 to n
let total = (100 * 101) / 2;
console.log("Sum:", total);
Sum up to the entered number.
#The user enters a number. Find the sum of all numbers from 1 to this number.
let n = 5; let i = 1; let total = 0;
Solution
let n = 5;
let i = 1;
let total = 0;
while (i <= n) {
total += i;
i += 1;
}
console.log("Sum:", total);
Multiplication table.
#The user enters a number. Print the multiplication table for this number from 1 to 10.
let n = 5; let i = 1;
Solution
let n = 5;
let i = 1;
while (i <= 10) {
console.log(`${n} x ${i} = ${n * i}`);
i += 1;
}
// or you can do this: calculate the product first
let n = 5;
let i = 1;
while (i <= 10) {
let result = n * i;
console.log(`${n} x ${i} = ${result}`);
i += 1;
}
Password until correct input.
#The user enters a password. Keep asking for the password until it equals "javascript".
let password = "";
Solution
let password = "";
while (password !== "javascript") {
console.log("Wrong password");
password = "javascript"; // simulation of new input
}
console.log("Password accepted");
Sum of numbers until zero.
#The user enters numbers. The program should calculate the sum of entered numbers until the user enters 0.
let total = 0; let num = 5;
Solution
let total = 0;
let num = 5;
while (num !== 0) {
total += num;
// In a real program, you can get the next value here.
// For the example, let's end the loop.
num = 0;
}
console.log("Sum:", total);
Counting digits in a number.
#The user enters a number. Count how many digits are in this number. You may solve it without a loop in any way.
let num = 5;
Solution
let num = -12345;
let count = String(Math.abs(num)).length;
console.log("Number of digits:", count);
Word backwards.
#Print the word backwards in the terminal.
let word = "иладеп";
Solution
let word = "pedali";
console.log(word.split('').reverse().join(''));
// or:
word = "pedali";
let drow = "";
let index = word.length - 1;
while (index > -1) {
drow += word[index];
index -= 1;
}
console.log(drow);
Text between identical symbols.
#I probably got carried away here and this task is probably not simple. But that's okay, let's slowly think step by step about what needs to be done. Task: There is a string with any information, for example: 'Company LLC "Horns and Hooves" won some procurement tender.' You need to extract the part between identical symbols. For example, in this case, to get the company name, you need to extract the text between quotation marks. Do not use the split string method. Use only the index method!! You can experiment and solve the task without a loop or with a loop, however you like. P.S. You will need slices, and make text input and symbol input for the repeated symbol between which to extract using input. P.P.S See the string methods table. The index method returns the index of the FIRST occurrence of a symbol in a string (it does not return the second one unless you somehow make it become the first one in some intermediate string).
let text = "JavaScript"; let symbol = "a";
Solution
let text = 'Company LLC "Horns and Hooves" won the tender';
let symbol = '"';
let startIndex = text.indexOf(symbol);
if (startIndex === -1) {
console.log("Symbol not found");
} else {
startIndex += 1;
let newText = "";
while (startIndex < text.length) {
let char = text[startIndex];
if (char === symbol) {
break;
}
newText += char;
startIndex += 1;
}
console.log(newText);
}
Letter stairs.
#This one is simple: There is a string "stairs", print it in the terminal like this: s -t --a ---i ----r -----s
let text = "ступеньки";
Solution
let word = "stairs";
let i = 0;
while (i < word.length) {
console.log("-".repeat(i) + word[i]);
i += 1;
}
Removing punctuation from text.
#There is a list of punctuation marks and special symbols: punctuation = "!@#$%^&./,?|" And there is a text string where they may appear. Form a new string without punctuation marks, leaving only the text, keep spaces. That's all that needs to be done.
let punctuation = "!@#$%^&./,?|"; let text = "I guess we'll finish on this exercise. Enough! We want to rest! #@&#@&!!!";
Solution
let punctuation = "!@#$%^&./,?|";
let text = "I guess we'll finish on this exercise. Enough! We want to rest! #@&#@&!!!";
let newText = "";
let idx = 0;
while (idx < text.length) {
let char = text[idx];
if (!punctuation.includes(char)) {
newText += char;
}
idx += 1;
}
console.log(newText);