0% found this document useful (0 votes)
2 views30 pages

Variables

This document explains the concept of variables in programming, detailing their purpose as containers for storing and labeling data. It covers how to assign values to variables, the importance of naming them descriptively, and the concept of variable scope, which determines where variables can be accessed within a program. Additionally, it introduces the different types of variables in Ruby, including constants, global variables, class variables, instance variables, and local variables.

Uploaded by

nancydcit2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Variables

This document explains the concept of variables in programming, detailing their purpose as containers for storing and labeling data. It covers how to assign values to variables, the importance of naming them descriptively, and the concept of variable scope, which determines where variables can be accessed within a program. Additionally, it introduces the different types of variables in Ruby, including constants, global variables, class variables, instance variables, and local variables.

Uploaded by

nancydcit2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Variables

What is a Variable?
Variables are used to store information to be referenced and
manipulated in a computer program. They also provide a way of labeling
data with a descriptive name, so our programs can be understood more
clearly by the reader and ourselves. It is helpful to think of variables as
containers that hold information. Their sole purpose is to label and store
data in memory. This data can then be used throughout your program.

Assigning Value to Variables


Naming variables is known as one of the most difficult tasks in computer
programming. When you are naming variables, think hard about the
names. Try your best to make sure that the name you assign your
variable is accurately descriptive and understandable to another reader.
Sometimes that other reader is yourself when you revisit a program that
you wrote months or even years earlier.

When you assign a variable, you use the = symbol. The name of the
variable goes on the left and the value you want to store in the variable
goes on the right.

irb :001 > first_name = 'Joe'


=> "Joe"

Here we've assigned the value 'Joe' , which is a string, to the


variable first_name . Now if we want to reference that variable, we can.

irb :002 > first_name


=> "Joe"

As you can see, we've now stored the string 'Joe' in memory for use
throughout the program.

Note: Make sure you don't confuse the assignment operator ( = ) with the
equality operator ( == ). The individual = symbol assigns value while
the == symbol checks if two things are equal.
Let's try a little something. Look at the following irb session.

irb :001 > a = 4


=> 4
irb :002 > b = a
=> 4
irb :003 > a = 7
=> 7

What is the value of b at this point? Take your best guess and then type
this session into irb to find out.

You'll notice that the value of b remains 4, while a was re-assigned to 7.


This shows that variables point to values in memory, and are not deeply
linked to each other. If this is confusing, don't worry, we'll have plenty of
exercises for you to complete that will make this information clear and
obvious. And when in doubt, always try it out in irb.

Getting Data from a User


Up until now, you've only been able to assign data to variables from
within the program. However, in the wild, you'll want other people to be
able to interact with your programs in interesting ways. In order to do
that, we have to allow the user to store information in variables as well.
Then, we can decide what we'd like to do with that data.

One way to get information from the user is to call


the gets method. gets stands for "get string", and is a lot of fun. When you
use it, the program waits for the user to 1) type in information and 2)
press the enter key. Let's try it out. Type these examples in irb to get the
feel and play around with them for a bit if you'd like to.

irb :001 > name = gets


Bob
=> "Bob\n"

After the code, name = gets , the computer waited for us to type in some
information. We typed "Bob" and then pressed enter and the program
returned "Bob\n" . The \n at the end is the "newline" character and
represents the enter key. But we don't want that as part of our string.
We'll use chomp chained to gets to get rid of that - you can put .chomp after
any string to remove the carriage return characters at the end.
irb :001 > name = gets.chomp
Bob
=> "Bob"

There we go! That's much prettier. Now we can use the name variable as
we so please.

irb :001 > name = gets.chomp


Bob
=> "Bob"
irb :002 > name + ' is super great!'
=> "Bob is super great!"

Variable Scope
A variable's scope determines where in a program a variable is available
for use. A variable's scope is defined by where the variable is initialized or
created. In Ruby, variable scope is defined by a block. A block is a piece
of code following a method invocation, usually delimited by either curly
braces {} or do/end . Be aware that not all do/end pairs imply a block*.

Now that you have an idea of what constitutes a variable's scope, one rule
that we want you to remember is this:

Inner scope can access variables initialized in an outer scope, but


not vice versa.

Looking at some code will make this clearer. Let's say we have a file
called scope.rb .

# scope.rb

a = 5 # variable is initialized in the outer scope

3.times do |n| # method invocation with a block


