Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Create Variables

C Variables

Variables serve as containers for holding data values, such as numbers and characters.

In the C programming language, various types of variables are defined using distinct keywords.

  • “int” for storing integers (whole numbers) like 123 or -123
  • “float” for holding floating-point numbers with decimals, such as 19.99 or -19.99
  • “char” for storing single characters, like ‘a’ or ‘B’, enclosed within single quotes.

Declaring (Creating) Variables

To define a variable, indicate its type and assign it a value.

Syntax

type variableName = value

Where “type” represents one of the C data types (like int), and “variableName” is the identifier for the variable (such as x or myName).

The equal sign is employed for assigning a value to the variable.

To define a variable intended to store a number, consider the following example:

Example

Declare a variable named myNum with the type int and initialize it with the value 15.

int myNum = 15

It’s also possible to declare a variable without immediately assigning a value to it, and assign the value later on.

Example

// Declare a variable
int myNum;

// Assign a value to the variable
myNum = 15

Output Variables

You’ve discovered that you can output values or print text using the printf() function:

Example

printf(“Hello World!”); 

In numerous other programming languages such as Python, Java, and C++, it’s common to utilize a print function to showcase the value of a variable.

Nonetheless, this capability is not available in C.

Example

int myNum = 15;
printf(myNum);  // Nothing happens 

In order to display variables in C, it’s essential to become acquainted with a concept known as “format specifiers,” which will be covered in the upcoming chapter.