Search

C programming Language

 

Dennis Ritchie - founder of C language
History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of the c language.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in      the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPInitially, C language was developed to be used in UNIX operating system. It inherits many features of previous languages such as B and BCPL.


LanguageYearDeveloped By
Algol

1960

International Group

BCPL

1967

Martin Richard

B

1970

Ken Thompson

Traditional C

1972

Dennis Ritchie

K & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee


Features of C Language


C is the widely used language. It provides many features that are given below.

  1. Simple
  2. Machine Independent or Portable
  3. Mid-level programming language
  4. structured programming language
  5. Rich Library
  6. Memory Management
  7. Fast Speed

    C features

  8. Pointers
  9. Recursion
  10. Extensible

1) Simple

C is a simple language in the sense that it provides a structured approach (to break the problem into parts), the rich set of library functionsdata types, etc.


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different machines with some machine specific changes. Therefore, C is a machine independent language.


3) Mid-level programming language

Although, C is intended to do low-level programming. It is used to develop system applications such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is known as mid-level language.


First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.

To write the first c program, open the C console and write the following code:


  1. #include <stdio.h>    
  2. int main(){    
  3. printf("Hello C Language");    
  4. return 0;   
  5. }  


#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .


int main() The main() function is the entry point of every program in C language.


Compilation process in c

What is a compilation?

The compilation is a process of converting the source code into object code. It is done with the help of the compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code is error-free, then it generates the object code.


Compilation process in c


The c compilation process converts the source code taken as input into the object code or machine code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the source code. The preprocessor takes the preprocessor directive and interprets it. For example, if <stdio.h>, the directive is available in the program, then the preprocessor interprets the directive and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into an executable form:

  • Preprocessor
  • Compiler
  • Assembler
  • Linker
Compilation process in c

Preprocessor

The source code is the code which is written in a text editor and the source code file is given an extension ".c". This source code is first passed to the preprocessor, and then the preprocessor expands this code. After expanding the code, the expanded code is passed to the compiler.

Compiler

The code which is expanded by the preprocessor is passed to the compiler. The compiler converts this code into assembly code. Or we can say that the C compiler converts the pre-processed code into assembly code.

Assembler

The assembly code is converted into object code by using an assembler. The name of the object file generated by the assembler is the same as the source file. The extension of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the object file would be 'hello.obj'.

Linker

Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The main working of the linker is to combine the object code of library files with the object code of our program. Sometimes the situation arises when our program refers to the functions defined in other files; then linker plays a very important role in this. It links the object code of these files to our program. Therefore, we conclude that the job of the linker is to link the object code of our program with the object code of the library files and other files. The output of the linker is the executable file. The name of the executable file is the same as the source file but differs only in their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'. For example, if we are using printf() function in a program, then the linker adds its associated code in an output file.

Let's understand through an example.

hello.c

printf() and scanf() in C

The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

  1. printf("format string",argument_list);  

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

  1. scanf("format string",argument_list);  

Program to print cube of given number

Let's see a simple example of c language that gets input from the user and prints the cube of the given number.

  1. #include<stdio.h>    
  2. int main(){    
  3. int number;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);    
  6. printf("cube of number is:%d ",number*number*number);    
  7. return 0;  
  8. }    

Output

enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console and stores the given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on the console.

Program to print sum of 2 numbers

Let's see a simple example of input and output in C language that prints addition of 2 numbers.

  1. #include<stdio.h>    
  2. int main(){    
  3. int x=0,y=0,result=0;  
  4.   
  5. printf("enter first number:");  
  6. scanf("%d",&x);  
  7. printf("enter second number:");  
  8. scanf("%d",&y);  
  9.   
  10. result=x+y;  
  11. printf("sum of 2 numbers:%d ",result);  
  12.   
  13. return 0;  
  14. }    

Output

enter first number:9
enter second number:9
sum of 2 numbers:18


Variables in C

variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring the variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;//declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits, and underscore.
  • A variable name can start with the alphabet, and underscore only. It can't start with a digit.
  • No whitespace is allowed within the variable name.
  • A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

  1. int a;  
  2. int _ab;  
  3. int a30;  

