I've been trying to do the initials program, I am able to get the first initial but not the rest of the initial after a ' '. Sarcastically, my program runs... but it comes out like this: enter image description here

This is a copy of the crazy code I've come up with.

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

    int main(void)
        char initial1;
        char y;
        string name;
        int x = 0;  

    //getting a persons name
    printf("please enter your name:\n");
    name = GetString();

   //code for getting 1st initial
   initial1 = name[0];

  // getting other initials 
   while (x == ' ')
        y = name[x] + 1;

   // output of initials
  printf("your initials are:%c and %c\n", initial1, y);


1 Answer 1


A couple of things going on here.

You declare x as an int and initialize it to 0. Your while loop will run as long as x == ' '. The computer interprets this as "compare the value of x to the integer value of ascii space". The integer value of ascii space is 32. So, your while loop never executes, y is never initialized and thus produces junk in your printf.

Don't you want to test (iterate over) every character in name to detect all the spaces? A while loop may not be the best approach. You might consider a for loop.

Once you get your loop sorted, you might find yourself faced with a problem at y = name[x] + 1; This code will add 1 to whatever is the contents of name[x]. My guess is that is not the result you are after.

And remember, you want to display the initials in upper case.

Back to the drawing board!


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .