How to find the max absolute difference between consecutive characters in a string with C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h> // abs
#include <string.h>

int maxAsciiDiff(const char *s) {
    size_t len = strlen(s);
    if (len < 2) return 0;  // No consecutive characters

    int maxDiff = 0;

    for (size_t i = 0; i < len - 1; ++i) {
        int diff = abs(s[i] - s[i + 1]);
        if (diff > maxDiff) {
            maxDiff = diff;
        }
    }

    return maxDiff;
}

int main(void) {
    const char *s = "jumplings";

    printf("Maximum ASCII difference: %d\n", maxAsciiDiff(s));
    
    return 0;
}




/*
run:

Maximum ASCII difference: 12

*/

 



answered Jan 9 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int maxAsciiDiff(const char *s, char *c1, char *c2) {
    size_t len = strlen(s);
    if (len < 2) return 0;  // No consecutive characters

    int maxDiff = 0;

    for (size_t i = 0; i < len - 1; ++i) {
        int diff = abs(s[i] - s[i + 1]);
        if (diff > maxDiff) {
            maxDiff = diff;
            *c1 = s[i];
            *c2 = s[i + 1];
        }
    }

    return maxDiff;
}

int main(void) {
    const char *s = "jumplings";

    char a = '\0', b = '\0';
    int result = maxAsciiDiff(s, &a, &b);

    printf("Maximum ASCII difference: %d\n", result);
    printf("Characters: '%c' and '%c'\n", a, b);

    return 0;
}



/*
run:

Maximum ASCII difference: 12
Characters: 'g' and 's'

*/

 



answered Jan 9 by avibootz
...