Invalid variable names:

  1. int 2;  
  2. int a b;  
  3. int long;  

Types of Variables in C

There are many types of variables in c:

  1. local variable
  2. global variable
  3. static variable
  4. automatic variable
  5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

  1. void function1(){  
  2. int x=10;//local variable  
  3. }  

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

  1. int value=20;//global variable  
  2. void function1(){  
  3. int x=10;//local variable  
  4. }  

Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

  1. void function1(){  
  2. int x=10;//local variable  
  3. static int y=10;//static variable  
  4. x=x+1;  
  5. y=y+1;  
  6. printf("%d,%d",x,y);  
  7. }  


If you call this function many times, the local variable will print the same value for each function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using auto keyword.

  1. void main(){  
  2. int x=10;//local variable (also automatic)  
  3. auto int y=20;//automatic variable  
  4. }  

External Variable

We can share a variable in multiple C source files by using an external variable. To declare an external variable, you need to use extern keyword.


  1. extern int x=10;//external variable (also global)  

program1.c

  1. #include "myfile.h"  
  2. #include <stdio.h>  
  3. void printValue(){  
  4.     printf("Global variable: %d", global_variable);  
  5. }  


Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

C Data Types

There are the following data types in C language.

TypesData Types
Basic Data Typeint, char, float, double
Derived Data Typearray, pointer, structure, union
Enumeration Data Typeenum
Void Data Typevoid

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data TypesMemory SizeRange
char1 byte−128 to 127
signed char1 byte−128 to 127
unsigned char1 byte0 to 255
short2 byte−32,768 to 32,767
signed short2 byte−32,768 to 32,767
unsigned short2 byte0 to 65,535
int2 byte−32,768 to 32,767
signed int2 byte−32,768 to 32,767
unsigned int2 byte0 to 65,535
short int2 byte−32,768 to 32,767
signed short int2 byte−32,768 to 32,767
unsigned short int2 byte0 to 65,535
long int4 byte-2,147,483,648 to 2,147,483,647
signed long int4 byte-2,147,483,648 to 2,147,483,647
unsigned long int4 byte0 to 4,294,967,295
float4 byte
double8 byte
long double10 byte

Int:

Integers are entire numbers without any fractional or decimal parts, and the int data type is used to represent them.

It is frequently applied to variables that include values, such as counts, indices, or other numerical numbers. The int data type may represent both positive and negative numbers because it is signed by default.

An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2 billion and +2 billion.

Char:

Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256 characters that can be represented by a single char, which takes up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.

Float:

To represent integers, use the floating data type. Floating numbers can be used to represent fractional units or numbers with decimal places.

The float type is usually used for variables that require very good precision but may not be very precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4 x 1038 in 4 bytes of memory.

Double:

Use two data types to represent two floating integers. When additional precision is needed, such as in scientific calculations or financial applications, it provides greater accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields larger values. C treats floating point numbers as doubles by default if no explicit type is supplied.

  1. int age = 25;  
  2. char grade = 'A';  
  3. float temperature = 98.6;  
  4. double pi = 3.14159265359;  

In the example above, we declare four variables: an int variable for the person's age, a char variable for the student's grade, a float variable for the temperature reading, and two variables for the number pi.

Derived Data Type

Beyond the fundamental data types, C also supports derived data types, including arrays, pointers, structures, and unions. These data types give programmers the ability to handle heterogeneous data, directly modify memory, and build complicated data structures.

Array:

An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It provides a mechanism for joining multiple targets of the same data under the same name.

The index is used to access the elements of the array, with a 0 index for the first entry. The size of the array is fixed at declaration time and cannot be changed during program execution. The array components are placed in adjacent memory regions.

Here is an example of declaring and utilizing an array:

  1. #include <stdio.h>  
  2.    
  3. int main() {  
  4.     int numbers[5]; // Declares an integer array with a size of 5 elements  
  5.    
  6.     // Assign values to the array elements  
  7.     numbers[0] = 10;  
  8.     numbers[1] = 20;  
  9.     numbers[2] = 30;  
  10.     numbers[3] = 40;  
  11.     numbers[4] = 50;  
  12.    
  13.     // Display the values stored in the array  
  14.     printf("Values in the array: ");  
  15.     for (int i = 0; i < 5; i++) {  
  16.         printf("%d ", numbers[i]);  
  17.     }  
  18.     printf("\n");  
  19.    
  20.     return 0;  
  21. }  

Output:

Values in the array: 10 20 30 40 50

Pointer:

pointer is a derived data type that keeps track of another data type's memory address. When a pointer is declared, the data type it refers to is stated first, and then the variable name is preceded by an asterisk (*).

You can have incorrect access and change the value of variable using pointers by specifying the memory address of the variable. Pointers are commonly used in tasks such as function pointers, data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:

  1. #include <stdio.h>  
  2.    
  3. int main() {  
  4.     int num = 42;      // An integer variable  
  5.     int *ptr;          // Declares a pointer to an integer  
  6.    
  7.     ptr = #        // Assigns the address of 'num' to the pointer  
  8.    
  9.     // Accessing the value of 'num' using the pointer  
  10.     printf("Value of num: %d\n", *ptr);  
  11.    
  12.     return 0;  
  13. }  

Output:

Value of num: 42

Structure:

A structure is a derived data type that enables the creation of composite data types by allowing the grouping of many data types under a single name. It gives you the ability to create your own unique data structures by fusing together variables of various sorts.

  1. A structure's members or fields are used to refer to each variable within it.
  2. Any data type, including different structures, can be a member of a structure.
  3. A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:

  1. #include <stdio.h>  
  2. #include <string.h>   
  3. // Define a structure representing a person  
  4. struct Person {  
  5.     char name[50];  
  6.     int age;  
  7.     float height;  
  8. };  
  9.    
  10. int main() {  
  11.     // Declare a variable of type struct Person  
  12.     struct Person person1;  
  13.    
  14.     // Assign values to the structure members  
  15.     strcpy(person1.name, "John Doe");  
  16.     person1.age = 30;  
  17.     person1.height = 1.8;  
  18.    
  19.     // Accessing the structure members  
  20.     printf("Name: %s\n", person1.name);  
  21.     printf("Age: %d\n", person1.age);  
  22.     printf("Height: %.2f\n", person1.height);  
  23.    
  24.     return 0;  
  25. }  

Output:

Name: John Doe
Age: 30
Height: 1.80

Union:

A derived data type called a union enables you to store various data types in the same memory address. In contrast to structures, where each member has a separate memory space, members of a union all share a single memory space. A value can only be held by one member of a union at any given moment. When you need to represent many data types interchangeably, unions come in handy. Like structures, you can access the members of a union by using the dot (.) operator.

Here is an example of a union being declared and used:

  1. #include <stdio.h>  
  2. // Define a union representing a numeric value  
  3. union NumericValue {  
  4.     int intValue;  
  5.     float floatValue;  
  6.     char stringValue[20];  
  7. };  
  8. int main() {  
  9.     // Declare a variable of type union NumericValue  
  10.     union NumericValue value;  
  11.     // Assign a value to the union  
  12.     value.intValue = 42;  
  13.     // Accessing the union members  
  14.     printf("Integer Value: %d\n", value.intValue);  
  15.     // Assigning a different value to the union  
  16.     value.floatValue = 3.14;  
  17.     // Accessing the union members  
  18.     printf("Float Value: %.2f\n", value.floatValue);  
  19.    
  20.     return 0;  
  21. }  

Output:

Integer Value: 42
Float Value: 3.14

Enumeration Data Type

A set of named constants or enumerators that represent a collection of connected values can be defined in C using the enumeration data type (enum). Enumerations give you the means to give names that make sense to a group of integral values, which makes your code easier to read and maintain.

Here is an example of how to define and use an enumeration in C:

  1. #include <stdio.h>  
  2.    
  3. // Define an enumeration for days of the week  
  4. enum DaysOfWeek {  
  5.     Monday,  
  6.     Tuesday,  
  7.     Wednesday,  
  8.     Thursday,  
  9.     Friday,  
  10.     Saturday,  
  11.     Sunday  
  12. };  
  13.    
  14. int main() {  
  15.     // Declare a variable of type enum DaysOfWeek  
  16.     enum DaysOfWeek today;  
  17.    
  18.     // Assign a value from the enumeration  
  19.     today = Wednesday;  
  20.    
  21.     // Accessing the enumeration value  
  22.     printf("Today is %d\n", today);  
  23.    
  24.     return 0;  
  25. }  

