Practical activity

Duration1h15

Presentation & objectives

Below is a list of exercises for experimenting with building algorithms focusing on loop construction. The topic is the manipulation of strings. Similar to lists/arrays, strings can be iterated over, and can be seen as a collection of characters.

Once your algorithms designed, it is recommended to code them in Python to be able to test them. However, if you do not feel confident with Python so far, you can simply write them on a sheet of paper and test them by hand.

When testing your algorithms, try to think of cases that cover all possible results. For instance, if your algorithm should output true or false, try it for inputs that lead to both cases.

Constraint – There are many ways to write algorithms to solve a problem, and many ways to program an algorithm. In this practical activity, you do not have the right to use the break keyword. Also, think carefully on whether you need a bounded loop (for) or an unbounded one (while).

Important

The aim of this session is to help you master the basics of algorithms and programming by tackling very classic and simple problems. An intelligent programming assistant such as GitHub Copilot, that you may have installed already, will be able to provide you with a solution to these exercises based only on a wisely chosen file name.

For the sake of training, we advise you to postpone the discovery of Copilot’s functionalities for now.

Important

We provide you the solutions to the exercises. Make sure to check them only after you have a solution to the exercises, for comparison purpose! Even if you are sure your solution is correct, please have a look at them, as they sometimes provide additional elements you may have missed.

Activity contents

1 — Last occurrence

Start with the following program:

# The string to manipulate
s = "IMT Atlantique"
print(s)

# Write your codes here
# ...
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Write your codes here
        // ...
    }

}

Conceive an algorithm that determines the position (between 0 and the length of s minus 1) of the last occurrence of a symbol in the string s. The searched symbol is stored in a variable named v. The algorithm displays the position found or indicates if the symbol is not present in s.

The algorithm can be evaluated with the following values:

  • s = "IMT Atlantique" and v = 'l'
  • s = "IMT Atlantique" and v = 'z'
  • s = "I love Computer Science and Algorithms" and v = 'o'
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 't'

# Last occurrence of v in s
index = len(s) - 1
while index >= 0 and s[index] != v:
    index -= 1

# Print result
if index >= 0:
    print("Found at index", index)
