Hamming: Calculate the Hamming Distance between two DNA strands.

#include <stdio.h>
#include <string.h>

int calculateHammingDistance(const char *strand1, const char *strand2) {
int i, distance = 0;

// Ensure the strands are of the same length
if (strlen(strand1) != strlen(strand2)) {
    printf("Error: DNA strands must be of the same length.\n");
    return -1;
}

// Calculate the Hamming distance
for (i = 0; strand1[i] != '\0'; i++) {
    if (strand1[i] != strand2[i]) {
        distance++;
    }
}

return distance;

}

int main() {
char strand1[100], strand2[100];
int hammingDistance;

// Input two DNA strands
printf("Enter the first DNA strand: ");
scanf("%s", strand1);

printf("Enter the second DNA strand: ");
scanf("%s", strand2);

// Calculate the Hamming distance
hammingDistance = calculateHammingDistance(strand1, strand2);

// Output the result if no error
if (hammingDistance != -1) {
    printf("Hamming Distance: %d\n", hammingDistance);
}

return 0;

}

Hi!

The code you posted looks like a reasonable implementation of a C program that calculates the Hamming distance (for strings with a length of up to 99 characters).

I’m just not sure why you posted it here. Exercism’s C track has a Hamming exercise. You can solve it directly in the online editor. Or you can use the command-line client (the “CLI”) to download the exercise (with the instructions, the initial stub, the tests, the testing framework, and the build files), solve it locally, and submit it with the CLI.

Or did I misunderstand this post? Do you have a question?

Cheers!