a = 3 # is a accessible here, in an inner scope?
end

puts a
What is the value of a when it is printed to the screen? Try it out.

The value of a is 3. This is because a is available to the inner scope


created by 3.times do ... end , which allowed the code to re-assign the
value of a . In fact, it re-assigned it three times to 3. Let's try something
else. We'll modify the same piece of code.

# scope.rb

a = 5

3.times do |n| # method invocation with a block


a = 3
b = 5 # b is initialized in the inner scope
end

puts a
puts b # is b accessible here, in the outer scope?

What result did you get when running that program? You should have
gotten an error to the tune of:

scope.rb:11:in `<main>': undefined local variable or method


`b' for main:Object
(NameError)

This is because the variable b is not available outside of the method


invocation with a block where it is initialized. When we call puts b it is not
available within that outer scope.

* Note: the key distinguishing factor for deciding whether code delimited
by {} or do/end is considered a block (and thereby creates a new scope for
variables), is seeing if the {} or do/end immediately follows a method
invocation. For example:

arr = [1, 2, 3]

for i in arr do
a = 5 # a is initialized here
end
puts a # is it accessible here?

The answer is yes. The reason is because the for...do/end code


did not create a new inner scope, since for is part of Ruby language and
not a method invocation. When we use each , times and other method
invocations, followed by {} or do/end , that's when a new block is created.

Types of Variables
Before we move on, you should be aware that there are five types of
variables. Constants, global variables, class variables, instance variables,
and local variables. While you should not worry too much about these
topics in depth yet, here is a brief description of each.

Constants are declared by capitalizing every letter in the variable's name.


They are used for storing data that never needs to change. While most
programming languages do not allow you to change the value assigned to
a constant, Ruby does. It will however throw a warning letting you know
that there was a previous definition for that variable. Just because you
can, doesn't mean you should change the value. In fact, you should not.
Constants cannot be declared in method definitions, and are available
throughout your application's scopes.

Example of a constant declaration:

MY_CONSTANT = 'I am available throughout your app.'

Global variables are declared by starting the variable name with the dollar
sign ( $ ). These variables are available throughout your entire app,
overriding all scope boundaries. Rubyists tend to stay away from global
variables as there can be unexpected complications when using them.

Example of a global variable declaration:

$var = 'I am also available throughout your app.'

Class variables are declared by starting the variable name with


two @ signs. These variables are accessible by instances of your class, as
well as the class itself. When you need to declare a variable that is
related to a class, but each instance of that class does not need its own
value for this variable, you use a class variable. Class variables must be
initialized at the class level, outside of any method definitions. They can
then be altered using class or instance method definitions.

Example of a class variable declaration:

@@instances = 0

Instance variables are declared by starting the variable name with


one @ sign. These variables are available throughout the current instance
of the parent class. Instance variables can cross some scope boundaries,
but not all of them. You will learn more about this when you get to OOP
topics, and should not use instance variables until you know more about
them.

Example of an instance variable declaration:

@var = 'I am available throughout the current instance of this


class.'

Local variables are the most common variables you will come across and
obey all scope boundaries. These variables are declared by starting the
variable name with neither $ nor @ , as well as not capitalizing the entire
variable name.

Example of a local variable declaration:

var = 'I must be passed around to cross scope boundaries.'

Summary
In this chapter, we talked about how to use variables to store information
for later use and how to get information from a user. We also showed that
not all variables are created equal and that the scope in which a variable
is defined changes its availability throughout the program. Now that you
know the different types of variables and how to use them, let's put some
of that knowledge into practice with some exercises.
Exercises
1. Write a program called name.rb that asks the user to type in their
name and then prints out a greeting message with their name
included.

Solution
Video Walkthrough

2. Write a program called age.rb that asks a user how old they are and
then tells them how old they will be in 10, 20, 30 and 40 years.
Below is the output for someone 20 years old.

3. # output of age.rb for someone 20 yrs old


4.
5. How old are you?
6. In 10 years you will be:
7. 30
8. In 20 years you will be:
9. 40
10. In 30 years you will be:
11. 50
12. In 40 years you will be:
13. 60

Solution
Video Walkthrough

14. Add another section onto name.rb that prints the name of the
user 10 times. You must do this without explicitly writing the puts
method 10 times in a row. Hint: you can use the times method to do
something repeatedly.

Solution
Video Walkthrough

