C Variables
C Variables
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords),
for example:
int : stores integers such as 25,50;
float :stores floating point numbers such as 500.00;
char :Stores single character such as 'a' or ’B’
Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of
data the variable is storing.
It is basically a placeholder for the variable value.A format specifier starts with a percentage
sign %, followed by a character.
Example:
int Num = 50;
printf("%d", Num);
Data Types
As explained in the Variables chapter, a variable in C must be a specified data
type, and you must use a format specifier inside the printf() function to display it:
Example:
// Create variables
int myNum = 5;
float myFloatNum = 5.99;
char myLetter = 'D';
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
Basic Data Types
The data type specifies the size and type of information the variable will store.
In this tutorial, we will focus on the most basic ones:
Data Type Size Description Example
Example
int myNum = 100 + 50;
Operator Name Description Example
Syntax
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Switch Example
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
Syntax
while (condition) {
// code block to be executed
}
Example:
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Do While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Example
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop
Syntax
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Example
int i;
Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of
a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the for loop when i is equal to 4:
Example
int i;
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the
next iteration in the loop.
This example skips the value of 4:
Example
int i;