From the course: Code Clinic: Ruby

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Using loops

Using loops

From the course: Code Clinic: Ruby

Start my 1-month free trial

Using loops

- Now that we have all the tools that we need, let's begin our first attempt at solving this challenge. Let's do that by using loops. If you have any prior programming experience, then you'll be familiar with loops. They're useful and they're used often. In Ruby, one of the simplest kinds of loops is times. In this example, the code will loop through eight times. It will repeat itself eight different times. And each time through the loop, the value of n will be to assign a number, starting with zero and incrementing until it gets to seven. When you think of our chess board, we can use a loop like this to loop over each of the eight columns in order to place each of our eight queens. Then, to place a queen in each column, we can loop over each of the eight rows in that column and test each location. If the location is safe, we'll place a queen there and move to the next column. If the location is not safe, then we'll keep going to the next row. Let me show you what that code looks…

Contents