15. Modify name.rb again so that it first asks the user for their first
name, saves it into a variable, and then does the same for the last
name. Then outputs their full name all at once.

Solution
Video Walkthrough

16. Look at the following programs...


17. x = 0
18. 3.times do
19. x += 1
20. end
21. puts x

and...

y = 0
3.times do
y += 1
x = y
end
puts x

Variables
What is a Variable?
Variables are used to store information to be referenced and
manipulated in a computer program. They also provide a way of labeling
data with a descriptive name, so our programs can be understood more
clearly by the reader and ourselves. It is helpful to think of variables as
containers that hold information. Their sole purpose is to label and store
data in memory. This data can then be used throughout your program.

Assigning Value to Variables


Naming variables is known as one of the most difficult tasks in computer
programming. When you are naming variables, think hard about the
names. Try your best to make sure that the name you assign your
variable is accurately descriptive and understandable to another reader.
Sometimes that other reader is yourself when you revisit a program that
you wrote months or even years earlier.

When you assign a variable, you use the = symbol. The name of the
variable goes on the left and the value you want to store in the variable
goes on the right.
irb :001 > first_name = 'Joe'
=> "Joe"

Here we've assigned the value 'Joe' , which is a string, to the


variable first_name . Now if we want to reference that variable, we can.

irb :002 > first_name


=> "Joe"

As you can see, we've now stored the string 'Joe' in memory for use
throughout the program.

Note: Make sure you don't confuse the assignment operator ( = ) with the
equality operator ( == ). The individual = symbol assigns value while
the == symbol checks if two things are equal.

Let's try a little something. Look at the following irb session.

irb :001 > a = 4


=> 4
irb :002 > b = a
=> 4
irb :003 > a = 7
=> 7

What is the value of b at this point? Take your best guess and then type
this session into irb to find out.

You'll notice that the value of b remains 4, while a was re-assigned to 7.


This shows that variables point to values in memory, and are not deeply
linked to each other. If this is confusing, don't worry, we'll have plenty of
exercises for you to complete that will make this information clear and
obvious. And when in doubt, always try it out in irb.

Getting Data from a User


Up until now, you've only been able to assign data to variables from
within the program. However, in the wild, you'll want other people to be
able to interact with your programs in interesting ways. In order to do
that, we have to allow the user to store information in variables as well.
Then, we can decide what we'd like to do with that data.

One way to get information from the user is to call


the gets method. gets stands for "get string", and is a lot of fun. When you
use it, the program waits for the user to 1) type in information and 2)
press the enter key. Let's try it out. Type these examples in irb to get the
feel and play around with them for a bit if you'd like to.

irb :001 > name = gets


Bob
=> "Bob\n"

After the code, name = gets , the computer waited for us to type in some
information. We typed "Bob" and then pressed enter and the program
returned "Bob\n" . The \n at the end is the "newline" character and
represents the enter key. But we don't want that as part of our string.
We'll use chomp chained to gets to get rid of that - you can put .chomp after
any string to remove the carriage return characters at the end.

irb :001 > name = gets.chomp


Bob
=> "Bob"

There we go! That's much prettier. Now we can use the name variable as
we so please.

irb :001 > name = gets.chomp


Bob
=> "Bob"
irb :002 > name + ' is super great!'
=> "Bob is super great!"

Variable Scope
A variable's scope determines where in a program a variable is available
for use. A variable's scope is defined by where the variable is initialized or
created. In Ruby, variable scope is defined by a block. A block is a piece
of code following a method invocation, usually delimited by either curly
braces {} or do/end . Be aware that not all do/end pairs imply a block*.
Now that you have an idea of what constitutes a variable's scope, one rule
that we want you to remember is this:

Inner scope can access variables initialized in an outer scope, but


not vice versa.

Looking at some code will make this clearer. Let's say we have a file
called scope.rb .

# scope.rb

a = 5 # variable is initialized in the outer scope

3.times do |n| # method invocation with a block


a = 3 # is a accessible here, in an inner scope?
end

puts a

What is the value of a when it is printed to the screen? Try it out.

The value of a is 3. This is because a is available to the inner scope


created by 3.times do ... end , which allowed the code to re-assign the
value of a . In fact, it re-assigned it three times to 3. Let's try something
else. We'll modify the same piece of code.

# scope.rb

a = 5

3.times do |n| # method invocation with a block