else:
    print("Not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 'l'

# Use string method to find last occurrence
result = s.rfind(v)

# Print result
if result != -1:
    print("Found at index", result)
else:
    print("Not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 't';

        // Last occurrence of v in s
        int index = s.length() - 1;
        while (index >= 0 && s.charAt(index) != v) {
            index--;
        }

        // Print result
        if (index >= 0) {
            System.out.println("Found at index " + index);
        } else {
            System.out.println("Not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Use string method to find last occurrence
        int result = s.lastIndexOf(v);

        // Print result
        if (result != -1) {
            System.out.println("Found at index " + result);
        } else {
            System.out.println("Not found");
        }
    }

}

2 — First occurrence

Start again with the same base code as in exercise 1.

Conceive an algorithm that determines the position (between 0 and the length of s minus 1) of the first occurrence of a symbol in the string s. The searched symbol is stored in a variable named v. The algorithm displays the position found or indicates if the symbol is not present in s.

The algorithm can be evaluated with the following values:

  • s = "IMT Atlantique" and v = 'l'
  • s = "IMT Atlantique" and v = 'z'
  • s = "I love Computer Science and Algorithms" and v = 'o'
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 't'

# Initialize variable for the while loop
index = 0

# Iterate from the start to the end
while index < len(s) and s[index] != v:
    index += 1

# Print the result
if index < len(s):
    print("Found at index", index)
else:
    print("Not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
v = 'l'

# Use string method to find first occurrence
result = s.find(v)

# Print result
if result != -1:
    print("Found at index", result)
else:
    print("Not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Initialize variable for the while loop
        int index = 0;

        // Iterate from the start to the end
        while (index < s.length() && s.charAt(index) != v) {
            index++;
        }

        // Print the result
        if (index < s.length()) {
            System.out.println("Found at index " + index);
        } else {
            System.out.println("Not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        char v = 'l';

        // Use string method to find first occurrence
        int result = s.indexOf(v);

        // Print result
        if (result != -1) {
            System.out.println("Found at index " + result);
        } else {
            System.out.println("Not found");
        }
    }

}

3 — Prefix

Start again with the same base code as in exercise 1.

Considering a second array of characters, named pref for instance, determine if pref is a prefix of s. Carefully think about the different possible scenarios related to the lengths of s and pref. The algorithm prints if pref is a prefix of s.

The algorithm can be evaluated with the following values:

  • s = "IMT Atlantique" and pref = "IMT"
  • s = "IMT Atlantique" and pref = "IMT Atlantique is a great school"
  • s = "I love Computer Science and Algorithms" and pref = "I love"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
pref = "IMT"

# Iterate over the string util a different character is found
i = 0
while i < len(s) and i < len(pref) and s[i] == pref[i]:
    i += 1

# Print result
if i == len(pref):
    print(pref, "is a prefix of", s)
else:
    print(pref, "is not a prefix of", s)
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
pref = "IMT"

# Use string method for that
if s.startswith(pref):
    print(pref, "is a prefix of", s)
else:
    print(pref, "is not a prefix of", s)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The prefix to search
        String pref = "IMT";

        // Iterate over the string until a different character is found
        int i = 0;
        while (i < s.length() && i < pref.length() && s.charAt(i) == pref.charAt(i)) {
            i++;
        }

        // Print result
        if (i == pref.length()) {
            System.out.println(pref + " is a prefix of " + s);
        } else {
            System.out.println(pref + " is not a prefix of " + s);
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String pref = "IMT";

        // Use string method for that
        if (s.startsWith(pref)) {
            System.out.println(pref + " is a prefix of " + s);
        } else {
            System.out.println(pref + " is not a prefix of " + s);
        }
    }

}

4 — Contains

Start again with the same base code as in exercise 1.

Considering a second array of characters, named substr for instance, determine if substr is present in s. The algorithm indicates the position of the first occurrence of substr in s or whether it is not present.

The algorithm can be evaluated with the following values:

  • s = "IMT Atlantique" and substr = "Atlan"
  • s = "IMT Atlantique" and substr = "Pyhton"
  • s = "I love Computer Science and Algorithms" and substr = "and"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
substr = "Atlan"

# Initialize variables
index_start = 0
index_sub = 0
found = False

# Outer loop: iterate through each position in the string where the substring could start
while index_start <= len(s) - len(substr) and index_sub < len(substr):

    # Inner loop: check if the substring matches at this position
    index_sub = 0
    while index_sub < len(substr) and s[index_start + index_sub] == substr[index_sub]:
        index_sub += 1
    index_start += 1

# Print a message if not found
if index_sub >= len(substr):
    print("Substring found at position", index_start - 1)
else:
    print("Substring not found")
# The string to manipulate
s = "IMT Atlantique"
print(s)

# The thing to search
substr = "Atlan"

# You can directly check with 'in' keyword
if substr in s:
    print("Substring found at index", s.index(substr))
else:
    print("Substring not found")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String substr = "Atlan";

        // Initialize variables
        int indexStart = 0;
        int indexSub = 0;
        boolean found = false;

        // Outer loop: iterate through each position in the string where the substring could start
        while (indexStart <= s.length() - substr.length() && indexSub < substr.length()) {

            // Inner loop: check if the substring matches at this position
            indexSub = 0;
            while (indexSub < substr.length() && s.charAt(indexStart + indexSub) == substr.charAt(indexSub)) {
                indexSub++;
            }
            indexStart++;
        }

        // Print a message if not found
        if (indexSub >= substr.length()) {
            System.out.println("Substring found at position " + (indexStart - 1));
        } else {
            System.out.println("Substring not found");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // The thing to search
        String substr = "Atlan";

        // Use string method for that
        if (s.contains(substr)) {
            System.out.println("Substring found at index " + s.indexOf(substr));
        } else {
            System.out.println("Substring not found");
        }
    }

}

5 — Reverse

Start again with the same base code as in exercise 1.

Determine an algorithm that reverses the content of string s.

The algorithm can be evaluated with the following values:

  • s = "IMT Atlantique"
  • s = "euqitnaltA TMI"
  • s = "I love Computer Science and Algorithms"
Correction
# The string to manipulate
s = "IMT Atlantique"
print(s)

# Loop to append to a new string
result = ""
for character in s:
    result = character + result

# Print the result
print("Reversed string:", result)
# The string to manipulate
s = "IMT Atlantique"
print(s)

# Using operator []
result = s[::-1]

# Print the result
print("Reversed string:", result)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Loop to append to a new string
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            result = s.charAt(i) + result;
        }

        // Print the result
        System.out.println("Reversed string: " + result);
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "IMT Atlantique";
        System.out.println(s);

        // Using StringBuilder for reversing a string
        String result = new StringBuilder(s).reverse().toString();

        // Print the result
        System.out.println("Reversed string: " + result);
    }

}

