C Programming Tutorial 11 -Taking Input from User

In this blog we are going to discuss how to get a value for our variables from the user of our program.

Right now, this example is pretty simple. As we get into more complex programs, we are often going to want to ask the user for some value. Now, taking input can be a very complex and complicated topic. Because of this, I’ll be giving you just the basics to get you started.

The goal of the application we are going to write is to calculate the area of a circle. So we are going to change some of our variables!

One thing that will become a big concern later is data validation. Let’s say we ask a user for an integer and they give us something like “tacos.” That can break our program. The topic of data validation is to make sure that the user inserts the correct kind of data.

We are going to basically ignore data validation for now because it will require a lot of other knowledge, but I wanted to start off teaching you how to get input so you can work on building some cool programs.

We’ve already discussed the printf() function. This is a function for output. In order to use this function, you must include stdio.h. When we include that, we also get access to another function called scanf. This is the function we will start off with to get user input.

We have to say what type of data to expect, which is why we use the %i  There are other format strings available, but this is the one we need for this situation.

The & behind the radius is called the address-of operator. This gets into some more advanced features of C, but what you need to know is that if you passed in radius by itself, and the compiler was okay with that, the function would get a copy of the value of radius and wouldn’t actually be able to change the value of radius. We need it to change radius because this function is going to ask the user for a number and then assign that value to radius. It would not work without the &.

The reason printf() does not need the address-of operator is because it doesn’t change the value, it just displays it on the screen, so it’s okay to have a copy of the value given to the function.

We will get into all of that later because I don’t want to distract from the purpose of this video. When we run a scanf(), it is going to just pause at the screen. Let’s give it a try!

You can see that it doesn’t tell the user what to do, so it’s super confusing.Let’s add a prompt.

In the next video we will worry about calculating the area. For now, let’s just output this value to the screen to make sure it got the right value and that it is working.

Congratulations! Now you know how to do input and output!

Now we need to calculate the radius and output the value to the screen. That’s what we are going to discuss in the next blog! Check it out!

Leave a Reply

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