Back to extras

Table of contents

Collection of 37 quick programming exercises

Mini courses covered:   Intro to ProgrammingProgramming Toolbox

You can't program

I regularly hear the same thing over and over (and over and over) again from beginner programmers that they know a language or two but somehow can NOT program. Does that even make sense?

Well it does.

It means that they know about different concepts in the language but can't solve problems. The crux here is not being able to "solve problems." That's what's meant by not being able to "program." If you feel the same, no need to worry any more, for I have a solution for you. (Yayy!)

So what's the solution?

Really simple: solve many (many many) simple programming exercises and, in this way, help yourself develop a programming mindset, muscle memory (really important for programmers), and familiarity with your basic programming tools.

You need lower-level schemas

In cognitive sciences, there's something called schema theory, which relates to how our minds organize information and process more information on top of it. The general idea is that in order for you to be able to learn complex things, you must be able to do the simpler things.

Phrasing this more precisely in terms of the theory: Complex things require higher-level schemas — which you can think of as steps of a staircase — in your brain to have been formed. These schemas can NOT be formed without having lower-level schemas, just like you can't have upper steps without the lower ones.

Coming back to the topic at hand, this means that you can't program complicated things until and unless you're super comfortable with the basics — that is, spinning up simple programs (these are your lower-level schemas).

How to approach these exercises?

I feel that hand-holding is one of the biggest problems of resources that help newbies learn programming. But saying that you shouldn't hand-hold newbies at all isn't good either. We need to strike a perfect balance.

