Get really good at programming.

Develop fluency in 69 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever.

is an independent, community funded, not-for-profit organisation.

Explore and get fluent in 69 programming languages

Over 5739 coding exercises. from "allergies" to "zebra puzzle"..

Learn by doing. Get better at programming through fun coding exercises that build your understanding of concepts.

Given a person's allergy score, determine whether or not they're allergic to a given item, and their full list of allergies.

Queen Attack

Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other

Zebra Puzzle

Which of the residents drinks water? Who owns the zebra? Can you solve the Zebra Puzzle with code?

programming problem solving exercises

Write code locally, in your own space

Exercism is primarily built as a CLI-first tool. Download and submit exercises right from your terminal.

Use the Exercism in-browser editor

Don't spend hours installing a language locally just to try it out. We support all 69 of our programming languages in our in-browser editor.

Get automated analysis on your code

Not quite sure how well you've done? We run automatic analysis on your solutions to give you quick feedback and points of improvement.

Deepen your knowledge with human mentoring, for free.

Discover new and exciting ways to approach an exercise by getting mentored on it. Become more familiar with the conventions, idioms and opinions of a particular programming language.

programming problem solving exercises

Why mentoring?

You don't know what you don't know.

When learning a new language, the hardest part is not being aware of the gaps in your knowledge. Our mentors can look at your code and immediately see the ideas you're not familiar with and give you a level-up by unlocking new knowledge.

Learn language-specific conventions

Becoming fluent in a language is more than being able to write code in it - it's about being able to think in that language. Our mentors will help guide you to how to reshape your thinking to write idiomatic code.

Learning with others is fun

Getting feedback from real people is an amazingly exciting way to learn. And becoming a mentor and giving feedback yourself is an even bigger step forward. So complete the circle - be mentored and mentor 🎉

Codemonk

  • Basics of Input/Output
  • Time and Space Complexity
  • Basics of Implementation
  • Basics of Operators
  • Basics of Bit Manipulation
  • Recursion and Backtracking
  • Multi-dimensional
  • Basics of Stacks
  • Basics of Queues
  • Basics of Hash Tables
  • Singly Linked List
  • Binary/ N-ary Trees
  • Binary Search Tree
  • Heaps/Priority Queues
  • Trie (Keyword Tree)
  • Segment Trees
  • Fenwick (Binary Indexed) Trees
  • Suffix Trees
  • Suffix Arrays
  • Basics of Disjoint Data Structures
  • Linear Search
  • Binary Search
  • Ternary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Basics of Greedy Algorithms
  • Graph Representation
  • Breadth First Search
  • Depth First Search
  • Minimum Spanning Tree
  • Shortest Path Algorithms
  • Flood-fill Algorithm
  • Articulation Points and Bridges
  • Biconnected Components
  • Strongly Connected Components
  • Topological Sort
  • Hamiltonian Path
  • Maximum flow
  • Minimum Cost Maximum Flow
  • Basics of String Manipulation
  • String Searching
  • Z Algorithm
  • Manachar’s Algorithm
  • Introduction to Dynamic Programming 1
  • 2 Dimensional
  • State space reduction
  • Dynamic Programming and Bit Masking
  • Basic Number Theory-1
  • Basic Number Theory-2
  • Primality Tests
  • Totient Function
  • Basics of Combinatorics
  • Inclusion-Exclusion
  • Line Sweep Technique
  • Line Intersection using Bentley Ottmann Algorithm
  • Basic Probability Models and Rules
  • Bayes’ rules, Conditional probability, Chain rule
  • Discrete Random Variables
  • Continuous Random Variables
  • Practical Tutorial on Data Manipulation with Numpy and Pandas in Python
  • Beginners Guide to Regression Analysis and Plot Interpretations
  • Practical Guide to Logistic Regression Analysis in R
  • Practical Tutorial on Random Forest and Parameter Tuning in R
  • Practical Guide to Clustering Algorithms & Evaluation in R
  • Beginners Tutorial on XGBoost and Parameter Tuning in R
  • Deep Learning & Parameter Tuning with MXnet, H2o Package in R
  • Decision Tree
  • Simple Tutorial on Regular Expressions and String Manipulations in R
  • Practical Guide to Text Mining and Feature Engineering in R
  • Winning Tips on Machine Learning Competitions by Kazanova, Current Kaggle #3
  • Practical Machine Learning Project in Python on House Prices Data
  • Challenge #1 - Machine Learning
  • Challenge #3 - Machine Learning
  • Challenge #2 - Deep Learning
  • Transfer Learning Introduction
  • Input and Output
  • Python Variables
  • Conditionals
  • Expressions
  • Classes and Objects I
  • Classes and Objects II (Inheritance and Composition)
  • Errors and Exceptions
  • Iterators and Generators
  • Functional Programming
  • Higher Order Functions and Decorators
  • +1-650-461-4192
  • For sales enquiry [email protected]
  • For support [email protected]
  • Campus Ambassadors
  • Assessments
  • Learning and Development
  • Interview Prep
  • Engineering Blog
  • Privacy Policy
  • © 2024 HackerEarth All rights reserved
  • Terms of Service

Simple Programming Problems

Whenever I’m TA for a introductory CS class where students learn some programming language, I have trouble coming up with good exercises. Problems from Project Euler and the like are usually much too difficult for beginners, especially if they don’t have a strong background in mathematics.

This page is a collection of progressively more difficult exercises that are suitable for people who just started learning. It will be extended as I come up with new exercises. Except for the GUI questions, exercises are generally algorithmic and should be solvable without learning any libraries. The difficulty of the exercises of course somewhat depends on the programming language you use. The List exercises for example are more complicated in languages like C that don’t have build-in support for lists.

I suppose they are also useful, although much easier, whenever an experienced person wants to learn a new language.

This guide has been translated to Chinese by yifeitao Simple Programming Problems in Chinese

Before you begin

Learning to program means learning how to solve problems using code. Conceptually it is not very difficult to write a program that solves a problem that you can solve yourself. The skill you need to acquire is thinking very precisely about how you solve the problem and breaking it down into steps that are so simple that a computer can execute them. I encourage you to first solve a few instances of a problem by hand and think about what you did to find the solution. For example if the task is sorting lists, sort some short lists yourself. A reasonable method would be to find the smallest element, write it down and cross it out of the original list and repeat this process until you have sorted the whole list. Then you have to teach the computer 1) how to find the smallest element, 2) how to write it down, 3) how to cross it out, and wrap this in a loop. Then continue this task breakdown process until you’re confident you know how to write the necessary program.

To make good progress in your programming task, you need to test your work as early and as thoroughly as possible. Everybody makes mistakes while programming and finding mistakes in programs consumes a very large part of a programmer’s work-day. Finding a problem in a small and easy piece of code is much simpler than trying to spot it in a large program. This is why you should try to test each sub task you identified during your task-breakdown by itself. Only after you’re confident that each part works as you expect you can attempt to plug them together. Make sure you test the complete program as well, errors can creep in in the way the different parts interact. You should try to automate your tests. The easier it is to test your program, the freer you are in experimenting with changes.

The last important point is how you express your thoughts as code. In the same way that you can express the same argument in different ways in a normal English essay, you can express the same problem-solving method in different ways in code. Try for brevity. The lines that you don’t write are the lines where you can be sure that the don’t have bugs. Don’t be afraid to Google for idiomatic ways of doing the things you’d like to do (after you tried doing them yourself!). Remember that you don’t write the program for the computer, you write it for other humans (maybe a future you!). Choose names that explain things, add comments where these names don’t suffice. Never comment on what the code is doing, only write comments that explain why .

This is a bad example:

The exact same idea is much easier to understand if you write it like this:

Better naming and a better task breakdown make the comments obsolete. Revise your code just as you would revise an essay. Sketch, write, delete, reformulate, ask others what they think. Repeat until only the crispest possible expression of your idea remains. Revisit code you’ve written a while ago to see whether you can improve it with things you’ve learned since.

  • Write a program that prints ‘Hello World’ to the screen.
  • Write a program that asks the user for their name and greets them with their name.
  • Modify the previous program such that only the users Alice and Bob are greeted with their names.
  • Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
  • Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n =17
  • Write a program that asks the user for a number n and gives them the possibility to choose between computing the sum and computing the product of 1,
, n .
  • Write a program that prints a multiplication table for numbers up to 12.
  • Write a program that prints all prime numbers. (Note: if your programming language does not support arbitrary size numbers, printing all primes up to the largest number you can easily represent is fine too.)
  • Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.
  • Write a program that prints the next 20 leap years.
  • Write a program that computes the sum of an alternating series where each element of the series is an expression of the form ( ( − 1 ) k + 1 ) / ( 2 * k − 1 ) ((-1)^{k+1})/(2 * k-1) for each value of k k from 1 to a million, multiplied by 4. Or, in more mathematical notation

4 ⋅ ∑ k = 1 10 6 ( − 1 ) k + 1 2 k − 1 = 4 ⋅ ( 1 − 1 / 3 + 1 / 5 − 1 / 7 + 1 / 9 − 1 / 11 
 ) . 4\cdot \sum_{k=1}^{10^6} \frac{(-1)^{k+1}}{2k-1} = 4\cdot(1-1/3+1/5-1/7+1/9-1/11\ldots).

Lists, Strings

If your language of choice doesn’t have a build in list and/or string type (e.g. you use C), these exercises should also be solvable for arrays. However, some solutions are very different between an array-based list (like C++’s vector ) and a pointer based list (like C++’s list ), at least if you care about the efficiency of your code. So you might want to either find a library, or investigate how to implement your own linked list if your language doesn’t have it.

  • Write a function that returns the largest element in a list.
  • Write function that reverses a list, preferably in place.
  • Write a function that checks whether an element occurs in a list.
  • Write a function that returns the elements on odd positions in a list.
  • Write a function that computes the running total of a list.
  • Write a function that tests whether a string is a palindrome.
  • Write three functions that compute the sum of the numbers in a list: using a for -loop, a while -loop and recursion. (Subject to availability of these constructs in your language of choice.)
  • Write a function on_all that applies a function to every element of a list. Use it to print the first twenty perfect squares. The perfect squares can be found by multiplying each natural number with itself. The first few perfect squares are 1*1= 1 , 2*2=4 , 3*3=9 , 4*4=16 . Twelve for example is not a perfect square because there is no natural number m so that m*m=12 . (This question is tricky if your programming language makes it difficult to pass functions as arguments.)
  • Write a function that concatenates two lists. [a,b,c] , [1,2,3] → [a,b,c,1,2,3]
  • Write a function that combines two lists by alternatingly taking elements, e.g. [a,b,c] , [1,2,3] → [a,1,b,2,c,3] .
  • Write a function that merges two sorted lists into a new sorted list. [1,4,6] , [2,3,5] → [1,2,3,4,5,6] . You can do this quicker than concatenating them followed by a sort.
  • Write a function that rotates a list by k elements. For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2] . Try solving this without creating a copy of the list. How many swap or move operations do you need?
  • Write a function that computes the list of the first 100 Fibonacci numbers. The first two Fibonacci numbers are 1 and 1. The n+1 -st Fibonacci number can be computed by adding the n -th and the n-1 -th Fibonacci number. The first few are therefore 1, 1, 1+1=2, 1+2=3, 2+3=5, 3+5=8.
  • Write a function that takes a number and returns a list of its digits. So for 2342 it should return [2,3,4,2] .
  • Write functions that add, subtract, and multiply two numbers in their digit-list representation (and return a new digit list). If you’re ambitious you can implement Karatsuba multiplication . Try different bases . What is the best base if you care about speed? If you couldn’t completely solve the prime number exercise above due to the lack of large numbers in your language, you can now use your own library for this task.
  • Write a function that takes a list of numbers, a starting base b1 and a target base b2 and interprets the list as a number in base b1 and converts it into a number in base b2 (in the form of a list-of-digits). So for example [2,1,0] in base 3 gets converted to base 10 as [2,1] .
  • Implement the following sorting algorithms: Selection sort, Insertion sort, Merge sort, Quick sort, Stooge Sort. Check Wikipedia for descriptions.
  • Implement binary search.

Write a function that takes a list of strings an prints them, one per line, in a rectangular frame. For example the list ["Hello", "World", "in", "a", "frame"] gets printed as:

Write function that translates a text to Pig Latin and back. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word and adding ‘ay’. “The quick brown fox” becomes “Hetay uickqay rownbay oxfay”.

Intermediate

  • Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,
,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.
  • Write a program that takes the duration of a year (in fractional days) for an imaginary planet as an input and produces a leap-year rule that minimizes the difference to the planet’s solar year.
  • Implement a data structure for graphs that allows modification (insertion, deletion). It should be possible to store values at edges and nodes. It might be easiest to use a dictionary of (node, edgelist) to do this.
  • Write a function that generates a DOT representation of a graph.
  • Using a sample text, create a directed (multi-)graph where the words of a text are nodes and there is a directed edge between u and v if u is followed by v in your sample text. Multiple occurrences lead to multiple edges.
  • Do a random walk on this graph: Starting from an arbitrary node choose a random successor. If no successor exists, choose another random node.
  • Write a program that automatically converts English text to Morse code and vice versa.
  • Write a program that finds the longest palindromic substring of a given string. Try to be as efficient as possible!
  • Think of a good interface for a list. What operations do you typically need? You might want to investigate the list interface in your language and in some other popular languages for inspiration.
  • Implement your list interface using a fixed chunk of memory, say an array of size 100. If the user wants to add more stuff to your list than fits in your memory you should produce some kind of error, for example you can throw an exception if your language supports that.
  • Improve your previous implementation such that an arbitrary number of elements can be stored in your list. You can for example allocate bigger and bigger chunks of memory as your list grows, copy the old elements over and release the old storage. You should probably also release this memory eventually if your list shrinks enough not to need it anymore. Think about how much bigger the new chunk of memory should be so that your performance won’t be killed by allocations. Increasing the size by 1 element for example is a bad idea.
  • If you chose your growth right in the previous problem, you typically won’t allocate very often. However, adding to a big list sometimes consumes considerable time. That might be problematic in some applications. Instead try allocating new chunks of memory for new items. So when your list is full and the user wants to add something, allocate a new chunk of 100 elements instead of copying all elements over to a new large chunk. Think about where to do the book-keeping about which chunks you have. Different book keeping strategies can quite dramatically change the performance characteristics of your list.
  • Implement a binary heap. Once using a list as the base data structure and once by implementing a pointer-linked binary tree. Use it for implementing heap-sort.
  • Implement an unbalanced binary search tree.
  • Implement a balanced binary search tree of your choice. I like (a,b)-trees best.
  • Compare the performance of insertion, deletion and search on your unbalanced search tree with your balanced search tree and a sorted list. Think about good input sequences. If you implemented an (a,b)-tree, think about good values of a and b.
  • Given two strings, write a program that efficiently finds the longest common subsequence.
  • Given an array with numbers, write a program that efficiently answers queries of the form: “Which is the nearest larger value for the number at position i ?”, where distance is the difference in array indices. For example in the array [1,4,3,2,5,7] , the nearest larger value for 4 is 5. After linear time preprocessing you should be able to answer queries in constant time.
  • Given two strings, write a program that outputs the shortest sequence of character insertions and deletions that turn one string into the other.
  • Write a function that multiplies two matrices together. Make it as efficient as you can and compare the performance to a polished linear algebra library for your language. You might want to read about Strassen’s algorithm and the effects CPU caches have. Try out different matrix layouts and see what happens.
  • Implement a van Emde Boas tree. Compare it with your previous search tree implementations.
  • Given a set of d-dimensional rectangular boxes, write a program that computes the volume of their union. Start with 2D and work your way up.
  • Write a program that displays a bouncing ball.
  • Write a Memory game.
  • Write a Tetris clone
  • Write a program that plays Hangman as good as possible. For example you can use a large dictionary like this and select the letter that excludes most words that are still possible solutions. Try to make the program as efficient as possible, i.e. don’t scan the whole dictionary in every turn.
  • Write a program that plays Rock, Paper, Scissors better than random against a human. Try to exploit that humans are very bad at generating random numbers.
  • Write a program that plays Battle Ship against human opponents. It takes coordinates as input and outputs whether that was a hit or not and its own shot’s coordinates.

