Variables
Imagine you're working with data from laser distance sensors attached to a remote-controlled car.
Before you can display this distance data on a screen or remove it from memory, you'll need a place to store it. That's where variables come in. Think of a variable as a storage bin within your computer's memory, which you "rent" to hold specific data. Essentially, every program you write will utilize variables, each of a particular type.
Declaring a variable in C involves two steps:
Defining the kind of data you'll be storing;
Naming this variable.
Here's what that looks like:
c9123// int - data type// qwerty - variable nameint qwerty;
Specifying the data type ensures the computer allocates the right amount of memory for your data. Now that we're familiar with three basic data types, we can declare variables for each:
c9123int iVariable; // variable of int typefloat fVariable; // variable of float typechar cVariable; // variable of char type
So, once we have a variable, how do we use it? Start by initializing it.
Initialization
To initialize a variable is to assign specific data to that chunk of memory. Given that iVariable
is an integer type, you'd assign it an integer value. Similarly, you'd assign a decimal value to fVariable
and a character to cVariable
.
c9123int iVariable = 832; // variable of int typefloat fVariable = 54.75; // variable of float typechar cVariable = '#'; // variable of char type
Note
When initializing a char type variable, make sure to use single quotes.
With the data stored in these variables, what can we do next?
One option is to display them on a screen.
Main
123456789101112#include <stdio.h> int main() { int iVariable = 832; // variable of int type float fVariable = 54.984; // variable of float type char cVariable = '#'; // variable of char type printf("iVariable = %d\n", iVariable); printf("fvariable = %f\n", fVariable); printf("cVariable = %c\n", cVariable); }
Curious about the odd characters in the printf()
function? We'll dive into that in the next lesson.
Bedankt voor je feedback!
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.