a = 3
b = 5 # b is initialized in the inner scope
end

puts a
puts b # is b accessible here, in the outer scope?

What result did you get when running that program? You should have
gotten an error to the tune of:
scope.rb:11:in `<main>': undefined local variable or method
`b' for main:Object
(NameError)

This is because the variable b is not available outside of the method


invocation with a block where it is initialized. When we call puts b it is not
available within that outer scope.

* Note: the key distinguishing factor for deciding whether code delimited
by {} or do/end is considered a block (and thereby creates a new scope for
variables), is seeing if the {} or do/end immediately follows a method
invocation. For example:

arr = [1, 2, 3]

for i in arr do
a = 5 # a is initialized here
end

puts a # is it accessible here?

The answer is yes. The reason is because the for...do/end code


did not create a new inner scope, since for is part of Ruby language and
not a method invocation. When we use each , times and other method
invocations, followed by {} or do/end , that's when a new block is created.

Types of Variables
Before we move on, you should be aware that there are five types of
variables. Constants, global variables, class variables, instance variables,
and local variables. While you should not worry too much about these
topics in depth yet, here is a brief description of each.

Constants are declared by capitalizing every letter in the variable's name.


They are used for storing data that never needs to change. While most
programming languages do not allow you to change the value assigned to
a constant, Ruby does. It will however throw a warning letting you know
that there was a previous definition for that variable. Just because you
can, doesn't mean you should change the value. In fact, you should not.
Constants cannot be declared in method definitions, and are available
throughout your application's scopes.
Example of a constant declaration:

MY_CONSTANT = 'I am available throughout your app.'

Global variables are declared by starting the variable name with the dollar
sign ( $ ). These variables are available throughout your entire app,
overriding all scope boundaries. Rubyists tend to stay away from global
variables as there can be unexpected complications when using them.

Example of a global variable declaration:

$var = 'I am also available throughout your app.'

Class variables are declared by starting the variable name with


two @ signs. These variables are accessible by instances of your class, as
well as the class itself. When you need to declare a variable that is
related to a class, but each instance of that class does not need its own
value for this variable, you use a class variable. Class variables must be
initialized at the class level, outside of any method definitions. They can
then be altered using class or instance method definitions.

Example of a class variable declaration:

@@instances = 0

Instance variables are declared by starting the variable name with


one @ sign. These variables are available throughout the current instance
of the parent class. Instance variables can cross some scope boundaries,
but not all of them. You will learn more about this when you get to OOP
topics, and should not use instance variables until you know more about
them.

Example of an instance variable declaration:

@var = 'I am available throughout the current instance of this


class.'

Local variables are the most common variables you will come across and
obey all scope boundaries. These variables are declared by starting the
variable name with neither $ nor @ , as well as not capitalizing the entire
variable name.

Example of a local variable declaration:

var = 'I must be passed around to cross scope boundaries.'

Summary
In this chapter, we talked about how to use variables to store information
for later use and how to get information from a user. We also showed that
not all variables are created equal and that the scope in which a variable
is defined changes its availability throughout the program. Now that you
know the different types of variables and how to use them, let's put some
of that knowledge into practice with some exercises.

Exercises
1. Write a program called name.rb that asks the user to type in their
name and then prints out a greeting message with their name
included.

Solution
Video Walkthrough

2. Write a program called age.rb that asks a user how old they are and
then tells them how old they will be in 10, 20, 30 and 40 years.
Below is the output for someone 20 years old.

3. # output of age.rb for someone 20 yrs old


4.
5. How old are you?
6. In 10 years you will be:
7. 30
8. In 20 years you will be:
9. 40
10. In 30 years you will be:
11. 50
12. In 40 years you will be:
13. 60

Solution
Video Walkthrough

14. Add another section onto name.rb that prints the name of the
user 10 times. You must do this without explicitly writing the puts
method 10 times in a row. Hint: you can use the times method to do
something repeatedly.

Solution
Video Walkthrough

15. Modify name.rb again so that it first asks the user for their first
name, saves it into a variable, and then does the same for the last
name. Then outputs their full name all at once.

Solution
Video Walkthrough

16. Look at the following programs...

17. x = 0
18. 3.times do
19. x += 1
20. end
21. puts x

and...

y = 0
3.times do
y += 1
x = y
end
puts x