Other Collections

Of course I’m not the first person to come up with the idea of having a list like this.

  • Several small problems Programming Practice
  • CPE 101 Projects
  • 99 Lisp Problems , 99 Haskell Problems . Most of these can also be done in other languages.
  • Rosetta Code Programming Tasks . These come with solutions in many languages!
  • Code Golf Challenges . The goal here is to solve the problem with as few characters as possible.
  • SPOJ Problems . This is a list of more than 13000 Problems!
  • Code Abbey According to Github user RodionGork, this is less mathy than Project Euler.

CC-BY-SA Adrian Neumann (PGP Key A0A8BC98 )

adriann.github.io

10 Python Practice Exercises for Beginners With Detailed Solutions

Author's photo

  • python basics
  • get started with python
  • online practice

A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.

Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.

If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. Read about the course in the March 2023 episode of our series Python Course of the Month .

Take the course Python Practice: Word Games , and you gain experience working with string functions and text files through its 27 interactive exercises.  Its release announcement gives you more information and a feel for how it works.

Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work.

To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise.

Let’s get started!

Exercise 1: User Input and Conditional Statements

Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers.

Here, we start by using the built-in function input() , which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times.

Exercise 2: Lowercase and Uppercase Characters

Below is a string, text . It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result:

We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format.

Exercise 3: Building Triangles

Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10.

The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything.

Python Practice Exercises for Beginners

Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy!

Exercise 4: Call a Function From Another Function

Create two functions: print_five_times() and speak() . The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False ). If the repeat parameter is set to False , the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function.

This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program.

If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True .

Exercise 5: Looping and Conditional Statements

Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example:

Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list.

Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold . You may include this if you like.

Exercise 6: Nested Loops and Conditional Statements

Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you:

This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list . Then, we loop through every character in the current word and check if the current character is in the special_chars list.

This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word.

Exercise 7: Lists and Tuples

Create a function find_short_long_word(words_list) . The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list:

the function should return

Assume the input list is non-empty.

The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list.

We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple.

Exercise 8: Dictionaries

As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points.

Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple.

The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable.

Exercise 9: More Dictionaries

Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format:

For example, for input:

the output should be:

Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items.

We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format.

Exercise 10: String Encryption

Implement the Caesar cipher . This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet.

For example, consider the string 'word' . If we shift every letter down one position in the alphabet, we have 'xpse' . Shifting by 2 positions gives the string 'yqtf' . Start by defining a string with every letter in the alphabet:

Name your function cipher(word, shift) , which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter.

This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string.

This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError . When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge.

Do You Want More Python Practice Exercises?

We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games . These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these.

We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “ The 5 Best Python Books for Beginners .” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “ What’s the Best Way to Practice Python? ” If you keep up with your practice exercises, you’ll become a Python master in no time!

You may also like

programming problem solving exercises

How Do You Write a SELECT Statement in SQL?

programming problem solving exercises

What Is a Foreign Key in SQL?

programming problem solving exercises

Enumerate and Explain All the Basic Elements of an SQL Query

PW Skills | Blog

75 Basic Programming Problems and Tutorials for Practice

By Varun Saharawat | November 15, 2023

Solving Basic Programming Problems is the key to achieve success in coding challenges. Students must practice these basic programming problems!

basic programming problems

Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

The beauty of basic programming problems lies in their convenience—they provide a platform to hone your abilities through bite-sized problems, often eliminating the need to construct entire applications. This characteristic allows you to conquer these challenges swiftly, fostering a sense of accomplishment.

Moreover, code challenges are integral components of many coding interviews.

While your resume may showcase your skills and ability to articulate programming concepts, employers want to validate your practical coding capabilities. Tackling coding challenges during interviews becomes a testament to your proficiency and showcases your competence for the role.

Therefore, incorporating coding challenges into your routine sharpens your skills and is an invaluable preparation strategy for job interviews. To kickstart your coding journey, we have curated a collection of popular basic programming problems to pave the way for your continued growth.

Table of Contents

Recommended Technical Course

  • Full Stack Development Course
  • Generative AI Course
  • DSA C++ Course
  • Data Analytics Course
  • Python DSA Course
  • DSA Java Course

Basic Programming Problems Overview

Basic programming problems provide an essential foundation for individuals learning to code, offering a practical and hands-on approach to mastering fundamental concepts in programming.

These problems are designed to introduce beginners to the core coding principles, gradually building their problem-solving skills and comprehension of programming logic.

Whether you are a novice looking to embark on your coding journey or an experienced programmer aiming to reinforce your foundational knowledge, engaging with basic programming problems is a valuable practice.

These problems typically cover essential topics such as data types, loops, conditionals, functions, and basic algorithms, providing a well-rounded introduction to the key building blocks of programming.

The significance of basic programming problems extends beyond mere skill development; it serves as a stepping stone for individuals aspiring to pursue more advanced coding challenges and projects.

By grappling with these foundational problems, learners can cultivate a solid understanding of programming fundamentals, laying the groundwork for future exploration and mastery of more complex coding concepts. Basic programming problems are the cornerstone of a programmer’s educational journey, fostering a strong and resilient coding skill set.

Basic Programming Problems for Beginners

Starting your career in the programming field is  exciting and challenging. For beginners, mastering the basics is crucial, and what better way to do so than by solving basic programming problems ?

Basic Programming Problems Java

Here are some of the basic programming problems JAVA :

1) Hello World:

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(“Hello, World!”);

2) The sum of Two Numbers:

Add two numbers and print the result.

public class Sum {

        int num1 = 5, num2 = 10, sum;

        sum = num1 + num2;

        System.out.println(“Sum: ” + sum);

3) Factorial of a Number:

Calculate the factorial of a number.

public class Factorial {

        int num = 5;

        long factorial = 1;

        for (int i = 1; i <= num; ++i) {

            factorial *= i;

        System.out.println(“Factorial: ” + factorial);

4) Check Even or Odd:

Determine if a number is even or odd.

public class EvenOdd {

        int num = 8;

        if (num % 2 == 0) {

            System.out.println(num + ” is even.”);

        } else {

            System.out.println(num + ” is odd.”);

5) Reverse a String:

Reverse the characters in a given string.

public class ReverseString {

        String str = “Hello”;

        StringBuilder reversed = new StringBuilder(str).reverse();

        System.out.println(“Reversed String: ” + reversed);

Here are some theory-based basic programming problems Java:

1) Differences Between C++ and Java

  • C++: Not platform-independent, follows “write once, compile anywhere.”
  • Java: Platform-independent byte code allows programs to run on any machine.

Languages Compatibility:

  • C++: Compatible with most high-level languages.
  • Java: Incompatible with most languages, comparable to C and C++.

Interaction with the Library:

  • C++: Direct access to native system libraries, suitable for system-level programming.
  • Java: Requires Java Native Interface or library access, not direct call support.

Characteristics:

  • C++: Combines features of procedural and object-oriented languages.
  • Java: Known for automatic garbage collection, lacks support for destructors.

Semantics of the Type:

  • C++: Consistent semantics for primitive and object types.
  • Java: Inconsistent semantics between primitive and object types and classes.

Compiler and Interpreter:

  • Java: Compiled and interpreted language, source code compiles into platform-independent bytecode.
  • C++: Purely compiled language, source program compiles into object code, further executed.

2) Features of the Java Programming Language:

  • Easy: Java is considered easy to learn, with fundamental Object-Oriented Programming (OOP) concepts.
  • Secured Feature: Java provides a secured feature, ensuring the development of virus-free and tamper-free systems.
  • OOP: Java follows Object-Oriented Programming, treating everything as an object.
  • Independent Platform: Java compiles into platform-independent bytecode, interpreted by the Virtual Machine.

3) ClassLoader in Java:

  • A ClassLoader in Java is a subsystem of the Java Virtual Machine responsible for loading class files during program execution.
  • It is the first to load the executable file and includes Bootstrap, Extension, and Application classloaders.

4) Differences Between Heap and Stack Memory in Java:

  • Stack Memory: Allocated to each individual program. Fixed memory space.
  • Heap Memory: Not assigned to Java code initially but available during runtime. Used as needed by the Java code.

Embark on a transformative journey with our comprehensive course, “ Decode Java+DSA 1.0 ,” meticulously designed to empower you with the skills needed to excel in programming. This course seamlessly integrates Core Java and Data Structures and Algorithms (DSA), offering a holistic learning experience that lays a robust foundation for your programming journey.

Key Features:

  • Comprehensive Java Coverage: Delve into the intricacies of Core Java, unraveling the language’s syntax, features, and object-oriented programming concepts. From basic constructs to advanced topics, this course ensures a thorough understanding of Java.
  • Powerful Problem-Solving with DSA: Unlock the potential of Data Structures and Algorithms to efficiently solve complex problems. Acquire the essential tools and strategies to approach real-world challenges with confidence and precision.
  • Hands-On Learning: Immerse yourself in practical, hands-on exercises that reinforce theoretical concepts. Through coding exercises and projects, you’ll apply your knowledge, fostering a deeper understanding of both Java and DSA.
  • Expert Guidance: Benefit from expert guidance provided by seasoned instructors with extensive industry experience. Learn industry best practices and gain insights into the practical applications of Java and DSA.

Who Should Enroll:

  • Programming Enthusiasts
  • Students Pursuing Computer Science or Related Fields
  • Professionals Seeking to Strengthen Core Java and DSA Skills

Upon completion of “ Decode Java+DSA 1.0 ,” by PW you’ll emerge as a proficient programmer equipped with the skills to tackle diverse programming challenges. Whether you’re aiming to kickstart your programming career, enhance your academic pursuits, or upskill for professional growth, this course is your gateway to mastering Java and DSA. Elevate your programming prowess and embark on a journey of continuous learning and innovation.

Basic Programming Problems in C

The table below shows the basic programming problems in C :

Put your learning into action with hands-on projects that simulate real-world scenarios with Decode Full Stack Web Dev 1.0 by PW . From designing responsive user interfaces to implementing robust server-side functionalities, you’ll gain practical experience that enhances your proficiency.

Learn essential tools like Git for version control, ensuring collaborative and efficient development. Explore deployment strategies to showcase your applications to the world, covering platforms like Heroku.

Who Should Enroll

  • Aspiring Web Developers 
  • Computer Science Students 
  • Professionals Transitioning to Web Development 
  • Entrepreneurs Looking to Build Web Applications

Basic Programming Problems in Python

In addition to introducing you to Python’s syntax and structure, tackling basic programming problems in Python helps you improve your problem-solving skills. With tasks ranging from basic logic puzzles to intricate algorithmic difficulties, these issues offer an interactive method of learning Python and put you on the route to becoming a skilled programmer.

Basic Programming Problems in Javascript

Whether you aim to enhance your web development skills or explore the vast world of JavaScript applications, these problems cater to beginners, guiding them through the foundational aspects of programming in this versatile language. Below table showcases the basic programming problems in Javascript :

Embark on a transformative learning experience with our comprehensive course, “Building MicroServices in Java for Cloud .”

Key Highlights

  • Microservices Fundamentals: Gain a solid understanding of microservices architecture, learning how to decompose large applications into smaller, independently deployable services. Explore the principles and benefits that drive the adoption of microservices in modern software development.
  • Java for Microservices : Leverage the power of Java to build robust microservices. Explore Java frameworks and libraries that facilitate the development of scalable and efficient microservices, ensuring seamless integration with cloud platforms.
  • Communication Strategies: Delve into various communication patterns and protocols essential for microservices interactions. Learn about RESTful APIs, messaging queues, and other communication mechanisms used to establish seamless communication between microservices.
  • Software Developers and Engineers
  • System Architects
  • Cloud Enthusiasts
  • Java Developers Exploring Microservices

Basic Programming Problems and Solutions

Here are 10 basic programming problems along with their solutions:

  • Hello World:

Problem: Write a program that prints “Hello, World!” to the console.

Solution (Python):

print(“Hello, World!”)

  • Sum of Two Numbers:

Problem: Write a program that inputs two numbers and prints their sum.

Solution (Java):

import java.util.Scanner;

public class SumOfTwoNumbers {

        Scanner scanner = new Scanner(System.in);

        System.out.print(“Enter first number: “);

        int num1 = scanner.nextInt();

        System.out.print(“Enter second number: “);

        int num2 = scanner.nextInt();

        int sum = num1 + num2;

