initials.c

Here is the reference solution for Problem Set 2, initials.c

// A simple program to find the initial letters of each word in a name,
// output the capitalized version of those letters.
// This is "Initializing" from CS50x problem set 2.
//
// Author: david@newtongwc.org

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

int main(void) {
    // This is allocated on the heap, must free it at the end to
    // avoid a memory leak.
    string name = GetString();
    int num_chars = strlen(name);
    for (int i=0; i < num_chars; ++i) {
        if (i == 0 || (name[i] != ' ' && name[i-1] == ' ')) {
            printf("%c", toupper(name[i]));
        }
    }
    printf("\n");
    free(name);
    return 0;
}

Comments