Variables
A variable is a symbolic name for (or reference to) information. The
variable's namerepresents what information the variable contains. They are
called variables because the represented information can change but
the operations on the variable remain the same. In general, a program
should be written with "Symbolic" notation, such that a statement is always
true symbolically. For example if I want to know the average of two
grades, We can write "average = (grade_1 + grade_2) / 2.0;" and the
variable average will then contain the average grade regardless of the scores
stored in the variables, grade_1 and grade_2.

Variables - Symbolic Nature


Variables in a computer program are analogous to "Buckets" or "Envelopes" where
information can be maintained and referenced. On the outside of the bucket is a name.
When referring to the bucket, we use the name of the bucket, not the data stored in the
bucket.

Variables are "Symbolic Names". This means the variable "stands in" for any
possible values. This is similar to mathematics, where it is always true that if given
two positive numbers (lets use the symbols 'a' and 'b' to represent them):

a + b > a

(i.e., if you add any two numbers, the sum is greater than one of the numbers by
itself).

This is called Symbolic Expression, again meaning, when any possible (valid) values
are used in place of the variables, the expression is still true.

Another example, if we want to find the sum of ANY TWO NUMBERS we can
write:

result = a + b;

Both 'a' and 'b' are variables. They are symbolic representations of any numbers. For
example, the variable 'a' could contain the number 5 and the variable 'b' could contain
the number 10. During execution of the program, the statement "a + b" is replaced by
the Actual Values "5 + 10" and the result becomes 15. The beauty (and
responsibility) of variables is that the symbolic operation should be true for any
values.

Another example, if we want to find out how many centimeters tall a person is, we
could use the following formula: height in centimeters = height in inches * 2.54.

This formula is always true. It doesn't matter if its Joe's height in inches or Jane's
height in inches. The formula works regardless. In computer terminology we would
use:

height_in_centimeters = height_in_inches * 2.54;

% the variable height_in_centimeters is assigned a


% new value based on the current value of "height_in_inches"
% multiplied by 2.54

Variable actions
There are only a few things you can do with a variable:

1. Create one (with a nice name). A variable should be named to represent all
possible values that it might contain. Some examples are: midterm_score,
midterm_scores, data_points, course_name, etc.

2. Put some information into it (destroying whatever was there before).

We "put" information into a variable using the assignment operator, e.g.,


midterm_score = 93;

3. Get a copy of the information out of it (leaving a copy inside)

We "get" the information out by simply writing the name of the variable, the
computer does the rest for us, e.g., average = (grade_1 + grade_2) / 2.
Examples of Usage
Below are some examples of how to use variables:

Matlab
C, Java
ActionScript

age = 15; % set the users age


age_in_months = age * 12; % compute the users age in months
age_in_days = age_in_months * 30; % compute the approximate age i
n days

student_name = 'jim'; % create a string (array of characters)

grades = [77, 95, 88, 47]; % create an arary

Variable Properties
There are 6 properties associated with a variable. The first three are very important as
you start to program. The last three are important as you advance and improve your
skills (and the complexity of the programs you are creating).

Memorize These!

1. A Name
2. A Type
3. A Value
4. A Scope
5. A Life Time
6. A Location (in Memory)

Clarification of Properties
1. A Name
The name is Symbolic. It represents the "title" of the information that is
being stored with the variable.

The name is perhaps the most important property to the programmer, because
this is how we "access" the variable. Every variable must have a unique name!

2. A Type

The type represents what "kind" of data is stored with the variable. (See the
Chapter on Data Types).

In C, Java, ActionScript, etc, the type of a variable must be explicitly declared


when the name is created.

In Matlab, the type of the variable is inferred from the data put into the
variable.

3. A Value

A variable, by its very name, changes over time. Thus if the variable
is jims_age and is assigned the value 21. At another point, jims_age may be
assigned the value 27.

Default Values

Most of the time, when you "create a variable" you are primarily defining the
variables name and type. Often (and the best programming practice) you will
want to provide an initial value to be associated with that variable name. If
you forget to assign an initial value, then various rules "kick in" depending on
the language.

Here are the basics:

Matlab
The C Language
ActionScript

In Matlab you cannot create a variable without giving it a value. The very act of
creation is associated with an assignment into the variable.
age = 20; % this creates a variable named
age with the value 20 (and type Number (double))

fprintf('age is %f\n'); % answer: age is


20

4. A Scope