6 — Palindrome

A palindrome is a word that can be read from both sides, as for instance “radar” or “laval”. Determine a first naive strategy to check if a string is a palindrome based on the reverse algorithm devised earlier.

The algorithm can be evaluated with the following values:

  • s = "laval"
  • s = "rennes"
  • s = "detartrated"
Correction
# Initialize variables
s = "LAVAL"
i = 0

# Iterate over the string
while i < len(s) / 2 and s[i] == s[len(s) - 1 - i]:
    i += 1

# Show result
# Show result
if i >= len(s) / 2:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
# The string to manipulate
s = "laval"
print(s)

# Check if s is a palindrome
if s == s[::-1]:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "laval";
        System.out.println(s);

        // Initialize variables
        int i = 0;

        // Loop to check characters from start and end
        while (i < s.length() / 2 && s.charAt(i) == s.charAt(s.length() - i - 1)) {
          
            i++;
        }

        // Print a message based on the result
        if (i >= s.length() / 2) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }
}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "laval";
        System.out.println(s);

        // Check if s is a palindrome using StringBuilder
        if (s.equals(new StringBuilder(s).reverse().toString())) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}

6.1 — Additional challenge (optional)

A palindrome can also be a sentence, such as "A man, a plan, a canal: Panama". Adapt your algorithm to ignore spaces, punctuation marks and to convert to lowercase before checking if the string is a palindrome.

Python provides built-in methods for such operations : isalnum(), lower().

Correction
# The string to manipulate
s = "A man, a plan, a canal: Panama"
print(s)

# Remove spaces, punctuation marks and convert to lowercase
simplified_s = ""
for character in s:
    if character.isalnum():
        simplified_s += character.lower()

# Iterate over the string
i = 0
while i < len(simplified_s) / 2 and simplified_s[i] == simplified_s[len(simplified_s) - 1 - i]:
    i += 1

# Show result
if i >= len(simplified_s) / 2:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
# The string to manipulate
s = "A man, a plan, a canal: Panama"
print(s)

# Remove spaces, punctuation marks and convert to lowercase
simplified_s = ''.join(character for character in s if character.isalnum()).lower()

# Check if s is a palindrome
if simplified_s == simplified_s[::-1]:
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "A man, a plan, a canal: Panama";
        System.out.println(s);

        // Remove spaces, punctuation marks and convert to lowercase
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char character = s.charAt(i);
            if (Character.isLetterOrDigit(character)) {
                builder.append(Character.toLowerCase(character));
            }
        }
        String simplifiedS = builder.toString();

        // Iterate over the string
        int i = 0;
        while (i < simplifiedS.length() / 2 && simplifiedS.charAt(i) == simplifiedS.charAt(simplifiedS.length() - 1 - i)) {
            i++;
        }

        // Show result
        if (i >= simplifiedS.length() / 2) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // The string to manipulate
        String s = "A man, a plan, a canal: Panama";
        System.out.println(s);

        // Remove spaces, punctuation marks and convert to lowercase
        String simplifiedS = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

        // Check if s is a palindrome using StringBuilder
        if (simplifiedS.contentEquals(new StringBuilder(simplifiedS).reverse())) {
            System.out.println(s + " is a palindrome");
        } else {
            System.out.println(s + " is not a palindrome");
        }
    }

}

