My Coding Place logo

The Source Code

A Blog on Learning Coding and STEM skills

Updated: Apr 5, 2021


Project Intro

Use a 2D array to make a Tic Tac Toe game — and practice using conditionals, loops, and functions!

This is a challenging project for Java coders familiar with basic concepts, and is also great practice for AP Computer Science students.

  • Coding language: Java

  • Approx. lines of code: ~150

  • Approx. time needed to build: 30-60 min

Who is this for?

  • Coding experience in language: Beginner

  • Challenge Level: Hard

Learning Outcomes

Core concepts practiced:

  • 2D arrays

  • Functions

Prerequisite concepts to know/review:

  • Variables

  • Input and output

  • Conditionals

  • Loops

Just using these core concepts, we can create a whole game of Tic Tac Toe from start to finish.

Moreover, we learn how we can turn a commonly played game into code by learning to think like a programmer. Without further ado, let’s get started!



Project Demo

Click run to play the Tic Tac Toe Java game yourself below!

You can also view my project solution code if you get stuck.

Specific features to consider:

  1. After asking us for our names, the program prints out a 3x3 board filled with dashes, signifying empty spots.

  2. Each turn it asks either player 1 or player 2 to enter a row and col index which is where they want to place their x and o, and then the board is printed again with the x or o in the right spot.

  3. If the position the player entered is “off the board” or already has an x or o on it, then our program notifies the player, who is prompted to enter another row and col.

  4. Once the player wins by getting 3 in a row, column, or diagonal, the program prints that player 1 or 2 has won and prints out the final board.

General order of steps to implement:

  1. Create a Tic Tac Toe board and fill it with dashes.

  2. Create a function that draws the board like a square.

  3. Keep track of the player’s turn and what symbol they are using.

  4. Keep asking the user to enter a row and col until they are valid.

  5. Set the right position on the board to the proper symbol.

  6. Create a function that checks if either player has won.

  7. Check if the game has ended in a tie.

  8. Use a loop to keep the game going.

How do we do each of these steps?

Step 1: Create a 3x3 array to represent the tic tac toe board and fill it with dashes.

We need to make a 2D array of characters, which can be x, o, or -.

Hint: We can use the following line of code to make a 3x3 array of chars: char[][] board = new char[3][3]

Now we have to fill our board with dashes.

Hint: We can use a nested for loop to iterate through each position on our board. Inside both for loops, we can set board[i][j] equal to a dash.


Step 2: Ask the users for their names.

First, we import the Scanner to help us get input from the user, by adding import java.util.Scanner to the top of our program.

Then, we create our Scanner variable.

Next, we print out a message asking the user to type in their name using System.out.print().

We store their input in a String called p1.

Do the same for p2.


Step 3: Create a function that draws the board and prints it out like a 3x3 square.

In order for our function to draw the board and print it out, do we need to pass a parameter into the function? Do we need to return anything?

Hint: We need to pass in the board 2D array in order for the function to be able to print it. We don’t need to return anything since the function is simply printing out the board.

Inside our function, we need to print out each position on our board.

Hint: If we do System.out.println(), then each position is on a new line.

Hint: If we do System.out.print(), then all of the positions are on one line.

Hint: We can do System.out.print() in the inner for loop, and do System.out.println() at the end of the outer for loop so that it starts a new line after each row has been printed.


Step 4: Print out the correct player’s turn and store the player’s char (x or o).

We need a way to keep track of which player’s turn it is in our game.

Hint: We can use a boolean called player1 which is true if it is player 1’s turn and false if it is player 2’s turn.

We can use a conditional to check whose turn it is.

Also, we can use string concatenation to print out the player’s name.


Step 5: Ask the user for the row and col and check if it is valid.

Print a message asking the user for a row and use the Scanner to get their input, storing it in a variable called row; repeat this for col.

Now, why would the row and col the user entered not be valid?

