usually you do only what you need to do. no more and no less. here, you don't really need to store the initials into a string and then print that whole string out (you could though). all you need to do is to print them out and you could do that directly.
another thing is that you don't need your loop to start at i = 0
since you already took care of name[0]
before the loop.
but just to answer your question
how to add a char to a string?
you should first know what a string is. in C, a string is basically a char array whose last element is a '\0'
. as you may know, array sizes in C are fixed — once you create an array of a particular size, you can't change that whether by extending it or reducing it (1).
so as long as you have room in your char array, you can easily add a char to that string. for example:
char str[5] = "car"; /* there's an empty slot we used 4 chars 5
{'c', 'a', 'r', '\0'}*/
str[3] = 'd'; // append 'd'
str[4] = '\0'; // terminate the string; str is now "card"
you could do a similar job using the strcat
function from the standard library, but technically you'd be concatenating a single-char string to another not a char to a string. execute man strcat
for more on that.
if you don't know the exact size before hand, you're typically gonna need to specify a maximum size that you presumably know.
if the size depends on a variable, you can create a variable-length array (allowed in ISO C99+). keep in mind though that an array size specified using a variable doesn't mean that the array size will change as the value in the variable change. the rule is still held — once the size of an array of specified, it's fixed. for example:
unsigned int size = 10;
char str[size]; // str is of size 10
size = 20;
// str is still of size 10
(1) technically, you can sort of get around that using some dynamic memory allocation techniques (addressed later in the course).