[#3] KoreanCoding 101: for loops and arrays
Hey there! This week we will be learning vocabulary related to arrays and for
loops! These are the bread and butter for us developers, something we deal with almost every single day. Arrays are like handy containers that let us store and organize data, while for
loops are these amazing tools that help us work with arrays in super flexible and speedy ways. We can loop through arrays, find specific elements, or filter out data that meets certain criteria using for loops. (By the way, some cool JavaScript methods work similarly but we will talk about those next week!) So, let's get into it!
Arrays | 배열
Arrays are like boxes that can hold multiple things at once - we can store strings, numbers, booleans, objects, and even other arrays inside of them. Arrays help us keep things organized and easily accessible. Just like how you can pick out a specific item from your box, we can retrieve individual elements (원소) from an array (배열) using their position or index (인덱스). Index counting starts from 0 (zero-based indexing), so the first element's position in an array called array
will be array[0]
, and the last item can be accessed by using length
property:
const array = ['a', 'b', 'c', 'd']
console.log(array.length) // Logs out 4
console.log(array[0]) // Logs out 'a'
console.log(array[array.length - 1]) // Logs out 'd'
The length
property returns the total number of elements present in the array. To access the last element, we subtract 1 from the length (길이). Why? Well, since index (인덱스) counting starts from 0, the last element's position is actually one less than the length. So, to access the last element (원소), we use array[array.length - 1]
.
for
loop | for
문
Now it's time to understand how for
loops work. A for
loop allows us to repeat (반복) a block of code multiple times. It consists of three essential components: initialization (초기화), condition (조건), and increment/decrement (증감식).
Initialization (초기화): Set an initial value before the loop starts, like initializing a variable or setting a counter.
Condition (조건): Define a condition that is checked before each loop iteration. The loop continues as long as the condition remains true and stops when it becomes false.
Increment/Decrement (증감식): Specify how the loop variable should change after each iteration, like increasing or decreasing its value (값).
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
// Logs out 'Iteration: 0'
// 'Iteration: 1'
// 'Iteration: 2'
// 'Iteration: 3'
// 'Iteration: 4'
We start with i
initialized to 0. The loop will continue as long as i
is less than 5. After each iteration, i
is incremented (증감) by 1. The loop will run five times, with i
taking the values 0, 1, 2, 3, and 4.
It's worth noting that we can set i
to be different values (값) depending on our needs, or we can even make it go in reverse order, like this:
for (let i = 5; i > 0; i--) {
console.log("Iteration: " + i);
}
// Logs out 'Iteration: 5'
// 'Iteration: 4'
// 'Iteration: 3'
// 'Iteration: 2'
// 'Iteration: 1'
Other than for
loop, there are many other kinds of loops, such as while
, do... while
, for... in
, for... of
, etc. You can learn more about them here: JavaScript Loops.
Vocabulary
Nouns:
배열 - array
문자열 배열 - an array of strings
원소, 요소 - element
인덱스 - index
길이 - length
값 - value
정수 - integer
짝수 - even number
홀수 - odd number
유사도 - similarity
소문자 - lowercase letters
중복된 원소 - duplicate elements
반복문 - iterationfor
문 - for
loop
중첩 반복문 - nested loop
초기화 - initialization
조건 - condition
증감 - increment
반복 횟수 - iteration count
Verbs:
추가하다 - to append, to add
삭제하다 - to delete
정렬하다 - to sort
합치다 - to merge
반복하다 - to repeat
Phrases:
1씩 감소하는 수들을 차례로 담은 리스트
a list of numbers decreasing by one
정수가 담긴 리스트
a list of integers
(something)의 개수
the number of (something)
원소의 개수
the number of elements
Challenges
카운트 다운
Description
정수
start
와end
가 주어질 때,start
에서end
까지 1씩 감소하는 수들을 차례로 담은 리스트를 return하도록 solution 함수를 완성해주세요.제한사항
- 0 ≤
end
≤start
≤ 50입출력 예
start end result 10 3 [10, 9, 8, 7, 6, 5, 4, 3] 입출력 예 설명
입출력 예 #1
- 10부터 3까지 1씩 감소하는 수를 담은 리스트는 [10, 9, 8, 7, 6, 5, 4, 3]입니다.
Description:
카운트 다운
Countdown
정수 start
와 end
가 주어질 때,
Integers start
and end
are given as parameters,
start
에서 end
까지 1씩 감소하는 수들을 차례로 담은 리스트를 return하도록 solution 함수를 완성해주세요.
complete the solution
function by returning a list of numbers that decrease by one from start
to end
.
제한사항 (constraints):
The constraints section of the challenge informs us that both end
and start
can have values ranging from 0 to 50. The end
's value will always be less or even start
.
입출력 예 (input-output examples):
#1: When start
= 10 and end
= 3, the result will be [10, 9, 8, 7, 6, 5, 4, 3].
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
The list containing the numbers from 10 to 3 in increments of 1 is [10, 9, 8, 7, 6, 5, 4, 3].
JavaScript Solution
First, we create an empty array called result
.
Then, we use a for
loop to iterate over numbers from start
to end
. The loop starts with the value of start
and continues as long as i
is greater than or equal to end
. The i
's value decrements by one after each iteration.
Inside the loop, each value of i
is pushed into result
array using the push
method. This adds the current value of i
to the end of the result
array.
After the loop finishes, the result
array is returned from the function.
function solution(start, end) {
const result = []
for(let i = start; i >= end; i--) {
result.push(i)
}
return result
}
짝수 홀수 개수
Description
정수가 담긴 리스트
num_list
가 주어질 때,num_list
의 원소 중 짝수와 홀수의 개수를 담은 배열을 return 하도록 solution 함수를 완성해보세요.제한사항
1 ≤
num_list
의 길이 ≤ 1000 ≤
num_list
의 원소 ≤ 1,000입출력 예
num_list result [1, 2, 3, 4, 5] [2, 3] [1, 3, 5, 7] [0, 4] 입출력 예 설명
입출력 예 #1
- [1, 2, 3, 4, 5]에는 짝수가 2, 4로 두 개, 홀수가 1, 3, 5로 세 개 있습니다.
입출력 예 #2
- [1, 3, 5, 7]에는 짝수가 없고 홀수가 네 개 있습니다.
Description:
짝수 홀수 개수
Counting odd and even numbers
정수가 담긴 리스트 num_list
가 주어질 때,
Given a list num_list
of integers,
num_list
의 원소 중 짝수와 홀수의 개수를 담은 배열을 return 하도록 solution 함수를 완성해보세요.
Complete the solution
function to return an array containing the count of even and odd numbers found in num_list
.
제한사항 (constraints):
The num_list
should contain a minimum of 1 element and a maximum of 100 elements and each element in num_list
must be between 0 and 1,000, inclusive.
입출력 예 (input-output examples):
#1: When num_list
= [1, 2, 3, 4, 5], the result should be [2, 3].
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
[1, 2, 3, 4, 5] has two even numbers: 2 and 4, and three odd numbers: 1, 3, 5.
JavaScript Solution
First, we initialize two variables evenCount
and oddCount
and set them both to 0. This is where we will store how many odd and even numbers appeared in our num_list
array.
Then, we use a for
loop to iterate over each element of the num_list
. The loop starts with i
equal to 0 and continues as long as i
is less than the length of num_list
. The loop increments i
by 1 in each iteration.
Inside the loop, it checks whether the current element at index i
is even or odd. This is done by checking if the remainder of dividing the element by 2 is equal to 0. If the current element is even, it increments the evenCount
variable by 1. Otherwise, if the element is odd, it increments the oddCount
variable by 1.
After the loop finishes iterating over all the elements in the num_list
array, it returns an array containing the counts of even and odd numbers, respectively, as [evenCount, oddCount]
.
function solution(num_list) {
let evenCount = 0
let oddCount = 0
for (let i = 0; i < num_list.length; i++) {
if(num_list[i] % 2 === 0) evenCount++
else oddCount++
}
return [evenCount, oddCount]
}
배열의 유사도
Description
두 배열이 얼마나 유사한지 확인해보려고 합니다. 문자열 배열
s1
과s2
가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.제한사항
1 ≤
s1
,s2
의 길이 ≤ 1001 ≤
s1
,s2
의 원소의 길이 ≤ 10
s1
과s2
의 원소는 알파벳 소문자로만 이루어져 있습니다
s1
과s2
는 각각 중복된 원소를 갖지 않습니다.입출력 예
s1 s2 result ["a", "b", "c"] ["com", "b", "d", "p", "c"] 2 ["n", "omg"] ["m", "dot"] 0 입출력 예 설명
입출력 예 #1
- "b"와 "c"가 같으므로 2를 return합니다.
입출력 예 #2
- 같은 원소가 없으므로 0을 return합니다.
Description:
배열의 유사도
Array's similarity
두 배열이 얼마나 유사한지 확인해보려고 합니다.
You want to determine how similar the two arrays are.
문자열 배열 s1
과 s2
가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.
Complete the solution
function to return the number of the same elements when given arrays of strings s1
and s2
.
제한사항 (constraints):
Arrays s1
and s2
can have a minimum length of 1 and a maximum length of 100, and each string in the arrays can have a minimum length of 1 character and a maximum length of 10 characters. Moreover, the elements of s1
and s2
consist only of lowercase letters of the alphabet and there are no duplicate elements within each array.
입출력 예 (input-output examples):
#1: When s1
= ["a", "b", "c"] and s2
= ["com", "b", "d", "p", "c"], result
= 2.
입출력 예 설명 (explanation of input-output examples):
Based on the example #1:
Returns 2 because "b" and "c" appear in both arrays.
JavaScript Solution
First, we initialize a variable called count
to keep track of the number of common elements between the arrays. The initial value is set to 0.
Then we use two nested for
loops to compare each element of s1
with each element of s2
. The outer loop iterates over the elements of s1
, and the inner loop iterates over the elements of s2
.
Inside the inner loop, it checks if the current element of s1
at index i
is equal to the current element of s2
at index j
. If they are equal, it means that there is a common element, so it increments the count
variable by 1.
After the loops finish iterating over all the elements in s1
and s2
, the function returns the final value of count
, which represents the number of common elements between the two arrays.
function solution(s1, s2) {
let count = 0
for (let i = 0; i < s1.length; i++) {
for (let j = 0; j < s2.length; j++) {
if(s1[i] === s2[j]) count++
}
}
return count
}
Wrap-up
And that's a wrap! I hope you've enjoyed today's lesson. Arrays and for
loops are super useful tools that developers use all the time. Understanding how they work and how to use them effectively can really level up your coding game. So keep on learning and experimenting, and soon you'll be able to make the most of arrays and for loops in your own projects.
For those who are keen on trying to solve some similar challenges on their own, I have picked some additional challenges related to arrays and for
loops:
And if you want to support this series and the work I put into it, you can do it by buying me a coffee here:
See you next week!
Subscribe to my newsletter
Read articles from Ha Anna directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ha Anna
Ha Anna
I am a self-taught Front-end developer with a passion for web accessibility and design. I love puzzles, challenges, well-organized spaces, and lame jokes. When I am not coding, I am hanging out with the local stray cats, checking out new cool cafes, or playing golf.