Good programs are "Chopped" into small self contained sections (called
functions) much like a good novel is broken into chapters, and a good chapter
is broken into paragraphs, etc. A variable that is seen and used in one function
is NOT available in another section. This allows us to reuse variable names,
such as age. In one function 'age' could refer to the age of a student, and in
another function 'age' could refer to the vintage of a fine wine.

Further this prevents us from "accidentally" changing information that is


important to another part of our program.

5. A Life Time

The life time of a variable is strongly related to the scope of the variable. When
a program begins, variables "come to life" when the program reaches the line of
code where they are "declared". Variables "die" when the program leaves the
"Scope" of the variable.

In our initial programs (which do not have functions), the life time and scope of
the variables will be the "entire program".

6. A Location (in Memory)

Luckily, we don't have to worry too much about where in the computer
hardware the variable is stored. The computer (Matlab/C/Actionscript, etc., via
the compiler) does this for us.

But you should be aware that a "Bucket" or "Envelope" exists in the hardware
for every variable you declare. In the case of an array, a "bunch of buckets"
exist. Every bucket can contain a single value.
Legal Variable Names
 Start with a letter
 Use _ (underscores) for clarity
 Can use numbers
 Don't use special symbols
 Don't have spaces
 Have meaningful Names

Good Variable Names


Good variable names tell you, your teammates, (and your TA) what information is
"stored" inside that variable. They should make sense to a non computer programmer.
For example:

g = -9.81; % bad

gravitational_constant = -9.81; % good

The Name _vs_ the contained information


The Name of the variable is not the information! The name is a title of the
envelope/bucket, the information is contained in the envelope/bucket. The variable
can contain different pieces of information at different times.

The information in the variable should be easily manipulated:


class_size = 95; % good:

tas_per_student = class_size / 3;

Notice that we can use class_size in math expressions.

% bad: Cannot Change value to represent new student


s (or those who withdraw!)
class_size_is_95 = true;

tas_per_student = ????? !!! Cannot access the 95 value

Notice that we cannot use class_size in math expressions.

This version of the variable would tell a "person" what the class size is,
but would not make that info available to the computer.

 Remember, the variable should contain information (Not be the information)


and the information should be easy to change.

 The good way to change class size:


class_size = 100; % new value for _same_ variable

 The bad way to change the class size:


"Declare another variable"

class_size_is_100 = true;

Now we have both class_size_is_100 and class_size_is_95 set to true!!! How


bad is that?

 One more example:


the_profs_name = 'jim'; % GOOD
the_prof_is_jim = true; % BAD

Vocabulary:
 "Access" a variable.

To access a variable is to "read" (or assign) the information inside the variable.

To access a variable, you simply type its name.

For example: total_age = jims_age + jens_age;

 To Access an Array

To access an array is to "read" from or "store" to a single "bucket" of the array:

Matlab
C Language, Java, ActionScript
% In Matlab, Arrays start at index 1
% In Matlab, Arrays are indexed using parentheses
()
% Thus in Matlab:

quiz_grades(1) = 98;
average_quiz_score = ( quiz_grade(1) + quiz_grad
e(2) + quiz_grade(3) ) / 3.0;

Notice how very similar the syntax is. More importantly, notice that the "SEMANTICS" is the
same.

 "Assign" a value to a variable.

When you assign a value to a variable, you replace the old value with a new
one. The old value is gone forever. You can, and often do, replace the old value
of a variable based on the current value of the variable. See the example below:

number_of_students = number_of_students + 1;

Here we:

1. first, the computer looks at the "right hand side" of the line (after the
equals). Then the computer gets the value found in the variable
"number_of_students"
2. then, the computer adds one to this value
3. finally, the computer stores the new sum in the variable on the "left
hand side" of the equals, which in this case happens to be
"number_of_students" (thus replacing the old value with a new value)

 "Declare" a variable.

To declare a variable is to create the variable.


In Matlab, you declare a variable by simply writing its name and assigning it a
value. (e.g., 'jims_age = 21;').

In C, Java you declare a variable by writing its TYPE followed by its name
and assigning it a value. (e.g., 'int jims_age = 21;').

In ActionScript declare a variable by writing "var" followed by the name of the


variable, followed by a colon, followed by the TYPE. (e.g., var jims_age : int =
21;').

 "Initialize" a variable.

Initializing a variable is another way to say, "declare a variable", but further,


implies giving it a base value.

For example, if we are plotting something on the X/Y axes, and we want to
start at zero for Z, we would say ("x = 0;"). Thus we have "initialized" the x
variable to the value 0.

 "Stored" in a variable.

The information "stored" in a variable, is the last piece of information assigned


to that variable name. After assigning into a variable, all previous information
is lost.

Note, we often use the statement "store the value 5 in X" to mean the same as
"assign the value 5 to X"

Variables are the names you give to computer memory locations which are
used to store values in a computer program.

For example, assume you want to store two values 10 and 20 in your
program and at a later stage, you want to use these two values. Let's see
how you will do it. Here are the following three simple steps −
 Create variables with appropriate names.

 Store your values in those two variables.

 Retrieve and use the stored values from the variables.

Creating variables
Creating variables is also called declaring variables in C programming.
Different programming languages have different ways of creating variables
inside a program. For example, C programming has the following simple
way of creating variables −

#include <stdio.h>

int main() {

int a;

int b;

The above program creates two variables to reserve two memory locations
with names a and b. We created these variables using int keyword to
specify variable data type which means we want to store integer values in
these two variables. Similarly, you can create variables to
store long, float, char or any other data type. For example −

/* variable to store long value */

long a;

/* variable to store float value */

float b;

You can create variables of similar type by putting them in a single line but
separated by comma as follows −

#include <stdio.h>
int main() {

int a, b;

Listed below are the key points about variables that you need to keep in
mind −

 A variable name can hold a single type of value. For example, if variable a has
been defined int type, then it can store only integer.

 C programming language requires a variable creation, i.e., declaration before its


usage in your program. You cannot use a variable name in your program without
creating it, though programming language like Python allows you to use a
variable name without creating it.

 You can use a variable name only once inside your program. For example, if a
variable a has been defined to store an integer value, then you cannot
define a again to store any other type of value.

 There are programming languages like Python, PHP, Perl, etc., which do not want
you to specify data type at the time of creating variables. So you can store
integer, float, or long without specifying their data type.

 You can give any name to a variable like age, sex, salary, year1990or
anything else you like to give, but most of the programming languages allow to
use only limited characters in their variables names. For now, we will suggest to
use only a....z, A....Z, 0....9 in your variable names and start their names
using alphabets only instead of digits.

 Almost none of the programming languages allow to start their variable names
with a digit, so 1990year will not be a valid variable name
whereas year1990 or ye1990ar are valid variable names.

Every programming language provides more rules related to variables and


you will learn them when you will go in further detail of that programming
language.

Store Values in Variables


You have seen how we created variables in the previous section. Now, let's
store some values in those variables −
#include <stdio.h>

int main() {

int a;

int b;

a = 10;

b = 20;

The above program has two additional statements where we are storing 10
in variable a and 20 is being stored in variable b. Almost all the
programming languages have similar way of storing values in variable
where we keep variable name in the left hand side of an equal sign = and
whatever value we want to store in the variable, we keep that value in the
right hand side.

Now, we have completed two steps, first we created two variables and then
we stored required values in those variables. Now variable a has value 10
and variable b has value 20. In other words we can say, when above
program is executed, the memory location named a will hold 10 and
memory location bwill hold 20.

Access stored values in variables


If we do not use the stored values in the variables, then there is no point in
creating variables and storing values in them. We know that the above
program has two variables a and b and they store the values 10 and 20,
respectively. So let's try to print the values stored in these two variables.
Following is a C program, which prints the values stored in its variables −
Live Demo

#include <stdio.h>

int main() {
int a;

int b;

a = 10;

b = 20;

printf( "Value of a = %d\n", a );

printf( "Value of b = %d\n", b );

When the above program is executed, it produces the following result −


Value of a = 10
Value of b = 20

You must have seen printf() function in the previous chapter where we had
used it to print "Hello, World!". This time, we are using it to print the values
of variables. We are making use of %d, which will be replaced with the
values of the given variable in printf() statements. We can print both the
values using a single printf() statement as follows −
Live Demo

#include <stdio.h>

int main() {

int a;

int b;

a = 10;

b = 20;

printf( "Value of a = %d and value of b = %d\n", a, b );


}

When the above program is executed, it produces the following result −


Value of a = 10 and value of b = 20

If you want to use float variable in C programming, then you will have to
use %f instead of %d, and if you want to print a character value, then you
will have to use %c. Similarly, different data types can be printed using
different % and characters.

You might also like