Hint: If the user types a row and col that is a spot that is not on the board, then the row and col aren’t valid. Use a conditional to check if the row and col are not greater than 2 and not less than 0.

Hint: If the user types a row and col that is a spot that already has an x or o on it, then the row and col aren’t valid. Use a conditional to check if the position on the board at row and col does not already have an x or o.


Step 6: Use a loop to keep asking the player to enter a valid row and col.

If the user enters a row and col that is out of bounds or a row and col that already has an x or o on it, then we want to ask the user to re-enter a row and col. We can use a loop to do this!

Hint: We can use a while(true) loop and break once the player has entered a valid row and col.


Step 7: Set the right position on the board to the player char.

Outside of the while loop, we know that we have a valid row and col. We can get the position on the board by doing board[row][col].

Now we can set this position to be equal to the char of the player, which we stored in the variable c.


Step 8: Create a function that checks if either player has won.

In tic tac toe, a player wins if they have 3 of their symbols in one row, column, or diagonal.

Let’s start with rows. We can use a for loop to iterate through each row i.

Inside the for loop, we can use a conditional to check if board[i][0] equals board[i][1] and if board[i][1] equals board[i][2]. Remember, we also have to check if board[i][0] doesn’t equal a dash so that we don’t win if there are three empty spots in a row. If that is all true, then we can return the value of board[i][0].

We can repeat similar steps for columns.

There are two diagonals on the board that we have to check. We can use two if statements to check the two diagonals, similar to the if statements we used for rows and columns.

If we reach the end of our function, that means that nobody has won. Here, we can just return a space.


Step 9: Print out which player has won if a player has won.

In our main method, we can use the function we just created to check if a player has won.

Hint: We can use conditionals to check if our function returns x or o. If it returns x, then print that player 1 has won. If it returns o, then print that player 2 has won.


Step 10: Check if the game has ended in a tie.

Tic tac toe ends in a tie if nobody has won and the board is full. We already have checked if someone has won. Now we just need to check if the board is full.

Let’s create a function that returns true if the board is full and false if there are still empty spots on the board. Remember, an empty spot is a dash.

Hint: We can use nested for loops to iterate through each position on the board. Inside the inner for loop, we can use a conditional to check if board[i][j] is equal to -, and if so, return true.

Once we finish going through the nested for loops and find that no position on the board equals a dash, then we know that the board is full so we can return true.


Step 11: Use a loop to keep the game going.

We can create a boolean called gameEnded and initially set it to false. Inside the if statement where we check if a player has won or if it is a tie, we can set gameEnded to true.

We can make a while loop, with its condition simply being gameEnded, so that the program keeps asking a player to enter a row and col until there is a winner or a tie.

If we run our program, we notice that the player doesn’t alternate every round. How can we fix this?

Hint: If there is no winner and no tie, we can switch the player1 boolean by writing the following: player1 = !player1. The ! means not, so if player1 was true, this line sets it to not true, or false, and if player1 was false, this line sets it to not false, or true.

After the while loop is over, we can draw the board a final time so that both players can see the final state of the board..


This article originally appeared on junilearning.com.


Updated: Apr 3, 2021


Our math camps and classes utilize a discovery-based and project-based learning approach. They encourage kids to find a love of math and empower students with the foundational skills and learning prowess they need to take on more advanced math courses and even the most math-intensive career fields.


In this post, you’ll learn what makes these courses so impactful, from our discovery-based learning approach to the process by which we select our outstanding instructors and pair them with students for 1-on-1 learning.


What Is Discovery-Based Learning?


The premise of discovery-based learning is simple: students learn best when they are put at the center of acquiring and building knowledge. This is why our instructors use guided activities to unlock the mathematical intuitions that the student already possesses.


Through engaging, hands-on projects and guiding questions, students in our courses take the lead in learning new concepts. Meanwhile, the instructor takes the role of a guide, adding suggestions and correcting misconceptions as needed. By taking the student’s discoveries and applying them to concrete exercises and comprehensive projects, students become experts in each mathematical concept they discover.