To go further

Important

The content of this section is optional. It contains additional material for you to consolidate your understanding of the current topic.

7 — Hexadecimal

Consider a string representing a number in an hexadecimal format. Calculate its decimal value.

As a recall, an hexadecimal number may contain the following digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. ‘A’ is equal to 10, and so on. For instance:

$$\text{8EA4} = 4 * 16^0 + 10 * 16^1 + 14 * 16^2 +8 * 16 ^3$$

A built-in solution exists in Python (and in other languages) to solve this problem but try to work with loops to familiarize with their use. It is assumed that every symbol in the string to be converted is an acceptable digit in hexadecimal format.

Correction
# Initialize variables
to_convert = "8EA4"
result = 0

# Iterate over the string
for index in range(len(to_convert)):

    # Convert to decimal
    value = None
    match to_convert[index]:
        case 'A': value = 10
        case 'B': value = 11
        case 'C': value = 12
        case 'D': value = 13
        case 'E': value = 14
        case 'F': value = 15
        case  _ : value = int(to_convert[index])
    
    # Aggregate to solution
    power = len(to_convert) - index - 1
    result += 16 ** power * value

# Print result
print("Decimal version of", to_convert, "is", result)
# Value to convert
to_convert = "8EA4"

# Convert into decimal
result = int(to_convert, 16)
print("Decimal version of", to_convert, "is", result)
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Initialize variables
        String toConvert = "8EA4";
        int result = 0;

        // Iterate over the string
        for (int index = 0; index < toConvert.length(); index++) {

            // Convert to decimal
            int value;
            char currentChar = toConvert.charAt(index);
            switch (currentChar) {
                case 'A': value = 10; break;
                case 'B': value = 11; break;
                case 'C': value = 12; break;
                case 'D': value = 13; break;
                case 'E': value = 14; break;
                case 'F': value = 15; break;
                default: value = Character.getNumericValue(currentChar); break;
            }

            // Aggregate to solution
            int power = toConvert.length() - index - 1;
            result += Math.pow(16, power) * value;
        }

        // Print result
        System.out.println("Decimal version of " + toConvert + " is " + result);
    }

}
/**
 * To run this code, you need to have Java installed on your computer, then:
 * - Create a file named `Main.java` in a directory of your choice.
 * - Copy this code in the file.
 * - Open a terminal in the directory where the file is located.
 * - Run the command `javac Main.java` to compile the code.
 * - Run the command `java -ea Main` to execute the compiled code.
 * Note: '-ea' is an option to enable assertions in Java.
 */
public class Main {

    /**
     * This is the entry point of your program.
     * It contains the first codes that are going to be executed.
     *
     * @param args Command line arguments received.
     */
    public static void main(String[] args) {
        // Value to convert
        String toConvert = "8EA4";

        // Convert into decimal using Java's built-in method
        int result = Integer.parseInt(toConvert, 16);
        System.out.println("Decimal version of " + toConvert + " is " + result);
    }

}

To go beyond

Important

The content of this section is very optional. We suggest you directions to explore if you wish to go deeper in the current topic.

8 — Check invariants

Coding and testing loops with a few, even wisely selected, cases is not enough to ensure that your algorithm will always returns the expected result. Using mathematical induction, check the correctness of the iterations you have conceived during this activity.

9 — Optimize your solutions

What you can also do is to use AI tools such as GitHub Copilot or ChatGPT, either to generate the solution, or to improve the first solution you came up with! Try to do this for all exercises above, to see the differences with your solutions.