C Tutorial/Language/Variable Declaration
Содержание
Define three variables and use assignment operator to assign value
int main()
{
int term; /* term used in two expressions */
int term_2; /* twice term */
int term_3; /* three times term */
term = 3 * 5;
term_2 = 2 * term;
term_3 = 3 * term;
return (0);
}
How to declare a variable
A variable declaration serves three purposes:
- It defines the name of the variable.
- It defines the type of the variable (integer, real, character, etc.).
- It gives the programmer a description of the variable.
int answer; /* the result of our expression */
- The keyword int tells C that this variable contains an integer value.
- The variable name is answer.
- The semicolon (;) marks the end of the statement.
- The comment is used to define this variable for the programmer.
Initialize int value in declaration
#include <stdio.h>
int main(void)
{
int number0 = 10, number1 = 40, number2 = 50, number3 = 80, number4 = 10;
int number5 = 20, number6 = 30, number7 = 60, number8 = 70, number9 = 110;
int sum = number0 + number1+ number2 + number3 + number4+
number5 + number6 + number7 + number8 + number9;
float average = (float)sum/10.0f;
printf("\nAverage of the ten numbers entered is: %f\n", average);
return 0;
}
Average of the ten numbers entered is: 48.000000
Meaningful variable name
int p,q,r;
Use printf to output variable
#include <stdio.h>
int main()
{
int term; /* term used in two expressions */
term = 3 * 5;
printf("Twice %d is %d\n", term, 2*term);
printf("Three times %d is %d\n", term, 3*term);
return (0);
}
Twice 15 is 30 Three times 15 is 45
The number of %d conversions should match the number of expressions.
Using a variable to store value
#include <stdio.h>
int main(void)
{
int salary;
salary = 10000;
printf("My salary is %d.", salary);
return 0;
}
My salary is 10000.
Variables
- You can store values in variables.
- Each variable is identified by a variable name.
- Each variable has a variable type.
- Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores.
- Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables.
- The variables are defined at the begining of the block.
The following is an example of some variable names:
average /* average of all grades */
pi /* pi to 6 decimal places */
number_of_students /* number students in this class */