We have already study Classification of data , now we will study the mechanism for storing them.
# C Variables Store world inside your Computer
As a programmer, you will frequently want your program to “remember” a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later.
When we want to store any information(data) on our computer/laptop, we store it in the computer's memory space. Instead of remembering the complex address of that memory space where we have stored our data, our operating system provides us with an option to create folders, name them, so that it becomes easier for us to find it and access it.
Similarly, in C language, when we want to use some data value in our program, we can store it in a memory space and name the memory space so that it becomes easier to access it.
The naming of an address is known as variable. Variable is the name of memory location.
A programmer can choose a meaningful variable name. Example : average, height, age, total etc.
Q) What is identifier in below code ?
int c = 0 ;
Hint: Name given to variables , function etc
# Defining a variable
To define a variable we must provide the datatype and the variable name.
datatypes variable_name ;
Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can hold only integer values.
We can even define multiple variables of same datatype in a single line by using comma to separate them.
float b, c;
# Initializing a variable
Initializing a variable means to provide it with a value.
variable_name = value;
x = 10;
A variable can be initialized and defined in a single statement, like:
int x = 10;
# Printing a variable
The following line shows how to output the value of a variable using printf.
printf ("%d " , b);
The %d is a placeholder that will be replaced by the value of the variable b when the printf statement is executed. Often, you will want to embed the value within some other words. One way to accomplish that is like this:
printf("The temperature is"); printf("% d" ,b); printf("degrees \n");
An easier way is to say this:
printf("The temperature is %d degrees \ n " , b );
You can also use multiple %d placeholders in one printf statement:
printf("%d + %d = %d \ n" , a , b , c );
You can print all of the normal C types with printf by using different placeholders:
- int (integer values) uses %d
- float (floating point values) uses %f
- char (single character values) uses %c
- character strings (arrays of characters, discussed later) use %s
- Declare and initialize 3 variable of each datatypes (not of string) with random value and print each of them using multiple placeholder
# Hint :
put the value of character inside 'value'
- Print the following output
Name : A Age : 20 Income : 0.00
# Hint :
printf("Name : %c \n" , name); printf("Income : %f \n" , income);