Output:

Today is 2

Void Data Type

The void data type in the C language is used to denote the lack of a particular type. Function return types, function parameters, and pointers are three situations where it is frequently utilized.

Function Return Type:

void return type function does not produce a value. A void function executes a task or action and ends rather than returning a value.

Example:

  1. void printHello() { printf("Hello, world!\n"); }  

Function Parameters:

The parameter void can be used to indicate that a function accepts no arguments.

Example:

  1. void processInput(void) { /* Function logic */ }  

Pointers:

Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a method for working with pointers to ambiguous or atypical types.

Example:

  1. void* dataPtr;   

The void data type is helpful for defining functions that don't accept any arguments when working with generic pointers or when you wish to signal that a function doesn't return a value. It is significant to note that while void* can be used to build generic pointers, void itself cannot be declared as a variable type.

Here is a sample of code that shows how to utilize void in various situations:

  1. #include <stdio.h>  
  2. // Function with void return type  
  3. void printHello() {  
  4.     printf("Hello, world!\n");  
  5. }  
  6. // Function with void parameter  
  7. void processInput(void) {  
  8.     printf("Processing input...\n");  
  9. }  
  10.    
  11. int main() {  
  12.     // Calling a void function  
  13.     printHello();  
  14.    
  15.     // Calling a function with void parameter  
  16.     processInput();  
  17.    
  18.     // Using a void pointer  
  19.     int number = 10;  
  20.     void* dataPtr = &number;  
  21.     printf("Value of number: %d\n", *(int*)dataPtr);  
  22.    
  23.     return 0;  
  24. }  

Output:

Hello, world!
Processing input...
Value of number: 10

Conclusion:

As a result, data types are essential in the C programming language because they define the kinds of information that variables can hold. They provide the data's size and format, enabling the compiler to allot memory and carry out the necessary actions. Data types supported by C include void, enumeration, derived, and basic types. In addition to floating-point types like float and double, basic data types in C also include integer-based kinds like int, char, and short. These forms can be signed or unsigned, and they fluctuate in size and range. To create dependable and efficient code, it is crucial to comprehend the memory size and scope of these types.

A few examples of derived data types are unions, pointers, structures, and arrays. Multiple elements of the same kind can be stored together in contiguous memory due to arrays. Pointers keep track of memory addresses, allowing for fast data structure operations and dynamic memory allocation. While unions allow numerous variables to share the same memory space, structures group relevant variables together.

Code becomes more legible and maintainable when named constants are defined using enumeration data types. Enumerations give named constants integer values to enable the meaningful representation of related data. The void data type indicates the lack of a particular type. It is used as a return type for both functions and function parameters that don't take any arguments and don't return a value. The void* pointer also functions as a general pointer that can store addresses of various types.

C programming requires a solid understanding of data types. Programmers can ensure adequate memory allocation, avoid data overflow or truncation, and enhance the readability and maintainability of their code by selecting the right data type. C programmers may create effective, dependable, and well-structured code that satisfies the requirements of their applications by having a firm understanding of data types.


Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

autobreakcasecharconstcontinuedefaultdo
doubleelseenumexternfloatforgotoif
intlongregisterreturnshortsignedsizeofstatic
structswitchtypedefunionunsignedvoidvolatilewhile

We will learn about all the C language keywords later.

C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays, structures, unions, labels, etc. An identifier can be composed of letters such as uppercase, lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an underscore. If the identifier is not used in the external linkage, then it is called as an internal identifier. If the identifier is used in the external linkage, then it is called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with an alphabetical character or an underscore, which are used to represent various programming elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters (uppercase and lowercase), underscore character, and ten numerical digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers

  • The first character of an identifier should be either an alphabet or an underscore, and then it can be followed by any of the character, digit, or underscore.
  • It should not begin with any numerical digit.
  • In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive.
  • Commas or blank spaces cannot be specified within an identifier.
  • Keywords cannot be represented as an identifier.
  • The length of the identifiers should not be more than 31 characters.
  • Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

  1. total, sum, average, _m _, sum_1, etc.  

Example of invalid identifier

  1. 2sum (starts with a numerical digit)  
  2. int (reserved word)  
  3. char (reserved word)  
  4. m+n (special character, i.e., '+')  

Types of identifiers

  • Internal identifier
  • External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier. The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The external identifiers can be function names, global variables.

Differences between Keyword and Identifier

KeywordIdentifier
Keyword is a pre-defined word.The identifier is a user-defined word
It must be written in a lowercase letter.It can be written in both lowercase and uppercase letters.
Its meaning is pre-defined in the c compiler.Its meaning is not defined in the c compiler.
It is a combination of alphabetical characters.It is a combination of alphanumeric characters.
It does not contain the underscore character.It can contain the underscore character.

Let's understand through an example.

  1. int main()  
  2. {  
  3.     int a=10;  
  4.     int A=20;  
  5.     printf("Value of a is : %d",a);  
  6.     printf("\nValue of A is :%d",A);  
  7.     return 0;  
  8. }  

Output

Value of a is : 10
Value of A is :20  

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we conclude that the identifiers are case sensitive.



C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary or Conditional Operators
  • Assignment Operator
  • Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operator direction to be evaluated; it may be left to right or right to left.

Let's understand the precedence by the example given below:

  1. int value=10+20*10;  

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

The precedence and associativity of C operators is given below:

CategoryOperatorAssociativity
Postfix() [] -> . ++ - -Left to right
Unary+ - ! ~ ++ - - (type)* & sizeofRight to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >>Left to right
Relational< <= > >=Left to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XOR^Left to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical OR||Left to right
Conditional?:Right to left
Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
Comma,Left to right

Comments in C

Comments in C language are used to provide information about lines of code. It is widely used for documenting code. There are 2 types of comments in the C language.

  1. Single Line Comments
  2. Multi-Line Comments

Single Line Comments

Single line comments are represented by double slash \\. Let's see an example of a single line comment in C.

  1. #include<stdio.h>    
  2. int main(){    
  3.     //printing information    


  4. <
  1. #include<stdio.h>    
  2. int main(){    
  3.     //printing information    
  4.     printf("Hello C");    
  5. return 0;  
  6. }      

Output:

Hello C


Even you can place the comment after the statement. For example:

printf("Hello C");//printing information 


Mult Line Comments

Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it can't be nested. Syntax:

  1. /*  
  2. code 
  3. to be commented 
  4. */  

Let's see an example of a multi-Line comment in C.

  1. #include<stdio.h>    
  2. int main(){    
  3.     /*printing information   
  4.       Multi-Line Comment*/  
  5.     printf("Hello C");    
  6. return 0;  
  7. }       

Output

Hello C


C Format Specifier

The Format specifier is a string used in the formatted input and output functions. The format string determines the format of the input and output. The format string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

Format specifierDescription
%d or %iIt is used to print the signed integer value where signed integer means that the variable can hold both positive and negative values.
%uIt is used to print the unsigned integer value where the unsigned integer means that the variable can hold only positive value.
%oIt is used to print the octal unsigned integer where octal integer value always starts with a 0 value.
%xIt is used to print the hexadecimal unsigned integer where the hexadecimal integer value always starts with a 0x value. In this, alphabetical characters are printed in small letters such as a, b, c, etc.
%XIt is used to print the hexadecimal unsigned integer, but %X prints the alphabetical characters in uppercase such as A, B, C, etc.
%fIt is used for printing the decimal floating-point values. By default, it prints the 6 values after '.'.
%e/%EIt is used for scientific notation. It is also known as Mantissa or Exponent.
%gIt is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the value after the decimal in input would be exactly the same as the value in the output.
%pIt is used to print the address in a hexadecimal form.
%cIt is used to print the unsigned character.
%sIt is used to print the strings.
%ldIt is used to print the long-signed integer value.

Let's understand the format specifiers in detail through an example.

  • %d
  1. int main()  
  2. {  
  3.   int b=6;  
  4.   int c=8;  
  5.   printf("Value of b is:%d", b);  
  6.   printf("\nValue of c is:%d",c);  
  7.   
  8.     return 0;  
  9. }  

In the above code, we are printing the integer value of b and c by using the %d specifier.


Output

C Format Specifier

  • %u
  1. int main()  
  2. {  
  3.   int b=10;  
  4.   int c= -10;  
  5.   printf("Value of b is:%u", b);  
  6.   printf("\nValue of c is:%u",c);  
  7.   
  8.     return 0;  
  9. }  

In the above program, we are displaying the value of b and c by using an unsigned format specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it does not print the value of c as c contains the negative value.

Output

C Format Specifier

  • %o
  1. int main()  
  2. {  
  3.   int a=0100;  
  4.   printf("Octal value of a is: %o", a);  
  5.   printf("\nInteger value of a is: %d",a);  
  6.   return 0;  
  7. }  

In the above code, we are displaying the octal value and integer value of a.

Output

C Format Specifier

  • %x and %X
  1. int main()  
  2. {  
  3.   int y=0xA;  
  4.   printf("Hexadecimal value of y is: %x", y);  
  5.   printf("\nHexadecimal value of y is: %X",y);  
  6.   printf("\nInteger value of y is: %d",y);  
  7.     return 0;  
  8. }  

In the above code, y contains the hexadecimal value 'A'. We display the hexadecimal value of y in two formats. We use %x and %X to print the hexadecimal value where %x displays the value in small letters, i.e., 'a' and %X displays the value in a capital letter, i.e., 'A'.


Output

C Format Specifier
  • %f
  1. int main()  
  2. {  
  3.   float y=3.4;  
  4.   printf("Floating point value of y is: %f", y);  
  5.   return 0;  
  6. }  

The above code prints the floating value of y.

Output

C Format Specifier
  • %e
  1. int main()  
  2. {  
  3.   float y=3;  
  4.   printf("Exponential value of y is: %e", y);  
  5.   return 0;  
  6. }  

Output

C Format Specifier
  • %E
  1. int main()  
  2. {  
  3.   float y=3;  
  4.   printf("Exponential value of y is: %E", y);  
  5.   return 0;  
  6. }  

Output

C Format Specifier
  • %g
  1. int main()  
  2. {  
  3.   float y=3.8;  
  4.   printf("Float value of y is: %g", y);  
  5.   return 0;  
  6. }  

In the above code, we are displaying the floating value of y by using %g specifier. The %g specifier displays the output same as the input with a same precision.

Output




  • %p
  1. int main()  
  2. {  
  3.   int y=5;  
  4.   printf("Address value of y in hexadecimal form is: %p", &y);  
  5.   return 0;  
  6. }  

Output

C Format Specifier

  • %c
  1. int main()  
  2. {  
  3.   char a='c';  
  4.   printf("Value of a is: %c", a);  
  5.   return 0;  
  6. }  

Output

C Format Specifier

  • %s
  1. int main()  
  2. {  
  3.   printf("%s""javaTpoint");  
  4.   return 0;  
  5. }  

Output

C Format Specifier

Minimum Field Width Specifier

Suppose we want to display an output that occupies a minimum number of spaces on the screen. You can achieve this by displaying an integer number after the percent sign of the format specifier.

  1. int main()  
  2. {  
  3.  int x=900;  
  4.   printf("%8d", x);  
  5.   printf("\n%-8d",x);  
  6.   return 0;  
  7. }  



In the above program, %8d specifier displays the value after 8 spaces while %-8d specifier will make a value left-aligned.

Output

C Format Specifier

Now we will see how to fill the empty spaces. It is shown in the below code:

  1. int main()  
  2. {  
  3.  int x=12;  
  4.   printf("%08d", x);  
  5.   return 0;  
  6. }  

In the above program, %08d means that the empty space is filled with zeroes.

Output

C Format Specifier

Specifying Precision

We can specify the precision by using '.' (Dot) operator which is followed by integer and format specifier.

  1. int main()  
  2. {  
  3.  float x=12.2;  
  4.   printf("%.2f", x);  
  5.   return 0;  
  6. }   

Output

C Format Specifier