This C Cheat Sheet provides an overview of both basic and advanced concepts of the C language. Whether you're a beginner or an experienced programmer, this cheat sheet will help you revise and quickly go through the core principles of the C language.
In this Cheat Sheet, we will delve into the basics of the C language, exploring its fundamental concepts that lay the groundwork for programming. We will cover topics such as variables, data types, and operators, providing you with a solid understanding of the building blocks of C programming.
Basic Syntax
Consider the below Hello World program:
C
// C Hello World program
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Here,
- #include <stdio.h>: The header file inclusion to use printf() function.
- int main(): The main() function is the entry point of any C program.
- printf("Hello World"): Function to print hello world.
- return 0: Value returned by the main() function.
Variables
A variable is the name given to the memory location that stores some data.
Syntax of Variable
data_type variable_name;
data_type variable_name = initial_value;
A variable can be of the following types:
- Local Variable
- Global Variable
- Static Variable
- Extern Variable
- Auto Variable
- Register Variable
Note: There are a few rules which we have to follow while naming a variable.
Data Types
The data type is the type of data that a given variable can store. Different data types have different sizes. There are 3 types of data types in C:
- Basic Data Types
- Derived Data Types
- User Defined Data Types
1. Basic Data Types
Basic data types are built-in in the C programming language and are independent of any other data type. There are x types of basic data types in C:
- char: Used to represent characters.
- int: Used to represent integral numbers.
- float: Used to represent decimal numbers up to 6-7 precision digits.
- double: Used to represent decimal numbers up to 15 precision digits.
- void: Used to represent the valueless entity.
Example of Basic Data Types
char c = 'a';
int integer = 24;
float f = 24.32;
double d = 24.3435;
void v;
The size of these basic data types can be modified using data type modifiers which are:
- short
- long
- signed
- unsigned
Example of Data Type Modifiers
unsigned int var1;
long double var2;
long int var3;
2. Derived Data Types
Derived data types are derived from the basic data types. There are 2 derived data types in C:
- Arrays
- Pointers
3. User-Defined Data Types
The user-defined data types are the data types that are defined by the programmers in their code. There are 3 user-defined data types in C:
- Structure
- Union
- Enumeration
Identifiers
Identifiers is the name given to the variables, functions, structure, etc. Identifiers should follow the following set of rules:
- A variable name must only contain alphabets, digits, and underscore.
- A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
- No whitespace is allowed within the variable name.
- A variable name must not be any reserved word or keyword.
Example of Identifiers
var, any_other_name, __this_var, var22;
Keywords
Keywords are the reserved words that have predefined meanings in the C compiler. They cannot be used as identifiers.
Example of Keywords
auto,
float,
int,
return,
switch
Basic Input and Output
The basic input and output in C are done using two <stdio.h> functions namely scanf() and print() respectively.
Basic Output - print()
The printf() function is used to print the output on the standard output device which is generally the display screen.
Syntax of printf()
printf("formatted-string", ...{arguments-list});
where,
- formatted-string: String to be printed. It may contain format specifiers, escape sequences, etc.
- arguments-list: It is the list of data to be printed.
Basic Input - scanf()
The scanf() function is used to take input from the standard input device such as the keyboard.
Syntax of scanf()
scanf("formatted-string", {address-argument-list});
where,
- formatted-string: String that describes the format of the input.
- address-of-arguments-list: It is the address list of the variables where we want to store the input.
Example of Input and Output
C
// C program to illustrate the basic input and output using
// printf() and scanf()
#include <stdio.h>
int main()
{
int roll_num;
char name[50];
// taking input using scanf
scanf("Enter Roll No.: %d", &roll_num);
scanf("Enter Name: %s", name);
// printing output using printf
printf("Name is %s and Roll Number is %d", name,
roll_num);
return 0;
}
OutputName is and Roll Number is 0
Input
Enter Roll No: 20
Enter Name: GeeksforGeeks
Output
Name is GeeksforGeeks and Roll Number is 20.
Format Specifiers
Format specifiers are used to describe the format of input and output in formatted string. It is different for different data types. It always starts with %
The following is the list of some commonly used format specifiers in C:
Format Specifier | Description |
---|
%c | For b type. |
%d | For signed integer type. |
%f | For float type. |
%lf | Double |
%p | Pointer |
%s | String |
%u | Unsigned int |
%% | Prints % character |
Escape Sequence
Escape sequences are the characters that are used to represent those characters that cannot by represented normally. They start with ( \ ) backslash and can be used inside string literals.
The below table list some commonly used escape sequences:
Escape Sequence | Name | Description |
---|
\b | Backspace | It is used to move the cursor backward. |
\n | New Line | It moves the cursor to the start of the next line. |
\r | Carriage Return | It moves the cursor to the start of the current line. |
\t | Horizontal Tab | It inserts some whitespace to the left of the cursor and moves the cursor accordingly. |
\v | Vertical Tab | It is used to insert vertical space. |
\\ | Backlash | Use to insert backslash character. |
\” | Double Quote | It is used to display double quotation marks. |
\0 | NULL | It represents the NLL character. |
Operators
Operators are the symbols that are used to perform some kind of operation. Operators can be classified based on the type of operation they perform.
There are the following types of operators in C:
S.No. | Operator Type | Description | Example |
---|
1. | Arithmetic Operators | Operators that perform arithmetic operations. | +, -, *, /, % |
---|
2. | Relational Operators | They are used to compare two values. | <, >, <=, >=, ==, != |
---|
3. | Bitwise Operators | They are used to perform bit-level operations on integers. | &, ^, |, <<, >>, ~ |
---|
4. | Logical Operators | They perform logical operations such as logical AND, logical OR, etc. | &&, ||, ! |
---|
5. | Conditional Operators | The conditional Operator is used to insert conditional code. | ? : |
---|
6. | Assignment Operators | They are used to assign some value to the variables. | =, +=, -=, <<= |
---|
7. | Miscellaneous Operators | comma, addressof, sizeof, etc. are some other types of operators. | , sizeof, &, *, ->, . |
---|
Conditional Statements
Conditional statements are used to execute some block of code based on whether the given condition is true. There are the following conditional statements in C:
1. if Statement
if statement contains a block of code that will be executed if and only if the given condition is true.
Syntax of if
if (condition) {
// statements
}
2. if-else Statements
The if-else statement contains the else block in addition to the if block which will be executed if the given condition is false.
Syntax if-else
if (expression) {
// if block
}
else {
// else block
}
3. if-else-if Ladder
The if-else-if ladder is used when we have to test multiple conditions and for each of these conditions, we have a separate block of code.
Syntax of if-else-if
if (expression) {
// block 1
}
else if (expression) {
// block 1
}
.
.
.
else {
// else block
}
4. switch Case Statement
The switch case statement is an alternative to the if-else-if ladder that can execute different blocks of statements based on the value of the single variable named switch variable.
Syntax of switch
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
.
.
.
default:
// defualt block
break;
}
5. Conditional Operator
The conditional operator is a kind of single-line if-else statement that tests the condition and executes the true and false statements.
Syntax of Conditional Operator
(condition) ? (true-exp) : (false-exp);
Example of Conditional Statements
C
// C program to illustrate conditional statements
#include <stdio.h>
int main()
{
// conditional operator will assign 10 if 5 < 25,
// otherwise it will assign 20
int i = 5 < 25 ? 10 : 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Loops
Loops are the control statements that are used to repeat some block of code till the specified condition is false. There are 3 loops in C:
1. for Loop
The for loop is an entry-controlled loop that consists initialization, condition, and updating as a part of itself.
Syntax of for
for (initialization; condition; updation) {
// statements
}
2. while Loop
The while loop is also an entry-controlled loop but only the condition is the part of is syntax.
Syntax of while
while (condition) {
// initialization
}
3. do-while Loop
The do-while loop is an exit-controlled loop in which the condition is checked after the body of the loop.
Syntax of do-while
do {
// statements
} while (condition);
Jump Statements
Jump statements are used to override the normal control flow of the program. There are 3 jump statements in C:
1. break Statement
It is used to terminate the loop and bring the program control to the statements after the loop.
Syntax of break
break;
It is also used in the switch statement.
2. continue Statement
The continue statement skips the current iteration and moves to the next iteration when encountered in the loop.
Syntax of continue
continue;
3. goto Statement
The goto statement is used to move the program control to the predefined label.
Syntax of goto
goto label; | label:
. | .
. | .
. | .
label: | goto label;
Example of Loops and Jump Statements
C
// C program to illustrate loops
#include <stdio.h>
// Driver code
int main()
{
int i = 0;
// for loop with continue
for (i = 1; i <= 10; i++) {
if (i == 5 || i == 7) {
continue;
}
printf("%d ", i);
}
printf("\n");
// while loop with break
i = 1;
while (i <= 10) {
if (i == 7) {
break;
}
printf("%d ", i++);
}
printf("\n");
// do_while loop
i = 1;
do {
printf("%d ", i++);
} while (i <= 10);
printf("\n");
// goto statement
i = 1;
any_label:
printf("%d ", i++);
if (i <= 10) {
goto any_label;
}
return 0;
}
Output1 2 3 4 6 8 9 10
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Arrays
An array is a fixed-size homogeneous collection of items stored at a contiguous memory location. It can contain elements from type int, char, float, structure, etc. to even other arrays.
- Array provides random access using the element index.
- Array size cannot change.
- Array can have multiple dimensions in which it can grow.
Syntax of Arrays
data_type arr_name [size1]; // 1D array
data_type arr_name [size1][size2]; // 2D array
data_type arr_name [size1][size2][size3]; // 3D array
Example of Arrays
C
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100;
// traversing array using for loop
printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
OutputElements in Array: 10 20 100 40 50
Strings
Strings are the sequence of characters terminated by a '\0' NULL character. It is stored as the array of characters in C.
Syntax of Strings
char string_name [] = "any_text";
Example of Strings
C
// C program to illustrate strings
#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
// displaying the length of string
printf("Length of string str is %d", length);
return 0;
}
OutputGeeks
Length of string str is 5
C String Functions
C language provides some useful functions for string manipulation in <string.h> header file. Some of them are as follows:
S. No. | Function | Description |
---|
1. | strlen() | Find the length of the string |
---|
2. | strcmp() | Compares two strings. |
---|
3. | strcpy() | Copy one string to another. |
---|
4. | strcat() | Concatenate one string with another. |
---|
5. | strchr() | Find the given character in the string. |
---|
6. | strstr() | Find the given substring in the string. |
---|
Pointers
Pointers are the variables that store the address of another variable. They can point to any data type in C
Syntax of Pointers
data_type * ptr_name;
Note: The addressof (&) operator is used to get the address of a variable.
We can dereference (access the value pointed by the pointer) using the same * operator.
Example of Pointers
C
// C program to illustrate Pointers
#include <stdio.h>
// Driver program
int main()
{
int var = 10;
// declare pointer variable
int* ptr;
// note that data type of ptr and var must be same
ptr = &var;
// assign the address of a variable to a pointer
printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
return 0;
}
OutputValue at ptr = 0x7ffd62e6408c
Value at var = 10
Value at *ptr = 10
There are different types of pointers based on different classification parameters. Some of them are:
- Double Pointers
- Function Pointers
- Structure Pointers
- NULL Pointers
- Dangling Pointers
- Wild Pointers
Functions
Functions are the block of statements enclosed within { } braces that perform some specific task. They provide code reusability and modularity to the program.
Function Syntax is divided into three parts:
1. Function Prototype
It tells the compiler about the existence of the function.
return_type function_name ( parameter_type_list... );
where,
- Return Type: It is the type of optional value returned by the function. Only one value can be returned.
- Parameters: It is the data passed to the function by the caller.
2. Function Definition
It contains the actual statements to be executed when the function is called.
return_type function_name ( parameter_type_name_list... ) {
// block of statements
.
.
}
3. Function Call
Calls the function by providing arguments. A function call must always be after either function definition or function prototype.
function_name (arguments);
Example of Function
C
// C program to show function
// call and definition
#include <stdio.h>
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b) { return a + b; }
// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
Type of Function
A function can be of 4 types based on return value and parameters:
- Function with no return value and no parameters.
- Function with no return value and parameters.
- Function with return value and no parameters.
- Function with return value and parameters.
There is another classification of function in which there are 2 types of functions:
- Library Functions
- User-Defined Functions
Dynamic Memory Management
Dynamic memory management allows the programmer to allocate the memory at the program's runtime. The C language provides four <stdlib.h> functions for dynamic memory management which are malloc(), calloc(), realloc() and free().
1. malloc()
The malloc() function allocates the block of a specific size in the memory. It returns the void pointer to the memory block. If the allocation is failed, it returns the null pointer.
Syntax
malloc (size_t size);
2. calloc()
The calloc() function allocates the number of blocks of the specified size in the memory. It returns the void pointer to the memory block. If the allocation is failed, it returns the null pointer.
Syntax
calloc (size_t num, size_t size);
3. realloc()
The realloc() function is used to change the size of the already allocated memory. It also returns the void pointer to the allocated memory.
Syntax
realloc (void *ptr, size_t new_size);
4. free()
The free function is used to deallocate the already allocated memory.
Syntax
free (ptr);
Example of Dynamic Memory Allocation
C
// C program to illustrate the dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
// using malloc to allocate the int array of size 10
int* ptr = (int*)malloc(sizeof(int) * 10);
// allocating same array using calloc
int* ptr2 = (int*)calloc(10, sizeof(int));
printf("malloc Array Size: %d\n", 10);
printf("calloc Array Size: %d\n", 10);
// reallocating the size of first array
ptr = realloc(ptr, sizeof(int) * 5);
printf("malloc Array Size after using realloc: %d", 5);
// freeing all memory
free(ptr);
return 0;
}
Outputmalloc Array Size: 10
calloc Array Size: 10
malloc Array Size after using realloc: 5
Structures
A structure is a user-defined data type that can contain items of different types as its members. In C, struct keyword is used to declare structures and we can use ( . ) dot operator to access structure members.
Structure Template
To use structure, we first have to define its template.
struct struct_name {
member_type1 name1;
member_type1 name1;
.
.
};
Structure Variable Syntax
...{
...structure template...
}var1, var2..., varN;
or
strcut str_name var1, var2,...varN;
Example of Structure
C
// C program to illustrate the use of structures
#include <stdio.h>
// declaring structure with name str1
struct str1 {
int i;
char c;
float f;
char s[30];
};
// declaring structure with name str2
struct str2 {
int ii;
char cc;
float ff;
} var; // variable declaration with structure template
// Driver code
int main()
{
// variable declaration after structure template
// initialization with initializer list and designated
// initializer list
struct str1 var1 = { 1, 'A', 1.00, "GeeksforGeeks" },
var2;
struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };
// copying structure using assignment operator
var2 = var1;
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
var1.i, var1.c, var1.f, var1.s);
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
var2.i, var2.c, var2.f, var2.s);
printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
var3.cc, var3.ff);
return 0;
}
OutputStruct 1:
i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 2:
i = 1, c = A, f = 1.000000, s = GeeksforGeeks
Struct 3
i = 5, c = a, f = 5.000000
Union
A union is also a user-defined data type that can contain elements of different types. However, unlike structure, a union stores its members in a shared memory location rather than having separate memory for each member.
Syntax of Union
union union_name {
// members
.
.
}
Union members can be accessed using dot operator ( . ) but only one member can store the data at a particular instance in time.
Example of Union
C
// C Program to demonstrate how to use union
#include <stdio.h>
// union template or declaration
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d",
var1.member1);
return 0;
}
OutputThe value stored in member1 = 15
Enumeration (enum)
Enumeration, also known as enum is a user-defined data type that is used to assign some name to the integral constant. By default, the enum members are assigned values starting from 0 but we can also assign values manually.
Syntax of enum
enum { name1, name2, name3 = value };
Example of enum
C
// An example program to demonstrate working
// of enum in C
#include <stdio.h>
enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };
int main()
{
enum week day;
day = Wed;
printf("%d", day);
return 0;
}
File Handling
File handling is the process of performing input and output on a file instead of the console. We can store, retrieve, and update data in a file. C supports text and binary files.
C File Operations
We can perform some set of operations on a file and C language provide some functions for it.
- Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
- Opening an existing file – fopen()
- Reading from file – fscanf() or fgets()
- Writing to a file – fprintf() or fputs()
- Moving to a specific location in a file – fseek(), rewind()
- Closing a file – fclose()
Preprocessor Directives
The preprocessor directives are used to provide instructions to the preprocessor that expands the code before compilation. They start with the # symbol.
The following table lists all the preprocessor directives in C/C++:
S.No. | Preprocessor Directives | Description |
---|
1. | #define | Used to define a macro |
---|
2. | #undef | Used to undefine a macro |
---|
3. | #include | Used to include a file in the source code program |
---|
4. | #ifdef | Used to include a section of code if a certain macro is defined by #define |
---|
5. | #endif | Used to mark the end of #endif |
---|
6. | #ifndef | Used to include a section of code if a certain macro is not defined by #define |
---|
7. | #if | Check for the specified condition |
---|
8. | #else | Alternate code that executes when #if fails |
---|
9. | #pragma | This directive is a special purpose directive and is used to turn on or off some features. |
---|
Common Library Functions
C languages come bundled with some Standard Libraries that contain some useful functions to make it easier to perform some common operations. These are as follows:
C Math Functions
The <math.h> header file contains functions to perform the arithmetic operations. The following table contains some common maths functions in C:
S.No. | Function Name | Function Description |
---|
1. | ceil(x) | Returns the smallest integer larger than or equal to x. |
---|
2. | floor(x) | Returns the largest integer smaller than or equal to x. |
---|
3. | fabs(x) | Returns the absolute value of x. |
---|
4. | sqrt(x) | Returns the square root of x. |
---|
5. | cbrt(x) | Returns the cube root of x. |
---|
6. | pow(x , y) | Returns the value of x raised to the power y. |
---|
7. | exp(x) | Returns the value of e(Euler’s Number) raised to the power x. |
---|
8. | fmod(x , y) | Returns the remainder of x divided by y. |
---|
9. | log(x) | Returns the natural logarithm of x. |
---|
10. | log10(x) | Returns the common logarithm of x. |
---|
11. | cos(x) | Returns the cosine of radian angle x. |
---|
12. | sin(x) | Returns the sine of radian angle x. |
---|
13. | tan(x) | Returns the tangent of radian angle x. |
---|
Conclusion
In summary, this C Cheat Sheet offers a concise yet comprehensive reference for programmers of all levels. Whether you're a beginner or an experienced coder, this cheat sheet provides a quick and handy overview of the core principles of C. With its organized format, code examples, and key syntaxes, it serves as a valuable resource to refresh your knowledge and navigate through the intricacies of C programming. Keep this cheat sheet close by to accelerate your coding journey and streamline your C programming endeavors.
Similar Reads
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
C Basics
C Language IntroductionC is a general-purpose procedural programming language initially developed by Dennis Ritchie in 1972 at Bell Laboratories of AT&T Labs. It was mainly created as a system programming language to write the UNIX operating system.Main features of CWhy Learn C?C is considered mother of all programmin
6 min read
Features of C Programming LanguageC is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system.The main features of C language include low-level access to memory, a simple set of keywords, and a clean style
3 min read
C Programming Language StandardIntroduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18.C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the feature
6 min read
C Hello World ProgramThe âHello Worldâ program is the first step towards learning any programming language. It is also one of the simplest programs that is used to introduce aspiring programmers to the programming language. It typically outputs the text "Hello, World!" to the console screen.C Program to Print "Hello Wor
1 min read
Compiling a C Program: Behind the ScenesThe compilation is the process of converting the source code of the C language into machine code. As C is a mid-level language, it needs a compiler to convert it into an executable code so that the program can be run on our machine.The C program goes through the following phases during compilation:C
4 min read
C CommentsThe comments in C are human-readable notes in the source code of a C program used to make the program easier to read and understand. They are not a part of the executable program by the compiler or an interpreter.Example:C#include <stdio.h> int main() { // This is a comment, the below // state
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
Keywords in CKeywords are predefined or reserved words that have special meanings to the compiler. These are part of the syntax and cannot be used as identifiers in the program. A list of keywords in C or reserved words in the C programming language are mentioned below:autobreakcasecharconstcontinuedefaultdodoub
2 min read
C Variables and Constants
C VariablesA variable in C is a named piece of memory which is used to store data and access it whenever required. It allows us to use the memory without having to memorize the exact memory address.To create a variable in C, we have to specify a name and the type of data it is going to store in the syntax.Cdat
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Const Qualifier in CThe qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to c
6 min read
Different ways to declare variable as constant in CThere are many different ways to make the variable as constant in C. Some of the popular ones are: Using const KeywordUsing MacrosUsing enum Keyword1. Using const KeywordThe const keyword specifies that a variable or object value is constant and can't be modified at the compilation time. Syntaxconst
2 min read
Scope rules in CThe scope of a variable in C is the block or the region in the program where a variable is declared, defined, and used. Outside this region, we cannot access the variable, and it is treated as an undeclared identifier.The scope is the area under which a variable is visible.The scope of an identifier
5 min read
Internal Linkage and External Linkage in CIn C, linkage is a concept that describes how names/identifiers can or cannot refer to the same entity throughout the whole program or a single translation unit. The above sounds similar to scope, but it is not so. To understand what the above means, let us dig deeper into the compilation process.Be
4 min read
Global Variables in CPrerequisite: Variables in C In a programming language, each variable has a particular scope attached to them. The scope is either local or global. This article will go through global variables, their advantages, and their properties. The Declaration of a global variable is very similar to that of a
3 min read
C Data Types
Data Types in CEach variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc.Example:C++int number;The above statement declares a variable with name number that can store integer values.C is a statically type language where
5 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Escape Sequence in CThe escape sequence in C is the characters or the sequence of characters that can be used inside the string literal. The purpose of the escape sequence is to represent the characters that cannot be used normally using the keyboard. Some escape sequence characters are the part of ASCII charset but so
5 min read
bool in CThe bool in C is a fundamental data type in most that can hold one of two values: true or false. It is used to represent logical values and is commonly used in programming to control the flow of execution in decision-making statements such as if-else statements, while loops, and for loops. In this a
5 min read
Integer Promotions in CSome data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and e
2 min read
Character Arithmetic in CAs already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. What is Character Arithmetic?Character arithmetic is used to implement arithmetic operations like addition, subtraction, multiplication, and division on characters
2 min read
Type Conversion in CIn C, type conversion refers to the process of converting one data type to another. It can be done automatically by the compiler or manually by the programmer. The type conversion is only performed to those data types where conversion is possible. Let's take a look at an example:C#include <stdio.
4 min read
C Input/Output
Basic Input and Output in CIn C, there are many input and output for different situations, but the most commonly used functions for Input/Output are scanf() and printf() respectively. These functions are part of the standard input/output library <stdio.h>. scanf() takes user inputs (typed using keyboard) and printf() di
4 min read
Format Specifiers in CThe format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc.The C language provides a number of format s
5 min read
printf in CIn C language, printf() function is used to print formatted output in many ways to the standard output stdout (which is generally the console screen).Example:C#include <stdio.h> int main() { // Using printf to print the text "Hi!" printf("Hi!"); return 0; }OutputHi!Explanation: In this program
5 min read
scanf in CIn C, scanf() is a function is used to read data from stdin (standard input stream i.e. usually keyboard) and stores the result into the given arguments. It is defined in the <stdio.h> header file.Example:C#include <stdio.h> int main() { int n; // Reading an integer input scanf("%d",
3 min read
Scansets in Cscanf family functions support scanset specifiers which are represented by %[]. Inside scanset, we can specify single character or range of characters. While processing scanset, scanf will process only those characters which are part of scanset. We can define scanset by putting characters inside squ
2 min read
Formatted and Unformatted Input/Output in CIn C, the input/output functions can be classified into two categories on the basis of how they handle the input/output in terms of formatting or structure: Formatted I/O FunctionsFormatted I/O functions help to display the output to the user in different formats using the format specifiers. These I
6 min read
C Operators
Operators in COperators are the basic components of C programming. They are symbols that represent some kind of operation, such as mathematical, relational, bitwise, conditional, or logical computations, which are to be performed on values or variables. The values and variables used with operators are called oper
11 min read
Arithmetic Operators in CArithmetic operators are the type of operators used to perform basic math operations like addition, subtraction, and multiplication. Let's take a look at an example:C#include <stdio.h> int main() { // Calculate the area of the triangle int sum = 10 + 20; printf("%d", sum); return 0; }Output30E
5 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Relational Operators in CIn C, relational operators are the symbols that are used for comparison between two values to understand the type of relationship a pair of numbers shares. The result that we get after the relational operation is a boolean value, that tells whether the comparison is true or false. Relational operato
4 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
C Logical OperatorsLogical operators in C are used to combine multiple conditions/constraints. Logical Operators returns either 0 or 1, it depends on whether the expression result is true or false. In C programming for decision-making, we use logical operators.We have 3 logical operators in the C language:Logical AND
4 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
Increment and Decrement Operators in CThe increment ( ++ ) and decrement ( -- ) operators in C are unary operators for incrementing and decrementing the numeric values by 1, respectively. They are one of the most frequently used operators in programming for looping, array traversal, pointer arithmetic, and many more.Increment Operator i
4 min read
Conditional or Ternary Operator (?:) in CThe conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it
3 min read
sizeof operator in CSizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integ
3 min read
Operator Precedence and Associativity in COperator precedence and associativity are rules that decide the order in which parts of an expression are calculated. Precedence tells us which operators should be evaluated first, while associativity determines the direction (left to right or right to left) in which operators with the same preceden
7 min read
C Control Statements Decision-Making
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C - if StatementThe if in C is the simplest decision-making statement. It consists of the test condition and a block of code that is executed if and only if the given condition is true. Otherwise, it is skipped from execution.Let's take a look at an example:C#include <stdio.h> int main() { int n = 9; // if st
4 min read
C if else StatementThe if else in C is an extension of the if statement which not only allows the program to execute one block of code if a condition is true, but also a different block if the condition is false. This enables making decisions with two possible outcomes.Example:C#include <stdio.h> int main() { in
3 min read
C if , else if ladderIn C, if else if ladder is an extension of if else statement used to test a series of conditions sequentially, executing the code for the first true condition. A condition is checked only if all previous ones are false. Once a condition is true, its code block executes, and the ladder ends.Example:C
4 min read
Switch Statement in CC switch statement is a conditional statement that allows you to execute different code blocks based on the value of a variable or an expression. It is often used in place of if-else ladder when there are multiple conditions.Example:C#include <stdio.h> int main() { // Switch variable int var =
5 min read
Using Range in switch Case in CYou all are familiar with switch case in C, but did you know you can use a range of numbers instead of a single number or character in the case statement? Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases se
2 min read
C - LoopsIn C programming, there is often a need for repeating the same part of the code multiple times. For example, to print a text three times, we have to use printf() three times as shown in the code:C#include <stdio.h> int main() { printf( "Hello GfG\n"); printf( "Hello GfG\n"); printf( "Hello GfG
6 min read
C for LoopIn C programming, the 'for' loop is a control flow statement that is used to repeatedly execute a block of code as many times as instructed. It uses a variable (loop variable) whose value is used to decide the number of repetitions. It is commonly used to iterate over a sequence such as an array or
4 min read
while Loop in CThe while loop in C allows a block of code to be executed repeatedly as long as a given condition remains true. It is often used when we want to repeat a block of code till some condition is satisfied.Example: C#include <stdio.h> int main() { int i = 1; // Condition for the loop while (i <=
5 min read
do...while Loop in CC do...while loop is a type of loop that executes a code block until the given condition is satisfied. Unlike the while loop, which checks the condition before executing the loop, the do...while loop checks the condition after executing the code block, ensuring that the code inside the loop is execu
4 min read
For vs. WhileIn C, loops are the fundamental part of language that are used to repeat a block of code multiple times. The two most commonly used loops are the for loop and the while loop. Although they achieve the same result, their structure, use cases, and flexibility differ.The below table highlights some pri
4 min read
Continue Statement in CThe continue statement in C is a jump statement used to skip the current iteration of a loop and continue with the next iteration. It is used inside loops (for, while, or do-while) along with the conditional statements to bypass the remaining statements in the current iteration and move on to the ne
4 min read
Break Statement in CThe break statement in C is a loop control statement that breaks out of the loop when encountered. It can be used inside loops or switch statements to bring the control out of the block. The break statement can only break out of a single loop at a time.Example:C#include <stdio.h> int main() {
5 min read
goto Statement in CThe goto statement in C allows the program to jump to some part of the code, giving you more control over its execution. While it can be useful in certain situations, like error handling or exiting complex loops, it's generally not recommended because it can make the code harder to read and maintain
4 min read
C Functions
C FunctionsA function is a named block of code that performs a specific task. It allows you to write a piece of logic once and reuse it wherever needed in the program. This helps keep your code clean, organized, and easier to understand.Functions play a vital role in building modular programs. They allow you t
6 min read
User-Defined Function in CA user-defined function is a type of function in C language that is defined by the user himself to perform some specific task. It provides code reusability and modularity to our program. User-defined functions are different from built-in functions as their working is specified by the user and no hea
6 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Function Prototype in CIn C, a function prototype is a statement that tells the compiler about the functionâs name, its return type, numbers, and data types of its parameters. Function prototype provides a means for the compiler to cross-check function parameters and their data type with the function definition and the fu
4 min read
How can I return multiple values from a function?In C programming, a function can return only one value directly. However, C also provides several indirect methods in to return multiple values from a function. In this article, we will learn the different ways to return multiple values from a function in C.The most straightforward method to return
3 min read
main Function in CThe main function is the entry point of a C program. It is a user-defined function where the execution of a program starts. Every C program must contain, and its return value typically indicates the success or failure of the program. In this article, we will learn more about the main function in C.E
5 min read
Implicit Return Type int in CIn C, every function has a return type that indicates the type of value it will return, and it is defined at the time of function declaration or definition. But in C language, it is possible to define functions without mentioning the return type and by default, int is implicitly assumed that the ret
2 min read
Callbacks in CIn C language, a callback is a function that is passed as an argument to another code, which is expected to call back (execute) the argument at a given time. In simple terms, a callback is the process of passing a function (executable code) to another function as an argument, which is then called by
4 min read
Nested Functions in CNesting of functions refers to placing the definition of the function inside another functions. In C programming, nested functions are not allowed. We can only define a function globally.Example:C#include <stdio.h> int main() { void fun(){ printf("GeeksForGeeks"); } fun(); return 0; }Outputmai
4 min read
Variadic Functions in CIn C, variadic functions are functions that can take a variable number of arguments. This feature is useful when the number of arguments for a function is unknown. It takes one fixed argument and then any number of arguments can be passed.Let's take a look at an example:C#include <stdio.h> #in
5 min read
_Noreturn function specifier in CIn C, the _Noreturn specifier is used to indicate that a function does not return a value. It tells the compiler that the function will either exit the program or enter an infinite loop, so it will never return control to the calling function. This helps the compiler to optimize code and issue warni
2 min read
Predefined Identifier __func__ in CBefore we start discussing __func__, let us write some code snippets and anticipate the output: C // C program to demonstrate working of a // Predefined Identifier __func__ #include <stdio.h> int main() { // %s indicates that the program will read strings printf("%s", __func__); return 0; } Ou
2 min read
C Library math.h FunctionsThe math.h header defines various C mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. Let us discuss some important C math functions one by one. C Math Functions1. double ceil (double x) The C library functio
6 min read
C Arrays & Strings
C ArraysAn array in C is a fixed-size collection of similar data items.Items are stored in contiguous memory locations. Can be used to store the collection of primitive data types such as int, char, float, etc., as well as derived and user-defined data types such as pointers, structures, etc.C// A simple C
7 min read
Properties of Array in CThe properties of the arrays vary in different programming languages. In this article, we will study the different properties of Array in the C programming language.1. Fixed Size of an ArrayIn C, the size of an array is fixed after its declaration. It should be known at the compile time and it canno
7 min read
Multidimensional Arrays in C - 2D and 3D ArraysA multi-dimensional array in C can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays include 2D arrays which grows in two dimensions, and 3D arrays which grows in three dimension
8 min read
Initialization of Multidimensional Array in CIn C, multidimensional arrays are the arrays that contain more than one dimensions. These arrays are useful when we need to store data in a table or matrix-like structure. In this article, we will learn the different methods to initialize a multidimensional array in C. The easiest method for initial
4 min read
Pass Array to Functions in CPassing an array to a function allows the function to directly access and modify the original array. In this article, we will learn how to pass arrays to functions in C.In C, arrays are always passed to function as pointers. They cannot be passed by value because of the array decay due to which, whe
3 min read
How to pass a 2D array as a parameter in C?A 2D array is essentially an array of arrays, where each element of the main array holds another array. In this article, we will see how to pass a 2D array to a function.The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D array with row size and co
3 min read
What are the data types for which it is not possible to create an array?In C, an array is a collection of variables of the same data type, stored in contiguous memory locations. Arrays can store data of primitive types like integers, characters, and floats, as well as user-defined types like structures.However, there are certain data types for which arrays cannot be dir
2 min read
How to pass an array by value in C ?In C programming, arrays are always passed as pointers to the function. There are no direct ways to pass the array by value. However, there is trick that allows you to simulate the passing of array by value by enclosing it inside a structure and then passing that structure by value. This will also p
2 min read
Strings in CA string is an array of characters terminated by a special character '\0' (null character). This null character marks the end of the string and is essential for proper string manipulation.Unlike many modern languages, C does not have a built-in string data type. Instead, strings are implemented as a
6 min read
Array of Strings in CIn C, an array of strings is a 2D array where each row contains a sequence of characters terminated by a '\0' NULL character (strings). It is used to store multiple strings in a single array.Let's take a look at an example:C#include <stdio.h> int main() { // Creating array of strings for 3 str
3 min read
What is the difference between single quoted and double quoted declaration of char array?In C programming, the way we declare and initialize a char array can differ based on whether we want to use a sequence of characters and strings. They are basically same with difference only of a '\0' NULL character.Double quotes automatically include the null terminator, making the array a string l
2 min read
C String FunctionsC language provides various built-in functions that can be used for various operations and manipulations on strings. These string functions make it easier to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions.st
6 min read
C Pointers
C PointersA pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it holds the address where the value is stored in memory. It is the backbone of low-level memory manipulation in C. Accessing the pointer directly will just give us the address that is stor
9 min read
Pointer Arithmetics in C with ExamplesPointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn't store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer
10 min read
C - Pointer to Pointer (Double Pointer)In C, double pointers are those pointers which stores the address of another pointer. The first pointer is used to store the address of the variable, and the second pointer is used to store the address of the first pointer. That is why they are also known as a pointer to pointer.Let's take a look at
5 min read
Function Pointer in CIn C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves di
6 min read
How to Declare a Pointer to a Function?A pointer to a function is similar to a pointer to a variable. However, instead of pointing to a variable, it points to the address of a function. This allows the function to be called indirectly, which is useful in situations like callback functions or event-driven programming.In this article, we w
2 min read
Pointer to an Array | Array PointerA pointer to an array is a pointer that points to the whole array instead of the first element of the array. It considers the whole array as a single unit instead of it being a collection of given elements.Example:C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr;
5 min read
Difference between constant pointer, pointers to constant, and constant pointers to constantsIn this article, we will discuss the differences between constant pointer, pointers to constant & constant pointers to constants. Pointers are the variables that hold the address of some other variables, constants, or functions. There are several ways to qualify pointers using const. Pointers to
3 min read
Pointer vs Array in CMost of the time, pointer and array accesses can be treated as acting the same, the major exceptions being:  1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2.
1 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Near, Far and Huge Pointers in CIn older times, the intel processors had 16-bit registers, but the address bus was 20-bits wide. Due to this, CPU registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were
4 min read
restrict Keyword in CThe restrict keyword is a type qualifier that was introduced in the C99 standard. It is used to tell the compiler that a pointer is the only reference or access point to the memory it points to, allowing the compiler to make optimizations based on that information.Let's take a look at an example:C#i
3 min read