C Programming Tutorial 14 – Working with Strings

Don’t forget to read the last blog about arithmetic expressions! Are you new here? Start at the beginning, Intro to C!

When we first started this series, we created a program where all it did was say “hello world” on the screen. It looked something like this:

Well, what if we wanted this to say something like our name?

We could modify the program by replacing the printf() line with this:

We are passing in an argument what is known as a string, which always has double quotes. You can think of a string as a bunch of characters strung together.  

This is cool and all, but what if we want to ask the user using our program what his or her name is?

In order to do that, before we print we need to create a variable. We’ll discuss the specifics of how this variable works in a future video, but we are going to be creating what is known as a char array.

This allows the user to put in up to 30 characters. You actually don’t want to use the last character because that character is used to say it is the end of your name. If you don’t reserve that last character, the computer might think your name goes on longer than it really does. The last character in that string is called the null terminator.

Now, we can get input using scanf();

Now, in previous videos we had to use an ampersand before the variable name, but we actually don’t have to do this with arrays, as we will discuss more in the future when we start working with arrays and pointers.

scanf() only accepts one word, so you can’t put your entire name, just use your first name.

If we run the program, it still does the same thing. We are getting the input but not doing anything with it.

Lastly, we can modify our final printf():

By the time you get through this series, this stuff will be easy. I just wanted to give you some of it now so you could start making your own cool programs!

Are you ready to move onto the next blog? We’re going to talk about using functions in C! Let’s go!

Leave a Reply

Your email address will not be published. Required fields are marked *