C Variables
- Variables stores data values for temporary period of time.
- C language has different types of variables.
- int - stores integers , such as 120, -110
- float - stores decimals floating point numbers , such as 16.55,-16.55
- char - stores single characters , such as 'a ' , 'B'
Syntax
type variablename = value;
Example 1;
int Number1 = 20;
Example 2;
// Declare a variable
int Number1;
// Assign a value to the variable
Number = 20;
C Format specifiers
- Format specifiers use together printf() function tell compiler type of data variable storing.
- Place holder is also called the variable value.
- Format specifier is indicated by the character "%".
Example;
#include <stdio.h>
int main(){
int Number1=15;
printf("%d", Number);// Output is 20
return 0;
}
- int - Format specifier is "%d"
- char - Format specifier is "%c"
- float - Format specifier is "%f "
Example;
#include <stdio.h>
int main(){
//Create variables
int Number = 20;
float FloatNumber = 10.55;
char Letter = 'A';
// Print variables
printf("%d\n", Number);
printf("%f\n", FloatNumber);
printf("%c\n", Letter);
return 0;
}
Change Variable Values
Example;
#include <stdio.h>
int main(){
int Number = 20; // Number is 20
Number = 10;// Now Number is 10
printf("%d" , Number);
return 0;
}
Example;
#include <stdio.h>
int main(){
int Number = 20;
int OtherNumber = 10;
// Assign the value of OtherNumber (10) to Number
Number = OtherNumber;
// Number is now 10, instead of 20
printf("%d", Number);
return 0;
}
C Multiple variables
- To declare more than one variable of the same data type using a comma.
Example;
#include <stdio.h>
int main(){
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
return 0;
}
C Variable Names (Identifiers)
Example;
#include <stdio.h>
int main() {
// Meaningful variable name
int minutesPerHour = 60;
// Using letters for variable names are not easy to understand what m actually us
int m = 60;
printf("%d\n", minutesPerHour);
printf("%d" , m);
return 0;
}
General rules for naming variables are ;
- Can contain letters, digits and underscore.
- Must begin with a letter or underscore.
- Case sensitive such as, variable1, Variable.
- Reserved words can not be used as names such as, int.
No comments:
Post a Comment