In each of these courses, students will acquire and build the in-depth, conceptual knowledge they need to succeed in their more advanced mathematics courses and future career fields.


Why Should Students Take Our Elementary Mathematics Courses?


The traditional classroom isn’t for everyone


Kids are often placed with 25 or more students in a traditional mathematics classroom and pushed to find the right answer to a given question. As a result, very early in their lives, students begin to see their mathematics skills as fixed: they’re either good or bad at math. With little space to enjoy the process of learning, most students disengage — never truly harnessing their mathematical potential.


Extracurricular mathematics programs often reinforce those sentiments. Rather than focusing on conceptual understanding, embedding elements of creativity, or hands-on activities, such programs use “skill and drill” learning. While fluency practice is a crucial component of developing mathematical skills, it is certainly not the only component.


Re-imagining the learning process


Math In Action challenges the traditional narratives. We empower students to explore, think critically, and ask questions. Rather than merely categorizing an answer as right or wrong, we implore students to ask why.


By leading with these questions, our instructors give students the space to explore new concepts and create meaningful connections. Because of this crucial shift in perspective, our students find their sessions opportunities for endless curiosity and possibilities.


Nurturing a student’s intrinsic motivation — their desire to learn because it is intrinsically gratifying rather than for a reward — sparks a life-long interest in learning that drives both academic and future career success. Offering a student a sense of autonomy and control in the learning process, exactly as discovery-based learning endeavors to do, is an excellent way to foster intrinsic motivation.



What Will Students Learn in Our Elementary Mathematics Courses?


In Early Elementary, kids will gain a deep appreciation for sums, differences, multiplication, and division. They will discover how to represent and interpret data and how these necessary skills are applied to understand time, money, length, and other basic units. By the end of the course, they’ll have improved their confidence by mastering complicated topics like fractions and measurement.



Late Elementary lets kids delve even deeper into the applications of arithmetic. They’ll discover place values, rounding, and multi-digit multiplication and division. Kids will understand how to add, subtract, multiply, and divide fractions and decimals. They’ll even have the chance to work with lines, angles, shapes, and coordinate planes!



Students will be paired with instructors whose focus is to guide the student in articulating their learning, but kids will have the central role in building their mathematics knowledge by working through discovery activities, games, and hands-on projects.


Example: counting penguins


Let’s try one of these fun and engaging activities together. Go ahead and access this discovery activity. Your task is to count the number of penguins on your screen.



How did you do it? Did you start from one corner and count each penguin? Did you group them first?


Because each student is different, we anticipate that they may apply one of several strategies to this activity — just as you did — and we welcome that!


Students will use whatever method they find most intuitive to count the penguins while working alongside their private instructor. After giving students a few moments to engage in a productive struggle, their instructor will guide them towards grouping the penguins by 10s.

In this process, students build their number sense and realize that counting by grouping is highly effective. More importantly, students intuitively learn that 10 groups of 10 penguins will make 100 penguins in total! This skill builds toward adding larger numbers together and eventually forms a central understanding of multiplication.


It All Starts With the Best Instructors


We’re so excited to release a set of mathematics courses that give students opportunities to explore the depths of their learning. This feat would not be possible, though, without our stellar instructors — each of whom was intentionally chosen and paired with students to maximize the students’ learning, comfort, and fun. Our instructors come from the world’s top universities, and we train them to work with all types of students.


Coupled with our discovery-learning curriculum, the 1:1 sessions between students and instructors make our program wonderfully unique. Students build a strong relationship with their instructor, who becomes their mentor as they progress through more challenging Juni mathematics courses.


Ready to Enroll Your Child?


These courses give students a central role in discovering the joy and importance of mathematics, all under our instructors’ 1-on-1 guidance and adapted from Common Core State Standards.


