Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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

Related questions

...