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

Format Specifiers

Format Specifiers

Format specifiers, employed alongside the printf() function, inform the compiler about the data type stored in a variable.

Essentially, they act as a placeholder for the variable’s value.

A format specifier begins with a percentage sign %, succeeded by a character.

For instance, when printing the value of an integer variable, enclose the format specifier %d within double quotes ( “” ) within the printf() function.

Example

int myNum = 15;
printf(“%d”, myNum);  // Outputs 15 

For printing different types, utilize %c for char and %f for float: 

Example

// Create variables
int myNum = 15;            // Integer (whole number)
float myFloatNum = 5.99;   // Floating point number
char myLetter = ‘D’;       // Character

// Print variables
printf(“%d\n”, myNum);
printf(“%f\n”, myFloatNum);
printf(“%c\n”, myLetter); 

To incorporate both text and a variable into a printf() function, ensure they are divided by a comma within the parentheses.

Example

int myNum = 15;
printf(“My favorite number is: %d”, myNum); 
 
To output various data types within a single printf() function, you can employ the following technique:

Example

int myNum = 15;
char myLetter = ‘D’;
printf(“My number is %d and my letter is %c”, myNum, myLetter);

 

You will learn more about Data Types in a later chapter.