Skip to main content

Copy string converting lower to upper using pointer

Short answer

copyUpper(char *src, char *dest) uses pointer loops: if *src between 'a'-'z', store *src-32 to dest; else copy *src. Increment both pointers, then null-terminate dest. Main reads string, removes newline, calls function, prints original and uppercase copy.

Write a program that reads a string from user and use a user defined function to copy the content of the read string into another character array changing lower case letter to upper if any. Use pointer to process the string.

Logic. The function copyUpper(char *src, char *dest) walks along the source string with the pointer src. For each character *src: if it lies between 'a' and 'z', 32 is subtracted (the ASCII code of a small letter is 32 more than that of the capital letter) and stored through dest; otherwise it is copied unchanged. Both pointers are incremented after every character, and '\0' is added at the end of dest. No array subscripts are used.

#include <stdio.h>

/* copy src to dest, converting lower case letters to upper case */
void copyUpper(char *src, char *dest)
{
    while (*src != '\0') {
        if (*src >= 'a' && *src <= 'z')
            *dest = *src - 32;        /* 'a'(97) - 32 = 'A'(65) */
        else
            *dest = *src;
        src++;
        dest++;
    }
    *dest = '\0';
}

int main(void)
{
    char s1[100], s2[100];
    printf("Enter a string: ");
    fgets(s1, sizeof s1, stdin);
    for (char *p = s1; *p; p++)
        if (*p == '\n') *p = '\0';
    copyUpper(s1, s2);
    printf("Original: %s\nCopied  : %s\n", s1, s2);
    return 0;
}

Sample run

Input: Hello World 2024 from Nepal

Enter a string: Original: Hello World 2024 from Nepal
Copied  : HELLO WORLD 2024 FROM NEPAL

Digits and spaces are unchanged; only the lower case letters are converted.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →