# Counting Columns explainer

The aim of this puzzle: To count all the commas so that you can find out how many columns are in the csv file.
Walkthrough of the solution: The variable `firstRow` holds a string (letters between quotes) and each new column is defined by a comma. To count how many columns there are you’ll need to loop through each letter of `firstRow` and count how many commas there are. You should use an if statement inside the for loop to check to see if the letter is equal to `===` a comma (,). If the letter is equal to a comma (i.e. if the if statement condition `()` is True), then you’ll want to add one to the variable `numCommas`. You can add to a variable like this: `numCommas = numCommas + 1`.
Sample code solution:
(Tap below to reveal)

``````var numCommas = 0;
for (var letter of firstRow) {
if (letter === ',') {
numCommas = numCommas + 1;
}
}
print('There are ' + numCommas + ' commas.');
``````

JavaScript Concepts: Binary Expression (+), Code Block (for loop, if statement), Calling Functions, Conditionals (===), Identifiers, Loops, Variable Declaration
Grasshopper Concepts: print()

Not able to understand.

I don’t understand in what part the code count the commas? And if have count 5 commas and we add 1 to the numCommas there will be 6 commas! No?

Hey there,

We can break this problem down by looking at a similar block of code. Take a look at the following:

``````var greeting = 'hello world';
var numL = 0;
for (var letter of greeting) {
if (letter === 'l') {
numL = numL + 1;
}
}

print('There are ' + numL + 'Ls');
``````

This code will count the number of times the letter `'l'` appears in the string `'hello world'`.

First, the variable `numL` is declared. This variable will hold the total number of `l`s, but we will set it to `0` at first, because we haven’t counted yet.

Next, a For Loop is set up. This will loop through each character in the string `'hello world'`, from the first character to the last, including whitespace and symbols. The variable `letter` will hold the current character being looked at, and the If Statement inside the For Loop will test if this letter is equal to `'l'`.

If the letter is `'l'`, then it will add 1 to the variable `numL`. If the letter is not `'l'`, it will do nothing, and move on to the next character in the string.

The For Loop will continue until it has looped through the entire string. After the For Loop is complete, the code will print out a sentence containing the final value of `numL`.

Hope this helps! Let me know if you have any more questions.
-Ben