Discovery-based learning gives kids the tools to feel empowered to drive them to succeed in their elementary school courses and future grade levels. If this sounds like an opportunity you want for your child, we encourage you to enroll them today.


This article originally appeared on junilearning.com.


Updated: Feb 21, 2021



Empowering Girls in Computer Science


"That's just for boys!" is a common remark heard among young girls. In fact, my younger sister recently made that comment to me when I asked her if she played a certain videogame. While the context might be innocent or inane, it's alarming how many things are deemed to be "for boys" when, in reality, this couldn't be farther from the truth.


Science- and technology-related fields of study and employment are often treated this way, even though women have historically been at the forefront of groundbreaking scientific and technological advancements. From Ada Lovelace to Katherine Johnson, knowledge of prominent female figures in STEM careers are difficult to come by, although recently more and more stores about these women have surfaced in mainstream media. It is easy to see how young girls internalize the "boys only" misconception when so many of the facts circulated in science and technology appear to be dominated by men.


Women code too


Ada Lovelace was a talented mathematician born in 1815. Ada took to mathematics at an early age, and was able to study math at the collegiate level. While translating an article about an invention created by her mentor, Ada was able to share some of her own ideas about the machine, along with notes on how computer code could be written to give the device repeatable instructions. Because of this, she is considered by many to be the world's first computer programmer.


The story of Katherine Johnson was recently featured in the Oscar-nominated film Hidden Figures. Katherine was an incredibly gifted woman. At the age of 10, she was a freshman in high school. She started working at the National Advisory Committee for Aeronautics, later known as NASA, in 1952. Her job title? Computer. Young women were hired at the time to perform calculations, even when NASA began to use actual computers for these tasks. Katherine's mathematical skills were so virtuosic that her job was to double-check the work of the machines! In 2015, Johnson received the Presidential Medal of Freedom.


Female influences in computer science are not relegated only to historical contributions. Over the past few years Samaira Mehta has been featured in the news and invited to speak at conferences for her work as a programmer — a title she earned at 6 years old! Her work has helped children all across the country learn to code.


Getting girls into computer science


While there is still a considerable amount of progress to be made, there are signs that more girls are getting exposed to computer science earlier on in their K-12 education. In 2018, there was a 39% increase in the number of female students who took the Advanced Placement (AP) Computer Science exam. Taken by high school students, passing scores on AP exams can translate to credit at many American colleges.


Still, in 2015, only 18% graduates with a computer science degree were female. Why is this?

  • Lack of female role models. As we mentioned earlier, the computer scientists and other workers in STEM fields we see at tech companies in Silicon Valley in the news and on TV are usually men. We don't see as many women in technology, and thus software engineering doesn't doesn't get added as often to girls' lists of career aspirations.

  • Lack of early exposure. Studies show that students are ten times more likely to major in computer science if they are introduced to it early on to build their programming experience, like in an AP Computer Science class.

  • Misconceptions about programming as a career.The media also portrays programming as an independent and "nerdy" discipline, whereas building software is actually a very collaborative process.

  • Afraid to make mistakes. Code rarely runs perfectly the first time you run it, and learning how to debug code is a key programming skill.


How coding schools help


It's hard to aspire toward what you've never glimpsed. Seeing women in STEM roles is key to discouraging the "that's for boys" mentality that has girls self-selecting out of fields they could succeed in. Mentorship is a great way to encourage young girls to experiment with technology.


How do coding schools help encourage girls in STEM?

  • Exposure to a female role model. Girls have a mentor to work with who is passionate about computer science and demonstrates highly technical skills.

  • Early exposure to computer programming. Students can start as young as 8, and we offer beginner courses in Scratch and Python.

  • Easy to make mistakes. Our instructors dispel the notion that code has to be perfect before we run it. We emphasize the importance of incrementally testing our code and how to debug code that isn't working.

  • Easy to ask questions. Some girls may be nervous to ask questions in a larger computer science course with more students. In a private class, there is no judgement!



This article originally appeared on junilearning.com