Utilizor
Contact Us
HomeC TutorialC Variables

CC Variables

Storing data.

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 (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

type variableName = value;

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.

  • %d or %i - prints an integer
  • %f - prints a float
  • %c - prints a character
  • %s - prints a string (text)

Examples

Create Variable

c example

Creating and printing an integer.

#include <stdio.h>

int main() {
  int myNum = 15;
  printf("%d", myNum);
  return 0;
}

Other Types

c example

Float and Char variables.

#include <stdio.h>

int main() {
  float myFloatNum = 5.99;
  char myLetter = 'D';
  printf("%f\n", myFloatNum);
  printf("%c\n", myLetter);
  return 0;
}

Combine Text and Variable

c example

Printing text with a variable.

#include <stdio.h>

int main() {
  int myNum = 15;
  printf("My favorite number is: %d", myNum);
  return 0;
}

Add Variables

c example

Adding two variables.

#include <stdio.h>

int main() {
  int x = 5;
  int y = 6;
  int sum = x + y;
  printf("%d", sum);
  return 0;
}

Declare Multiple Variables

c example

One line declaration.

#include <stdio.h>

int main() {
  int x = 5, y = 6, z = 50;
  printf("%d", x + y + z);
  return 0;
}

Test Your Knowledge

1. Which keyword creates an integer variable?

2. Which format specifier is used for integers?