Having said that, the approach that you should use in order to attempt these exercises is that you should firstly have a pen and paper ready with you. (Yes, that's right!)

Some exercises are slightly complicated in the thinking that you must apply before being able to solve them, not necessarily in the actual code itself, and that's where a pen and paper come handy. Express your thinking on paper and try to find a road to the solution.

Moreover, in some exercises, I don't state whether you should get the underlying data from input or by setting it in a variable that you yourself define in the program — this is up to you. Where I do state it and you feel that you're tired of getting the input again and again, just use a variable.

Once again, don't take this as a formal test of any kind. This is just you and your ambition to learn how to program better and to solve problems. You're free to tweak problems to your liking (in fact, that's desirable because you might be able to learn a lot from one single exercise by continuously tuning its difficulty up one level than from multiple different exercises).

And most importantly, do NOT rely on AI to solve these. Go back to the pen and paper and see what you might need in the language of your choice to achieve the solution. It's necessary for you to know how to read a documentation and find what you need at the moment. This is the perfect opportunity for you to exercise these skills as well.

So without further ado, let's get started!

I'm assuming that you know at least one programming language.

Echo printing

Ask the user to input anything and then output it back. This is often referred to as echo printing.

Variable swapping

Create two variables x and y in a program and then swap their values.

Addition calculator

Ask the user to input two numbers. Add these two together and then output the result back.

String length

Ask the user to input anything and then output the length of the input (which is a string).

Blank spaces

Ask the user to input anything and then count the number of blank spaces in it. Output this back.

Sorted array

Create an array of numbers (whatever you like), then sort it, and finally print it. The array should be modified in-place.

Sum of positive integers

Given a positive integer n, sum all positive integers less than or equal to n. For example, if n = 10, the result would be 55.

You should do this using a loop even though a closed mathematical formula does exist for it.

Linear search

Create an array of numbers and a variable val holding any number that you like. Find whether val exists in the array or not, using linear search (that is, iterating over the entire array until you find a match).

Iterative factorial

Given a non-negative n, compute its factorial using a for loop. (I call this an iterative factorial.)

Palindrome check

Given a string, determine whether it is a palindrome or not. A palindrome is a string that reads the same way forwards and backwards. For example, "civic" is a palindrome because it reads as "civic" in reverse. But "good" is not a palindrome because it reads as "doog" in reverse.

You shall only work with lowercase characters; no need to overcomplicate.

Exam grade

Given the score achieved by a student in an exam, determine the corresponding grade. Here are the grade thresholds you should use:

  • 90 or above: "A+"
  • 80 to 90 (exclusive): "A"
  • 70 to 80 (exclusive): "B"
  • 60 to 70 (exclusive): "C"
  • Below 60: "F"

For example, if the score is 79.5, the grade is "B."

Price after discount

Given an item's price in dollars (stored in a variable) and a discount, given as a percentage value (e.g. 50, meaning ::50\%::), determine the price after discount. Output it, rounded to 2 decimal places.

For example, if the price is 10.5 and the discount is 50, then output something like this:

$5.25

Digit character

Given a character, output "Digit" if it's a digit (0 - 9) or else "Not a digit."

Student bundles

Given the number of students n in a school, you have to determine how many 5-book bundles you need to order so that one book can be given to each student. For example, if there are 31 students, then you need 7 bundles (not 6 bundles because then you'll have only 30 books).

Time span

Given a time span in seconds, for e.g. 70, express it as a combination of hours, minutes, and seconds, as follows:

Hours: <hrs>
Minutes: <mins>
Seconds: <secs>

Readable time span

Extending the previous exericse, now express the time span in one line, just like you'd do so when writing out the time span. For example, 70 becomes "1 min 10 secs."

If hours, minutes, or seconds, anyone of these are zero, you should NOT include it in the output. For example, 60 (seconds) should be expressed as "1 min." Similarly, 3600 (seconds) should be expressed as "1 hr."

Also remember to omit the "s" suffix if the corresponding time component is singular. For example, you should use "1 min" instead of "1 mins."

More simplified time span

Extend the previous exercise once again, this time omitting all lower components if a larger one is non-zero. For example, if the time span is "3 mins 2 secs" then just write "3 mins."

This also means that you must round the highest non-zero time component. For example:

  • "3 mins 2 secs" is "3 mins".
  • "3 mins 40 secs" is "4 mins" (because 40 is larger than 30).

User confirmation

Create a function to ask the user to enter a "yes" or "no" for confirming something (imagine that this is part of a larger program where you want to get the user's confirmation before doing something) and then return a Boolean likewise.

If the user enters "y" or "n", take it just like a "yes" or "no". If the user enters nothing, or enters anything other than these four values, take it as a "no."

User confirmation, default configurable

Extend the previous program so that you can configure the function to choose a default of your liking. For example, if you want the input to default to a "Yes" in case the user enters nothing or enters something out of the range of the four possible values, then you can provide true to the function.

Minimum number

Given an array of numbers, find the minimum number. In case the array is empty, just use a nullish value (in your language) as the minimum.

Bitwise NOT string

Given a string consisting of 0s and 1s — known as a bit string — compute its bitwise NOT operation, where each 1 becomes a 0 and each 0 becomes a 1. For example, given '1011', you get '0100'.

Random integer

Generate a random integer in a given range ::[a, b]:: (this is interval notation).

Float holding integer

Given a floating-point value, determine whether it holds an integer in it or not. For example, 70.0 holds an integer whereas 70.1 does NOT.

Multiplication table

Given an integer n, print its multiplication table from 1 to 10 as follows:

3 x 1 = 3
3 x 2 = 6
...
3 x 9 = 27
3 x 10 = 30

Array reverse

Given an array of items, reverse the array in-place.

Path segments

Given a Unix filesystem path, like /home/music, in a string, extract the individual path segments in an array. For example, given the path '/home/music', you should get the array:

['home', 'music']

Assume that the path might end at "/" (e.g. /home/music/, in which case the path segments are still "home" and "music") and that there is no contiguous repetition of "/" in the path.

Rudimentary calculator

Ask the user to input two numbers and then input a letter representing an operation that he wants to perform on them. For now, just stick to four operations: addition, subtraction, multiplication, and division. The letters that correspond to these are "a," "s," "m," and "d," respectively.

Validate integer

Create a function to accept a string that is comprised entirely of an integer (this is usually called a stringified integer), e.g. '-50', and then return a Boolean indicating whether it's an integer or not.

For example, '-50' indeed represents a valid integer (in the string). However, '-50s' is NOT a valid integer. Any other type apart from a string must be rejected (i.e. return a Boolean false for it).

Validate integer loop

Ask the user to input an integer and keep asking him again and again if the entered input is invalid. You should, of course, use the function created in the previous exercise for this.

OTP code

Generate a random 4-digit OTP (one-time password) string, usually used to authorize operations in applications. For example, '0038'.

Manual uppercasing

Given a string consisting only of alphanumeric characters, create a function to uppercase the string. Handle the uppercasing manually.

For this exercise, I recommend you to search for how to get the character code of each character in the given string, and also how to go from the character code of a lowercase character to its corresponding uppercase character.

Letter frequency

Given a piece of text, determine the frequency of all the 26 English alphabet letters in it and output something as follows:

a: <count>
b: <count>
c: <count>
...
y: <count>
z: <count>

You must use an array to solve this problem.

Again, in order to solve this exercise, it'll really help you if you know how to get the code of a given character and how to get the character from a given code.

Hyphenated words

Ask the user to input a hyphenated word, i.e. containing the hyphen (-) character, and then display each constituent word out on the document, one-by-one. If the input doesn't contain a hyphen, produce an error message to the user and ask for the input again.

For example, if the user inputs "new-line," the program must output "new" and "line." But if the user inputs "hello," since there is no hyphen in the input, print something like "Invalid input" and then prompt him to input again.

Arithmetic again

Combine the Addition calculator and User confirmation exercises to continuously perform addition of two given numbers until the user asks to exit the loop.

Binary, octal, and hex

Given an integer n, output it in binary, octal, and hexadecimal representations. These representations must be prefixed with "0b," "0o," and "0x" respectively. For example, the binary representation "0b1001" should be produced for the decimal integer 9.

You must use the language's own utilities for this conversion, if available, or write your own.

String representation

Given a string, output it with single quotes (') around it. If the string itself contains single quotes in it, precede them with a backslash (\). If the string contains a backslash, precede it with another backslash.

For example, shown below are the outputs for the strings 'hello' and "he's doing good":

'hello'
'he\'s doing good'

Balanced braces

Given a string containing, or possibly even not containing, left and right curly braces ({ and }), determine whether they are balanced or not.

"Balanced" here means that a right curly brace does NOT appear before a preceding left curly brace, and also that each left curly brace is balanced by a corresponding right curly brace.

For example, the following is balanced:

This is { balanced }

But the following three lines are not:

This is } not balanced {
This is } not balanced
And { this isn't either

In case the string doesn't contain any brace at all, consider it balanced.

Solutions

At the time of this writing, I've written solutions for these exercises in JavaScript and Python, and you can see them all as follows:

Solutions in JavaScript

Solutions in Python