Basic Input & Output in C Programming

Lesson Transcript
Instructor: Sean McKenna

Sean has a Bachelor's Degree in Physics and has taught Computer Science courses as a Graduate Assistant.

C programming is a general purpose language used in computer programming. Learn about basic input and output in C programming and review a simple vending machine program to gain deeper understanding. Updated: 01/24/2022

Basic Input vs Output

Input and output is terminology referring to the communication between a computer program and its user. Input is the user giving something to the program, while output is the program giving something to the user.

Let's say we're stuck in the waiting room at the doctor's office, and we get hungry. Oh look, a vending machine! We're saved! Well, we might not get that excited, but let's get a snack. We'll input $2 into the vending machine, and it will output a bag of chips. This is a very simple and straightforward form of input and output. Put something into a machine, and it puts something back out.

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Practical Application for C Programming: ~'Hello World~' Program

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Basic Input vs Output
  • 0:41 Simple Vending Machine Program
  • 10:34 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Simple Vending Machine Program

In programming, the most basic form of input/output (I/O) is displaying some text to a user and allowing the user to enter some text back. For example, let's say we wanted to write a simple vending machine program where the user inputs a selection from a menu, and the vending machine outputs the name of the product selected.

Well, first let's add a menu. We want to keep it simple, so let's make it look like what's appearing here:

Vending Machine Menu

1 - Chips
2 - Peanuts
3 - Popcorn
4 - Cookie
5 - Drink

In C programming, the most basic function to output text to the screen is printf(). So let's write a program in C that simply displays our menu and exits. We will use the printf() function.


#include <stdio.h>
int main( ) {
   char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};
   printf("Vending Machine Menu\n\n");
   for(int i = 0; i < 5; i++) {
     printf("%d - %s\n", i+1, products + i);
  }
  return 0;
}

There's a lot going on here, so let's look at it line by line, starting with the header files.

Header Files

Let's look at the first line:

#include <stdio.h>

This line includes the header file for the basic input and output functions of the C standard library. Lines like this will appear at the top of C programs to add some extra functionality. In our case, we need some basic input and output functions, so we use the stdio.h header file. I won't go into more detail on the standard library and header files as it's beyond the scope of this lesson, but including header files gives us access to functions that we won't have to write for ourselves. At least one header file will be included in almost every C program.

Main Function

Now, let's look at the main function:

int main( ) {

This line creates the main() function, which will be executed when we run a C program. It's generally good practice to write other functions that can be called from within the main() function, but for a simple program like this, including the code in the main() function itself is generally acceptable.

The Code

Now, let's look at the code itself. In the first couple of lines, we're setting up our program to run. We will see those lines in nearly every C program. Now that we're inside the main() function, we can look at what our program will actually do:

char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};

Here we create an array of products that can be purchased from the vending machine. We can think of an array as a numbered list. When we create the array, it's similar to tearing off a sheet of paper and numbering it. We can then fill in the list of items in any order we want. In almost all programming languages, an array is defined and accessed using brackets. In C programming, a string is created and stored as an array of characters, like this:

char somestring[10] = "some text";

This statement creates an array of characters called somestring to hold the string "some text". If we want to access the values in our array, we can do so by using the index, which is the number for each item in the list. However, instead of starting at one like a numbered list would, the index starts at zero. So if we want to access the first thing in our array, we'll want the item at index zero. We can access the first character in somestring by using the following code:

somestring[0];

The first item in somestring is the first character in "some text", so when the above reference is used it will return the character "s".

Okay, back to our vending machine program. We were looking at the first line:

char products[5][10] = {"Chips", "Peanuts", "Popcorn", "Cookie", "Drink"};

Notice the double set of brackets after products in the code. Since a string is an array of characters in C, we create an array of arrays in order to create an array of strings. Here we are creating the array products to hold 5 strings, each with a maximum length of 10, and filling in all 5 values with the product names we want in our menu.

printf("Vending Machine Menu\n\n");

When you pass a string to the printf() function as a parameter, that string (minus the quotation marks) will be displayed on the screen. In this case, we will use the function to output "Vending Machine Menu". The two line breaks (\n\n) at the end allow us to move to a new line below our menu heading:

for(int i = 0; i < 5; i++){

On this line, we start a loop that will run 5 times so that we can go through our product list:

printf("%d - %s\n", i+1, products + i);

Each time we go through the loop, we will use printf() to display a line about the corresponding product. The %d and %s inside the first parameter are placeholders. These will be replaced with values that we want to insert into the output. The function will go through these placeholders and replace them, in order, with the parameters that follow. The %d is a placeholder for an integer value; in this case, we will be displaying the number of the product. The %s is a placeholder for a string; in this case, the product description will be displayed.

Format Specifiers

Now, let's look at the format specifiers. The %s and %d are called format specifiers, and, as their name suggests, they are used to specify the format of input or output.

The four most common format specifiers are in this chart:

Format Specifier Data Type
%s string
%c character
%d int
%f float

We will generally see these used any time we do input/output in a program.

Now to the last line of our program:

return 0;

This line exits our main() function. By returning 0 as our exit code, we are sending the message that everything completed without error. And if we run our program, we will see this:

Vending Machine Menu

1 - Chips
2 - Peanuts
3 - Popcorn
4 - Cookie
5 - Drink

Great! This is exactly what we wanted. Now it's time to let the user enter a selection.

Taking Input

Now, let's look at taking input. Let's add the following lines to our program:

printf("\n\n");
printf("Please enter a selection (1 - 5): ");
int selection = -1;
scanf("%d", &selection);

The first line here just moves down a couple of lines on our output to make things a little less jumbled up. Next, we prompt the user to enter a selection from the menu we've provided. The third line creates a variable selection to hold the value that the user enters. And, the last line uses the scanf() function to take in the input from the user.

The first parameter in scanf() takes a format specifier (inside quotation marks), and the second takes a pointer to a variable, which is where we want to store the input. So in this case, we are expecting an integer value to be entered, and we will store it in the selection variable we created on the previous line.

Okay, so now we know what snack our user wants! Let's finish up by displaying the selection back to the user:

printf("\n\nYou've selected %s, an excellent choice!\n\n", products + (selection - 1));

Here we use some line breaks to make things look a little nicer, then we use the %s placeholder for the selected product and use the selection variable that the user entered to specify what product they want. Here's what the whole program looks like:

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it now
Create an account to start this course today
Used by over 30 million students worldwide
Create an account