  • Factorial of a Number:

Problem: Write a program to calculate the factorial of a given number.

Solution (C++):

#include <iostream>

using namespace std;

int factorial(int n) {

    if (n == 0 || n == 1)

        return 1;

        return n * factorial(n – 1);

int main() {

    int num;

    cout << “Enter a number: “;

    cin >> num;

    cout << “Factorial: ” << factorial(num) << endl;

    return 0;

  • Check Even or Odd:

Problem: Write a program that checks if a given number is even or odd.

Solution (JavaScript):

let number = 7;

if (number % 2 === 0) {

    console.log(number + ” is even”);

    console.log(number + ” is odd”);

  • Reverse a String:

Problem: Write a program to reverse a given string.

original_string = “Hello, World!”

reversed_string = original_string[::-1]

print(“Reversed String:”, reversed_string)

  • Fibonacci Series:

Problem: Generate the Fibonacci series up to a specific limit.

public class FibonacciSeries {

        int limit = 10;

        int firstTerm = 0, secondTerm = 1;

        System.out.println(“Fibonacci Series up to ” + limit + ” terms:”);

        for (int i = 1; i <= limit; ++i) {

            System.out.print(firstTerm + “, “);

            int nextTerm = firstTerm + secondTerm;

            firstTerm = secondTerm;

            secondTerm = nextTerm;

  • Check Prime Number:

Problem: Write a program to check if a given number is prime.

def is_prime(number):

    if number > 1:

        for i in range(2, int(number / 2) + 1):

            if (number % i) == 0:

                return False

        else:

            return True

        return False

if is_prime(num):

    print(num, “is a prime number.”)

    print(num, “is not a prime number.”)

  • Find Maximum Element:

Problem: Write a program to find the maximum element in an array.

int findMax(int arr[], int size) {

    int max = arr[0];

    for (int i = 1; i < size; ++i) {

        if (arr[i] > max) {

            max = arr[i];

    return max;

    int numbers[] = {5, 8, 2, 10, 3};

    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << “Maximum Element: ” << findMax(numbers, size) << endl;

  • Palindrome Check:

Problem: Write a program to check if a given string is a palindrome.

public class PalindromeCheck {

        String str = “level”;

        String reversedStr = new StringBuilder(str).reverse().toString();

        if (str.equals(reversedStr)) {

            System.out.println(str + ” is a palindrome.”);

            System.out.println(str + ” is not a palindrome.”);

  • Count Vowels and Consonants:

Problem: Write a program to count the number of vowels and consonants in a given string.

text = “Hello, World!”

vowels = “AEIOU

Benefits of Solving Basic Programming Problems

Solving basic programming problems offers numerous benefits for individuals looking to enhance their programming skills. Here are some key advantages:

Skill Development:

  • Coding Proficiency: Regular problem-solving helps improve your coding skills and fluency in programming languages.
  • Algorithmic Thinking: It fosters the development of algorithmic thinking, enabling you to devise efficient solutions to various problems.

Logical Thinking:

  • Problem Decomposition: Breaking down problems into smaller components and solving them enhances logical thinking and problem-solving abilities.
  • Pattern Recognition: Regular problem-solving helps in recognizing patterns and similarities between different problems, leading to more efficient solutions.

Learning New Concepts:

  • Exposure to Diverse Topics: Programming problems often cover a wide range of concepts, exposing you to different areas of computer science and software development.
  • New Algorithms and Data Structures: Exploring various problems introduces you to new algorithms and data structures, expanding your knowledge base.

Preparation for Interviews:

  • Technical Interviews: Many technical interviews for programming roles involve solving algorithmic and coding problems. Regular practice prepares you for such interviews and boosts your confidence.
  • Coding Challenges: Familiarity with common coding challenges often encountered in interviews is an asset.

Building a Portfolio:

  • Showcasing Skills: Solving problems allows you to build a portfolio of solutions that you can showcase to potential employers or on coding platforms.
  • GitHub Contributions: Uploading your solutions to platforms like GitHub demonstrates your coding proficiency and problem-solving ability.

Enhanced Efficiency:

  • Code Optimization: Regular practice encourages optimization, leading to more efficient and cleaner code.
  • Time Complexity Awareness: Problem-solving helps in understanding and considering time complexity, contributing to the creation of scalable solutions.

Community Engagement:

  • Online Communities: Engaging in online coding communities allows you to discuss problems, learn from others, and gain insights into alternative solutions.
  • Peer Learning: Collaborating with peers on coding challenges can provide different perspectives and foster a collaborative learning environment.

Career Advancement:

  • Competitive Edge: Building strong problem-solving skills sets you apart in a competitive job market, enhancing your employability.
  • Adaptability: A wide range of problem-solving experiences makes you more adaptable to different tasks and projects.

Personal Satisfaction:

  • Sense of Achievement: Successfully solving programming problems brings a sense of accomplishment, boosting confidence and motivation.
  • Continuous Learning: It fosters a mindset of continuous learning, crucial in a rapidly evolving field like programming.

In summary, regular practice of solving basic programming problems contributes significantly to skill development, logical thinking, and overall proficiency in the field of programming.

For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group

Web Development an Ultimate Roadmap to Success

programming problem solving exercises

Angular js vs React js Career Pros and Cons

angular vs react

7 Tools Must Know For Web Development

Achieve mastery through challenge

Improve your development skills by training with your peers on code kata that continuously challenge and push your coding practice.

programming problem solving exercises

Sharpen your coding skills

Challenge yourself on small coding exercises called "kata". Each kata is crafted by the community to help you strengthen different coding techniques. Master your current language of choice, or quickly pick up any of the 55+ programming languages supported.

programming problem solving exercises

Get instant feedback

Solve kata with your coding style right in the browser and use test cases (TDD) to check it as you progress. Retrain with new, creative, and optimized approaches. Find all of the bugs in your programming practice.

programming problem solving exercises

Earn ranks and honor

Kata code challenges are ranked from beginner to expert level. As you complete higher-ranked kata, you level up your profile and push your software development skills to your highest potential.

programming problem solving exercises

An engaged software development community

Codewars is a collective effort by its users. They are creators—authoring kata to teach various techniques, solving kata with solutions that enlighten others, and commenting with constructive feedback.

Community members added every month

Kata completed every month

Kata created by our community

Tap into the collective wisdom

Compare your solution with others after each kata for greater understanding. Discuss kata, best practices, and innovative techniques with the community. Have your mind blown by how different other solutions can be from your own.

programming problem solving exercises

Create your own kata

Author kata that focus on your interests and train specific skill sets. Challenge the community with your insight and code understanding. Create everything from common developer interview questions to challenges that push the limits of your creativity. Gain honor within the coding dojo.

programming problem solving exercises

What can I use Codewars for?

From beginner to expert and beyond...

Get new perspectives

Solve challenges then view how others solved the same challenge. Pickup new techniques from some of the most skilled developers in the world.

Learn new languages

Solve challenges in a language you are comfortable with, then do it in a language you want to improve with. Level up across different languages.

Compete with peers

Compete against your friends, colleagues, and the community at large. Allow competition to motivate you  towards mastering your craft.

Extremely well done and an excellent example of mastery learning.

programming problem solving exercises

Ahmed Omran

@this_ahmed

Accidentally got addicted to codewars, oops.

programming problem solving exercises

Kelly Williams

Build self-confidence

Not sure if you are progressing well as a programmer? Push yourself to your limits and show yourself what you are really made of.

Become a mentor

Lend your expertise to others, either indirectly by contributing great solutions or directly by creating your own kata and reviewing code.

Insights from Codewars staff and community.

What's new in Codewars: February highlights

What's new in Codewars: February highlights

programming problem solving exercises

What's new in Codewars: Q4 2023 to January 2024

programming problem solving exercises

Codewarriors, it's time to build your personal brand!

Codewars is built on.

The world's most advanced coding assessment platform for organizations looking to scale their hiring, upskilling, and certification programs.

Achieve mastery through challenge.

Top languages

Welcome to Java! Easy Max Score: 3 Success Rate: 97.05%

Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.89%, java if-else easy java (basic) max score: 10 success rate: 91.32%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.61%, java output formatting easy java (basic) max score: 10 success rate: 96.55%, java loops i easy java (basic) max score: 10 success rate: 97.67%, java loops ii easy java (basic) max score: 10 success rate: 97.32%, java datatypes easy java (basic) max score: 10 success rate: 93.66%, java end-of-file easy java (basic) max score: 10 success rate: 97.91%, java static initializer block easy java (basic) max score: 10 success rate: 96.15%.

Problem Solving

Foundations course, introduction.

Before we start digging into some pretty nifty JavaScript, we need to begin talking about problem solving : the most important skill a developer needs.

Problem solving is the core thing software developers do. The programming languages and tools they use are secondary to this fundamental skill.

From his book, “Think Like a Programmer” , V. Anton Spraul defines problem solving in programming as:

Problem solving is writing an original program that performs a particular set of tasks and meets all stated constraints.

The set of tasks can range from solving small coding exercises all the way up to building a social network site like Facebook or a search engine like Google. Each problem has its own set of constraints, for example, high performance and scalability may not matter too much in a coding exercise but it will be vital in apps like Google that need to service billions of search queries each day.

New programmers often find problem solving the hardest skill to build. It’s not uncommon for budding programmers to breeze through learning syntax and programming concepts, yet when trying to code something on their own, they find themselves staring blankly at their text editor not knowing where to start.

The best way to improve your problem solving ability is by building experience by making lots and lots of programs. The more practice you have the better you’ll be prepared to solve real world problems.

In this lesson we will walk through a few techniques that can be used to help with the problem solving process.

Lesson overview

This section contains a general overview of topics that you will learn in this lesson.

  • Explain the three steps in the problem solving process.
  • Explain what pseudocode is and be able to use it to solve problems.
  • Be able to break a problem down into subproblems.

Understand the problem

The first step to solving a problem is understanding exactly what the problem is. If you don’t understand the problem, you won’t know when you’ve successfully solved it and may waste a lot of time on a wrong solution .

To gain clarity and understanding of the problem, write it down on paper, reword it in plain English until it makes sense to you, and draw diagrams if that helps. When you can explain the problem to someone else in plain English, you understand it.

Now that you know what you’re aiming to solve, don’t jump into coding just yet. It’s time to plan out how you’re going to solve it first. Some of the questions you should answer at this stage of the process:

  • Does your program have a user interface? What will it look like? What functionality will the interface have? Sketch this out on paper.
  • What inputs will your program have? Will the user enter data or will you get input from somewhere else?
  • What’s the desired output?
  • Given your inputs, what are the steps necessary to return the desired output?

The last question is where you will write out an algorithm to solve the problem. You can think of an algorithm as a recipe for solving a particular problem. It defines the steps that need to be taken by the computer to solve a problem in pseudocode.

Pseudocode is writing out the logic for your program in natural language instead of code. It helps you slow down and think through the steps your program will have to go through to solve the problem.

Here’s an example of what the pseudocode for a program that prints all numbers up to an inputted number might look like:

This is a basic program to demonstrate how pseudocode looks. There will be more examples of pseudocode included in the assignments.

Divide and conquer

From your planning, you should have identified some subproblems of the big problem you’re solving. Each of the steps in the algorithm we wrote out in the last section are subproblems. Pick the smallest or simplest one and start there with coding.

It’s important to remember that you might not know all the steps that you might need up front, so your algorithm may be incomplete -— this is fine. Getting started with and solving one of the subproblems you have identified in the planning stage often reveals the next subproblem you can work on. Or, if you already know the next subproblem, it’s often simpler with the first subproblem solved.

Many beginners try to solve the big problem in one go. Don’t do this . If the problem is sufficiently complex, you’ll get yourself tied in knots and make life a lot harder for yourself. Decomposing problems into smaller and easier to solve subproblems is a much better approach. Decomposition is the main way to deal with complexity, making problems easier and more approachable to solve and understand.

In short, break the big problem down and solve each of the smaller problems until you’ve solved the big problem.

Solving Fizz Buzz

To demonstrate this workflow in action, let’s solve a common programming exercise: Fizz Buzz, explained in this wiki article .

Understanding the problem

Write a program that takes a user’s input and prints the numbers from one to the number the user entered. However, for multiples of three print Fizz instead of the number and for the multiples of five print Buzz . For numbers which are multiples of both three and five print FizzBuzz .

This is the big picture problem we will be solving. But we can always make it clearer by rewording it.

Write a program that allows the user to enter a number, print each number between one and the number the user entered, but for numbers that divide by 3 without a remainder print Fizz instead. For numbers that divide by 5 without a remainder print Buzz and finally for numbers that divide by both 3 and 5 without a remainder print FizzBuzz .

Does your program have an interface? What will it look like? Our FizzBuzz solution will be a browser console program, so we don’t need an interface. The only user interaction will be allowing users to enter a number.

What inputs will your program have? Will the user enter data or will you get input from somewhere else? The user will enter a number from a prompt (popup box).

What’s the desired output? The desired output is a list of numbers from 1 to the number the user entered. But each number that is divisible by 3 will output Fizz , each number that is divisible by 5 will output Buzz and each number that is divisible by both 3 and 5 will output FizzBuzz .

Writing the pseudocode

What are the steps necessary to return the desired output? Here is an algorithm in pseudocode for this problem:

Dividing and conquering

As we can see from the algorithm we developed, the first subproblem we can solve is getting input from the user. So let’s start there and verify it works by printing the entered number.

With JavaScript, we’ll use the “prompt” method.

The above code should create a little popup box that asks the user for a number. The input we get back will be stored in our variable answer .

We wrapped the prompt call in a parseInt function so that a number is returned from the user’s input.

With that done, let’s move on to the next subproblem: “Loop from 1 to the entered number”. There are many ways to do this in JavaScript. One of the common ways - that you actually see in many other languages like Java, C++, and Ruby - is with the for loop :

If you haven’t seen this before and it looks strange, it’s actually straightforward. We declare a variable i and assign it 1: the initial value of the variable i in our loop. The second clause, i <= answer is our condition. We want to loop until i is greater than answer . The third clause, i++ , tells our loop to increment i by 1 every iteration. As a result, if the user inputs 10, this loop would print numbers 1 - 10 to the console.

Most of the time, programmers find themselves looping from 0. Due to the needs of our program, we’re starting from 1

With that working, let’s move on to the next problem: If the current number is divisible by 3, then print Fizz .

We are using the modulus operator ( % ) here to divide the current number by three. If you recall from a previous lesson, the modulus operator returns the remainder of a division. So if a remainder of 0 is returned from the division, it means the current number is divisible by 3.

After this change the program will now output this when you run it and the user inputs 10:

The program is starting to take shape. The final few subproblems should be easy to solve as the basic structure is in place and they are just different variations of the condition we’ve already got in place. Let’s tackle the next one: If the current number is divisible by 5 then print Buzz .

When you run the program now, you should see this output if the user inputs 10:

We have one more subproblem to solve to complete the program: If the current number is divisible by 3 and 5 then print FizzBuzz .

We’ve had to move the conditionals around a little to get it to work. The first condition now checks if i is divisible by 3 and 5 instead of checking if i is just divisible by 3. We’ve had to do this because if we kept it the way it was, it would run the first condition if (i % 3 === 0) , so that if i was divisible by 3, it would print Fizz and then move on to the next number in the iteration, even if i was divisible by 5 as well.

With the condition if (i % 3 === 0 && i % 5 === 0) coming first, we check that i is divisible by both 3 and 5 before moving on to check if it is divisible by 3 or 5 individually in the else if conditions.

The program is now complete! If you run it now you should get this output when the user inputs 20:

  • Read How to Think Like a Programmer - Lessons in Problem Solving by Richard Reis.
  • Watch How to Begin Thinking Like a Programmer by Coding Tech. It’s an hour long but packed full of information and definitely worth your time watching.
  • Read this Pseudocode: What It Is and How to Write It article from Built In.

Knowledge check

This section contains questions for you to check your understanding of this lesson on your own. If you’re having trouble answering a question, click it and review the material it links to.

  • What are the three stages in the problem solving process?
  • Why is it important to clearly understand the problem first?
  • What can you do to help get a clearer understanding of the problem?
  • What are some of the things you should do in the planning stage of the problem solving process?
  • What is an algorithm?
  • What is pseudocode?
  • What are the advantages of breaking a problem down and solving the smaller problems?

Additional resources

This section contains helpful links to other content. It isn’t required, so consider it supplemental.

  • Read the first chapter in Think Like a Programmer: An Introduction to Creative Problem Solving ( not free ). This book’s examples are in C++, but you will understand everything since the main idea of the book is to teach programmers to better solve problems. It’s an amazing book and worth every penny. It will make you a better programmer.
  • Watch this video on repetitive programming techniques .
  • Watch Jonathan Blow on solving hard problems where he gives sage advice on how to approach problem solving in software projects.

Support us!

The odin project is funded by the community. join us in empowering learners around the globe by supporting the odin project.

How to think like a programmer — lessons in problem solving

How to think like a programmer — lessons in problem solving

by Richard Reis

aNP21-ICMABUCyfdi4Pys7P0D2wiZqTd3iRY

If you’re interested in programming, you may well have seen this quote before:

“Everyone in this country should learn to program a computer, because it teaches you to think.” — Steve Jobs

You probably also wondered what does it mean, exactly, to think like a programmer? And how do you do it??

Essentially, it’s all about a more effective way for problem solving .

In this post, my goal is to teach you that way.

By the end of it, you’ll know exactly what steps to take to be a better problem-solver.

Why is this important?

Problem solving is the meta-skill.

We all have problems. Big and small. How we deal with them is sometimes, well
pretty random.

Unless you have a system, this is probably how you “solve” problems (which is what I did when I started coding):

  • Try a solution.
  • If that doesn’t work, try another one.
  • If that doesn’t work, repeat step 2 until you luck out.

Look, sometimes you luck out. But that is the worst way to solve problems! And it’s a huge, huge waste of time.

The best way involves a) having a framework and b) practicing it.

“Almost all employers prioritize problem-solving skills first.
Problem-solving skills are almost unanimously the most important qualification that employers look for
.more than programming languages proficiency, debugging, and system design.
Demonstrating computational thinking or the ability to break down large, complex problems is just as valuable (if not more so) than the baseline technical skills required for a job.” — Hacker Rank ( 2018 Developer Skills Report )

Have a framework

To find the right framework, I followed the advice in Tim Ferriss’ book on learning, “ The 4-Hour Chef ”.

It led me to interview two really impressive people: C. Jordan Ball (ranked 1st or 2nd out of 65,000+ users on Coderbyte ), and V. Anton Spraul (author of the book “ Think Like a Programmer: An Introduction to Creative Problem Solving ”).

I asked them the same questions, and guess what? Their answers were pretty similar!

Soon, you too will know them.

Sidenote: this doesn’t mean they did everything the same way. Everyone is different. You’ll be different. But if you start with principles we all agree are good, you’ll get a lot further a lot quicker.

“The biggest mistake I see new programmers make is focusing on learning syntax instead of learning how to solve problems.” — V. Anton Spraul

So, what should you do when you encounter a new problem?

Here are the steps:

1. Understand

Know exactly what is being asked. Most hard problems are hard because you don’t understand them (hence why this is the first step).

How to know when you understand a problem? When you can explain it in plain English.

Do you remember being stuck on a problem, you start explaining it, and you instantly see holes in the logic you didn’t see before?

Most programmers know this feeling.

This is why you should write down your problem, doodle a diagram, or tell someone else about it (or thing
 some people use a rubber duck ).

“If you can’t explain something in simple terms, you don’t understand it.” — Richard Feynman

Don’t dive right into solving without a plan (and somehow hope you can muddle your way through). Plan your solution!

Nothing can help you if you can’t write down the exact steps.

In programming, this means don’t start hacking straight away. Give your brain time to analyze the problem and process the information.

To get a good plan, answer this question:

“Given input X, what are the steps necessary to return output Y?”

Sidenote: Programmers have a great tool to help them with this
 Comments!

Pay attention. This is the most important step of all.

Do not try to solve one big problem. You will cry.

Instead, break it into sub-problems. These sub-problems are much easier to solve.

Then, solve each sub-problem one by one. Begin with the simplest. Simplest means you know the answer (or are closer to that answer).

After that, simplest means this sub-problem being solved doesn’t depend on others being solved.

Once you solved every sub-problem, connect the dots.

Connecting all your “sub-solutions” will give you the solution to the original problem. Congratulations!

This technique is a cornerstone of problem-solving. Remember it (read this step again, if you must).

“If I could teach every beginning programmer one problem-solving skill, it would be the ‘reduce the problem technique.’
For example, suppose you’re a new programmer and you’re asked to write a program that reads ten numbers and figures out which number is the third highest. For a brand-new programmer, that can be a tough assignment, even though it only requires basic programming syntax.
If you’re stuck, you should reduce the problem to something simpler. Instead of the third-highest number, what about finding the highest overall? Still too tough? What about finding the largest of just three numbers? Or the larger of two?
Reduce the problem to the point where you know how to solve it and write the solution. Then expand the problem slightly and rewrite the solution to match, and keep going until you are back where you started.” — V. Anton Spraul

By now, you’re probably sitting there thinking “Hey Richard... That’s cool and all, but what if I’m stuck and can’t even solve a sub-problem??”

First off, take a deep breath. Second, that’s fair.

Don’t worry though, friend. This happens to everyone!

The difference is the best programmers/problem-solvers are more curious about bugs/errors than irritated.

In fact, here are three things to try when facing a whammy:

  • Debug: Go step by step through your solution trying to find where you went wrong. Programmers call this debugging (in fact, this is all a debugger does).
“The art of debugging is figuring out what you really told your program to do rather than what you thought you told it to do.”” — Andrew Singer
  • Reassess: Take a step back. Look at the problem from another perspective. Is there anything that can be abstracted to a more general approach?
“Sometimes we get so lost in the details of a problem that we overlook general principles that would solve the problem at a more general level. [
]
The classic example of this, of course, is the summation of a long list of consecutive integers, 1 + 2 + 3 + 
 + n, which a very young Gauss quickly recognized was simply n(n+1)/2, thus avoiding the effort of having to do the addition.” — C. Jordan Ball

Sidenote: Another way of reassessing is starting anew. Delete everything and begin again with fresh eyes. I’m serious. You’ll be dumbfounded at how effective this is.

  • Research: Ahh, good ol’ Google. You read that right. No matter what problem you have, someone has probably solved it. Find that person/ solution. In fact, do this even if you solved the problem! (You can learn a lot from other people’s solutions).

Caveat: Don’t look for a solution to the big problem. Only look for solutions to sub-problems. Why? Because unless you struggle (even a little bit), you won’t learn anything. If you don’t learn anything, you wasted your time.

Don’t expect to be great after just one week. If you want to be a good problem-solver, solve a lot of problems!

Practice. Practice. Practice. It’ll only be a matter of time before you recognize that “this problem could easily be solved with <insert concept here>.”

How to practice? There are options out the wazoo!

Chess puzzles, math problems, Sudoku, Go, Monopoly, video-games, cryptokitties, bla
 bla
 bla
.

In fact, a common pattern amongst successful people is their habit of practicing “micro problem-solving.” For example, Peter Thiel plays chess, and Elon Musk plays video-games.

“Byron Reeves said ‘If you want to see what business leadership may look like in three to five years, look at what’s happening in online games.’
Fast-forward to today. Elon [Musk], Reid [Hoffman], Mark Zuckerberg and many others say that games have been foundational to their success in building their companies.” — Mary Meeker ( 2017 internet trends report )

Does this mean you should just play video-games? Not at all.

But what are video-games all about? That’s right, problem-solving!

So, what you should do is find an outlet to practice. Something that allows you to solve many micro-problems (ideally, something you enjoy).

For example, I enjoy coding challenges. Every day, I try to solve at least one challenge (usually on Coderbyte ).

Like I said, all problems share similar patterns.

That’s all folks!

Now, you know better what it means to “think like a programmer.”

You also know that problem-solving is an incredible skill to cultivate (the meta-skill).

As if that wasn’t enough, notice how you also know what to do to practice your problem-solving skills!

Phew
 Pretty cool right?

Finally, I wish you encounter many problems.

You read that right. At least now you know how to solve them! (also, you’ll learn that with every solution, you improve).

“Just when you think you’ve successfully navigated one obstacle, another emerges. But that’s what keeps life interesting.[
]
Life is a process of breaking through these impediments — a series of fortified lines that we must break through.
Each time, you’ll learn something.
Each time, you’ll develop strength, wisdom, and perspective.
Each time, a little more of the competition falls away. Until all that is left is you: the best version of you.” — Ryan Holiday ( The Obstacle is the Way )

Now, go solve some problems!

And best of luck ?

Special thanks to C. Jordan Ball and V. Anton Spraul . All the good advice here came from them.

Thanks for reading! If you enjoyed it, test how many times can you hit in 5 seconds. It’s great cardio for your fingers AND will help other people see the story.

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Java Exercises - Basic to Advanced Java Practice Set with Solutions

1. Write Hello World Program in Java

2. write a program in java to add two numbers., 3. write a program to swap two numbers, 4. write a java program to convert integer numbers and binary numbers..

  • 5. Write a Program to Find Factorial of a Number in Java
  • 6. Write a Java Program to Add two Complex Numbers

7. Write a Program to Calculate Simple Interest in Java

  • 8. Write a Program to Print the Pascal’s Triangle in Java

9. Write a Program to Find Sum of Fibonacci Series Number

10. write a program to print pyramid number pattern in java., 11. write a java program to print pattern., 12. write a java program to print pattern., 13. java program to print patterns., 14. write a java program to compute the sum of array elements., 15. write a java program to find the largest element in array, 16. write java program to find the tranpose of matrix, 17. java array program for array rotation, 18. java array program to remove duplicate elements from an array, 19. java array program to remove all occurrences of an element in an array, 20. java program to check whether a string is a palindrome, 21. java string program to check anagram, 22. java string program to reverse a string, 23. java string program to remove leading zeros, 24. write a java program for linear search., 25. write a binary search program in java., 26. java program for bubble sort..

  • 27. Write a Program for Insertion Sort in Java

28. Java Program for Selection Sort.

29. java program for merge sort., 30. java program for quicksort., java exercises – basic to advanced java practice programs with solutions.

Java is one of the most popular languages because of its robust and secure nature. But, programmers often find it difficult to find a platform for Java Practice Online. In this article, we have provided Java Practice Programs. That covers various Java Core Topics that can help users with Java Practice.

Take a look at our Java Exercises to practice and develop your Java programming skills. Our Java programming exercises Practice Questions from all the major topics like loops, object-oriented programming, exception handling, and many more.

Table of Content

Pattern Programs in Java

Array programs in java, string programs in java, java practice problems for searching algorithms, practice problems in java sorting algorithms.

  • Practice More Java Problems

Java_Exercise_Poster-(1)

Java Practice Programs

The solution to the Problem is mentioned below:

Click Here for the Solution

5. write a program to find factorial of a number in java., 6. write a java program to add two complex numbers., 8. write a program to print the pascal’s triangle in java.

Pattern_In_Java

Time Complexity: O(N) Space Complexity: O(N)
Time Complexity: O(logN) Space Complexity: O(N)

Sorting_in_java

Time Complexity: O(N 2 ) Space Complexity: O(1)

27. Write a Program for Insertion Sort in Java.

Time Complexity: O(N logN) Space Complexity: O(N)
Time Complexity: O(N logN) Space Complexity: O(1)

After completing these Java exercises you are a step closer to becoming an advanced Java programmer. We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming.

Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews.

More Java Practice Exercises

Java Array Exercise Java String Exercise Java Collection Exercise To Practice Java Online please check our Practice Portal. <- Click Here

FAQ in Java Exercise

1. how to do java projects for beginners.

To do Java projects you need to know the fundamentals of Java programming. Then you need to select the desired Java project you want to work on. Plan and execute the code to finish the project. Some beginner-level Java projects include: Reversing a String Number Guessing Game Creating a Calculator Simple Banking Application Basic Android Application

2. Is Java easy for beginners?

As a programming language, Java is considered moderately easy to learn. It is unique from other languages due to its lengthy syntax. As a beginner, you can learn beginner to advanced Java in 6 to 18 months.

3. Why Java is used?

Java provides many advantages and uses, some of which are: Platform-independent Robust and secure Object-oriented Popular & in-demand Vast ecosystem

Please Login to comment...

  • Java-Arrays
  • java-basics
  • Java-Data Types
  • Java-Functions
  • Java-Library
  • Java-Object Oriented
  • Java-Output
  • Java-Strings
  • Output of Java Program
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. 6 Ways to Improve Your Programming Problem Solving

    programming problem solving exercises

  2. Six Steps to Solving a Programming Problem Infographic

    programming problem solving exercises

  3. How to Build and Use Problem-solving Skills [Dev Concepts #41

    programming problem solving exercises

  4. Problem Solving in C and Python: Programming Exercises and Solutions

    programming problem solving exercises

  5. 1.17. Programming Exercises

    programming problem solving exercises

  6. Problem Solving In Programming

    programming problem solving exercises

VIDEO

  1. Problem Solving Techniques

  2. Exercise 1: How to solve coding problems

  3. Problem Solving Trainings 2023

  4. Problem Solving with Phython.. Right the answer comment #shorts #funnyvideo #shortsvideo #funny

  5. BLHS Design Thinking Process Video

  6. What to expect in final round?

COMMENTS

  1. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  2. 10,000+ Coding Practice Challenges // Edabit

    functional_programming. math. numbers. Very Easy. Add to bookmarks. Add to collection. Basketball Points. You are counting points for a basketball game, given the amount of 2-pointers scored and 3-pointers scored, find the final points for the team and return that value. Examples points(1, 1) 5 points(7, 5) 29 points(38, 8) 100 Notes N/A

  3. Exercism

    Develop fluency in 69 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever. ... Get better at programming through fun coding exercises that build your understanding of concepts. Allergies. Given a person's allergy score, determine whether or not they're allergic to a ...

  4. Programming Tutorials and Practice Problems

    Functional Programming. Higher Order Functions and Decorators. Practice programming skills with tutorials and practice problems of Basic Programming, Data Structures, Algorithms, Math, Machine Learning, Python. HackerEarth is a global hub of 5M+ developers.

  5. Online Coding Practice Problems & Challenges

    Sharpen your coding skills with CodeChef. Old practice page Recent Contest Problems

  6. Python Exercises, Practice, Challenges

    Each exercise has 10-20 Questions. The solution is provided for every question. Practice each Exercise in Online Code Editor. These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

  7. 20 Code Challenges To Put What You're Learning to the Test

    Code challenges help you build problem-solving skills, better understand the programming language you use, and get to know algorithms you may not be familiar with. If you want to improve your skills in programming, there's no better way than by writing code. In addition, coding challenges are convenient because they allow you to exercise your ...

  8. Simple Programming Problems

    Whenever I'm TA for a introductory CS class where students learn some programming language, I have trouble coming up with good exercises. Problems from Project Euler and the like are usually much too difficult for beginners, especially if they don't have a strong background in mathematics.. This page is a collection of progressively more difficult exercises that are suitable for people who ...

  9. How to Solve Coding Problems with a Simple Four Step Method

    In this post, we've gone over the four-step problem-solving strategy for solving coding problems. Let's review them here: Step 1: understand the problem. Step 2: create a step-by-step plan for how you'll solve it. Step 3: carry out the plan and write the actual code.

  10. 10 Python Practice Exercises for Beginners With Detailed Solutions

    A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills. ... The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be ...

  11. 75 Basic Programming Problems and Tutorials for Practice

    Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

  12. Codewars

    codewars IS BUILT ON. The world's most advanced coding assessment platform for organizations looking to scale their hiring, upskilling, and certification programs. through challenge. A coding practice website for all programming levels - Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

  13. Do You Solve Programming Problems or Complete Exercises? (The

    Each day we put our problem-solving skills to work as programmers: debugging code, learning a new topic, or even solving a problem. Exercises have their place, but as a programmer there's no replacement for solving problems. Exercise with Exercises. There are two ways you can benefit from exercises. First, they're helpful when learning a ...

  14. Solve Python

    Join over 16 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews. ... Problem Solving (Basic) Python (Basic) Problem Solving (Advanced) Python (Intermediate) Difficulty. Easy. Medium. Hard. Subdomains.

  15. The 10 Most Popular Coding Challenge Websites [Updated for 2021]

    A great way to improve your skills when learning to code is by solving coding challenges. Solving different types of challenges and puzzles can help you become a better problem solver, learn the intricacies of a programming language, prepare for job interviews, learn new algorithms, and more.

  16. Solve Java

    Join over 16 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  17. Problem Solving

    From his book, "Think Like a Programmer", V. Anton Spraul defines problem solving in programming as: ... The set of tasks can range from solving small coding exercises all the way up to building a social network site like Facebook or a search engine like Google. Each problem has its own set of constraints, for example, high performance and ...

  18. Logic Problems

    A logic problem is a general term for a type of puzzle that is solved through deduction. Given a limited set of truths and a question, we step through the different scenarios until an answer is found. While these problems rarely involving coding, they require problem-solving and the ability to articulate plausible outcomes.

  19. How to think like a programmer

    Simplest means you know the answer (or are closer to that answer). After that, simplest means this sub-problem being solved doesn't depend on others being solved. Once you solved every sub-problem, connect the dots. Connecting all your "sub-solutions" will give you the solution to the original problem. Congratulations!

  20. Python Practice Problems: Get Ready for Your Next Interview

    While this solution takes a literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the .translate() solution in practice problem 2. Solution 2. The second solution to this problem mimics the behavior of Python's built-in method .translate(). Instead of shifting each letter by a given ...

  21. Java Exercises

    We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews. More Java Practice Exercises

  22. C programming Exercises, Practice, Solution

    C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs.

  23. Java programming Exercises, Practice, Solution

    Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking the solution. Hope, these exercises help you to improve your Java ...