C Programming Language Cheatsheet 2022 [Latest Update!!]

1. What is C?

C is a Procedural Oriented language, developed at AT & T’s Bell Laboratories of USA in 1972 by Dennis Ritchie.

C language is considered as the mother language of all the modern programming languages because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in many languages like C++, Java, C#, etc.

Features Of C
  • Structured language
    • It has the ability to divide and hide all the information and instruction.
    • Code can be partitioned in C using functions or code block.
    • C is a well structured language compare to other.
  • General purpose language
    • Make it ideal language for system programming.
    • It can also be used for business and scientific application.
    • ANSI established a standard for c in 1983.
    • The ability of c is to manipulate bits,byte and addresses.
    • It is adopted in later 1990.
  • Portability
    • Portability is the ability to port or use the software written .
    • One computer C program can be reused.
    • By modification or no modification.
  • Code Re-usability & Ability to customize and extend
    • A programmer can easily create his own function
    • It can can be used repeatedly in different application
    • C program basically collection of function
    • The function are supported by ‘c’ library
    • Function can be added to ‘c’ library continuously
  • Limited Number of Key Word
    • There are only 32 keywords in ‘C’
    • 27 keywords are given by ritchie
    • 5 is added by ANSI
    • The strength of ‘C’ is lies in its in-built function
    • Unix system provides as large number of C function
    • Some function are used in operation .
    • Other are for specialized in their application

Basics

Basic syntax and functions from the C programming language.

Boilerplate Code
#include<stdio.h>
int main()
{
return(0);
}
printf function

It is used to show output on the screen

printf("Hello World!")
scanf function - How To Take Input From User in C Language?/Receiving input values from keyboard

It is used to take input from the user

scanf("placeholder", variables)

Comments – What are two types of comments in C?

A comment is a code that is not executed by the compiler, and the programmer uses it to keep track of the code.

1. Single line comment -How do you comment out a line in C?
// It's a single line comment
2. Multi-line comment in C
/* It's a 
multi-line
comment
*/

C Keywords – How Many Keywords are There in C?

Keywords are the words whose meaning has already been explained to the C compiler. There are only 32 keywords available in C. The keywords are also called ‘Reserved words’.

auto        double      int         struct 
break       else        long        switch 
case        enum        register    typedef 
char        extern      return      union 
const       float       short       unsigned 
continue    for         signed      void 
default     goto        sizeof      volatile 
do          if          static      while
C Character Set

A character denotes any alphabet, digit or special symbol used to represent information. Following are the valid alphabets, numbers and special symbols allowed in C.

  • Alphabets – A, B, ….., Y, Z a, b, ……, y, z
  • Digits – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • Special symbols – ~ ‘ ! @ # % ^ & * ( ) _ – + = | \ { }
    [ ] : ; ” ‘ < > , . ? /
Rules for Writing, Compiling and Executing the C program
  • C is case sensitive means variable named “COUNTER” is different from a variable named “counter”.
  • All keywords are lowercased.
  • Keywords cannot be used for any other purpose (like variable names).
  • Every C statement must end with a ;. Thus ;acts as a statement terminator.
  • First character must be an alphabet or underscore, no special symbol other than an underscore, no commas or blank spaces are allowed with in a variable, constant or keyword.
  • Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
  • Variable must be declared before it is used in the program.
  • File should be have the extension .c
  • Program need to be compiled before execution.

Data types

The data type is the type of data

Character type

Typically a single octet(one byte). It is an integer type

char variable_name;
Integer type

The most natural size of integer for the machine

int variable_name;
Float type

A single-precision floating-point value

float variable_name;
Double type

A double-precision floating-point value

double variable_name;
Void type

Represents the absence of the type

void

Variables

Declaring
int x;A variable.
char x = 'C';A variable & initializing it.
float x, y, z;Multiple variables of the same type.
const int x = 88;A constant variable: can’t assign to after declar­ation (compiler enforced.)

Primitive Variable Types – Values Ranges of Data Type

Integer
TypeBytesValue Range
char1unsigned OR signed
unsigned char10 to 28-1
signed char1-27 to 27-1
int2 / 4unsigned OR signed
unsigned int2 / 40 to 216-1 OR 231-1
signed int2 / 4-215 to 215-1 OR -231 to 232-1
short2unsigned OR signed
unsigned short20 to 216-1
signed short2-215 to 215-1
long4 / 8unsigned OR signed
unsigned long4 / 80 to 232-1 OR 264-1
signed long4 / 8-231 to 231-1 OR -263 to 263-1
long long8unsigned OR signed
unsigned long long80 to 264-1
signed long long8-263 to 263-1
Float
TypeBytesValue Range (Norma­lized)
float4±1.2×10-38 to ±3.4×1038
double8 / 4±2.3×10-308 to ±1.7×10308 OR alias to float for AVR.

Format Specifiers

Format SpecifierType
%cCharacter
%dInteger
%ffloat
%lfdouble
%llong
%Lflong double
%lldlong long
%ooctal representation
%ppointer
%sstring
%%prints % symbol

Escape Sequences

Escape SequenceType
\aProduces Alarm/Beep Sound
\bBackspace
\fForm Feed
\nNew Line
\rCarriage return
\tTab Space -Horizontally
\vTab Space – Vertically
\\Backslash
\”Double Quote
\’Single Quote
\?Question Mark

Expression & Operators Precedence

The following table summarizes the rules for precedence and associativity of all operators, including those that we have not yet discussed. Operators on the same line have the same precedence; rows are in order of decreasing precedence, so, for example, *, /, and % all have the same precedence, which is higher than that of the binary + and -. The “operator” () refers to function call. The operators -> and . are used to access members of structures;

DESCRIPTIONOPERATORSASSOCIATIVITY
Function Expression()Left to Right
Array Expression[]Left to Right
Structure Operator->Left to Right
Structure Operator.Left to Right
Unary minusRight to Left
Increment/Decrement++, —Right to Left
One’s compliment~Right to Left
Negation!Right to Left
Address of&Right to Left
Value of address`*`Right to Left
Typecast(type)Right to Left
Size in bytessizeofRight to Left
Multiplication`*`Left to Right
Division/Left to Right
Modulus%Left to Right
Addition+Left to Right
SubtractionLeft to Right
Left shift<<Left to Right
Right shift>>Left to Right
Less than<Left to Right
Less than or equal to<=Left to Right
Greater than>Left to Right
Greater than or equal to>=Left to Right
Equal to==Left to Right
Not equal to!=Left to Right
Bitwise AND&Left to Right
Bitwise exclusive OR^Left to Right
Bitwise inclusive OR|Left to Right
Logical AND&&Left to Right
Logical OR||Left to Right
Conditional?:Right to Left
Assignment=, *=, /=, %=, +=, -=, &=, ^=, |=, <<=, >>=Right to Left
Comma,Right to Left

Unary & +, -, and * have higher precedence than the binary forms.

Conditional Instructions

Conditional statements are used to perform operations based on some condition.

If Statement
if (/* condition */)
{
/* code */
}
If-else Statement
if (/* condition */)
{
/* code */
}
else{
/* Code */
}
if else-if Statement
if (condition) {
// Statements;
}
else if (condition){
// Statements;
}
else{
// Statements
}
Switch Case Statement

It allows a variable to be tested for equality against a list of values (cases).

switch (expression) 
{
case constant-expression: 
statement1;
statement2;
break;
case constant-expression: 
statement;
break;
...
default: 
statement;
}

Iterative Statements

Iterative statements facilitate programmers to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.

while Loop

It allows the execution of statements inside the block of the loop until the condition of the loop succeeds.

while (/* condition */)
{
/* code */
}
do-while loop

It is an exit-controlled loop. It is very similar to the while loop with one difference, i.e., the body of the do-while loop is executed at least once even if the expression is false

do
{
/* code */
} while (/* condition */);
for loop

It is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

for (int i = 0; i < count; i++)
{
/* code */
}
Break Statement

break keyword inside the loop is used to terminate the loop

break;
Continue Statement

continue keyword skips the rest of the current iteration of the loop and returns to the starting point of the loop

continue;

Goto and labels

C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice, it is almost always easy to write code without it. We have not used goto in this book.

Nevertheless, there are a few situations where gotos may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop. Thus:

for ( ... )
{           
    for ( ... ) 
    {               
        ...               
        if (disaster)
        {                   
            goto error;
        }           
    }
}       
...   
error:       
/* clean up the mess */

This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.

label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.

Note – By use of goto, programs become unreliable, unreadable, and hard to debug.

Functions

Functions are used to divide the code and to avoid the repetitive task. It provides reusability and readability to code.
Function Declaration

return_type function_name(data_type-parameters){
    //code
}
//  Example of function to add two numbers

int add(int a, int b){
    return a+b;
}
Multiple Parameters Passed In Functions

In fact, you can use more than one argument in a function. The following example will show you how you can do this.

#include<stdio.h> 
int min(int a,int b); 
main() 
{ 
    int m; 
    m=min(3,6); 
    printf("Minimum is %d",m);  
    return 0; 
} 
int min(int a,int b) 
{ 
    if(a<b) 
        return a; 
    else 
        return b; 
} 

As you see you can add your variables to the arguments list easily.

Recursion

Recursion is the process of repeating items in a self-similar way. If a program allows you to call a function inside the same function, then it is called a recursive call of the function.

recursive
void myFunction(){
    myFunction();   //Function calling itself
}
//Factorial Using Recursion
long factorial(long n){
    if(n==0){
        return 1;
    }
    return n * factorial(n -1);
}

int main(){
    int n = 5;
    printf("Factorial of %d is %l.",n,factorial(n));
    return 0;
}
//OUTPUT : Factorial of 5 is 120.

Arrays

Arrays are structures that hold multiple variables of the same data type. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared.

Array Declaration

Like other variables an array needs to be declared so that the compiler will know what kind of an array and how large an array we want.

int marks[30] ;

Here, int specifies the type of the variable, just as it does with ordinary variables and the word marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array. This number is often called the “dimension” of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.

Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this.

int num[6] = { 2, 4, 12, 5, 45, 5 } ; 
int n[] = { 2, 4, 12, 5, 45, 5 } ; 
float press[] = { 12.3, 34.2 -23.4, -11.3 } ;
Accessing Elements of an Array

Once an array is declared, let us see how individual elements in the array can be referred to. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks [2] are not the second element of the array, but the third.

int valueOfThirdElement = marks[2];
Entering Data into an Array

Here is the section of code that places data into an array:

for(i = 0;i <= 29;i++) 
{ 
    printf("\nEnter marks "); 
    scanf("%d", &marks[i]); 
}

The for a loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop i has a value 0, so the scanf() function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i become 29. This is the last time through the loop, which is a good thing because there is no array element like marks[30].

In scanf() function, we have used the “address of” operator (&) on the element marks[i] of the array. In so doing, we are passing the address of this particular array element to the scanf() function, rather than its value; which is what scanf() requires.

 Reading Data from an Array

The balance of the program reads the data back out of the array and uses it to calculate the average. The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average.

for ( i = 0 ; i <= 29 ; i++ )
    sum = sum + marks[i] ; 
avg = sum / 30 ; 
printf ( "\nAverage marks = %d", avg ) ;
Example

Let us try to write a program to find average marks obtained by a
class of 30 students in a test.

#include<stdio.h>  
main() 
{ 
    int avg, i, sum=0; 
    int marks[30] ; /*array declaration */ 
    for ( i = 0 ; i <= 29 ; i++ ) 
    { 
        printf ( "\nEnter marks " ) ; 
        scanf ( "%d", &marks[i] ) ; /* store data in array */ 
    } 
    for ( i = 0 ; i <= 29 ; i++ ) 
        sum = sum + marks[i] ; /* read data from an array*/ 
    avg = sum / 30 ; 
    printf ( "\nAverage marks = %d", avg ) ; 
} 


Strings

What is String?

Strings are arrays of characters. Each member of the array contains one of the characters in the string.

Example

#include<stdio.h> 
main() 
{ 
    char name[20]; 
    printf("Enter your name : "); 
    scanf("%s",name); 
    printf("Hello, %s , how are you ?\n",name); 
} 

Output Results:

Output Console:
Enter your name : Vineet 
Hello, Vineet, how are you ?

If the user enters “Vineet” then the first member of the array will contain ‘V’ , the second cell will contain ‘i’, and so on. C determines the end of a string by a zero value character. We call this character NULL a character and show it with \0 character. (It’s only one character and its value is 0, however, we show it with two characters to remember it is a character type, not an integer).

Equally, we can make that string by assigning character values to each member.

name[0]='B'; 
name[1]='r'; 
name[2]='i'; 
name[3]='a'; 
name[4]='n'; 
name[5]='\0';

As we saw in the above example placeholder for string variables is %s. Also, we will not use a & sign for receiving string values.

Standard Library String Functions

With every C compiler, a large set of useful string handling library functions are provided in string.h file.

  • strlen – Finds length of a string
  • strlwr – Converts a string to lowercase
  • strupr – Converts a string to uppercase
  • strcat – Appends one string at the end of another
  • strncat – Appends first n characters of a string at the end of
    another
  • strcpy – Copies a string into another
  • strncpy – Copies first n characters of one string into another
  • strcmp – Compares two strings
  • strncmp – Compares first n characters of two strings
  • strcmpi – Compares two strings without regard to case (“i” denotes
    that this function ignores case)
  • stricmp – Compares two strings without regard to case (identical to
    strcmpi)
  • strnicmp – Compares first n characters of two strings without regard
    to case
  • strdup – Duplicates a string
  • strchr – Finds first occurrence ofa given character in a string
  • strrchr – Finds last occurrence ofa given character in a string
  • strstr – Finds first occurrence of a given string in another string
  • strset – Sets all characters ofstring to a given character
  • strnset – Sets first n characters ofa string to a given character
  • strrev – Reverses string

Call By Value VS Call By Reference

Call By ValueCall By Reference
While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”.While calling a function, instead of passing the values of variables, we pass the address of variables(location of variables) to the function known as “Call By References.
In this method, the value of each variable in the calling function is copied into corresponding dummy variables of the called function.In this method, the address of actual variables in the calling function is copied into the dummy variables of the called function.
With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function.With this method, using addresses we would have access to the actual variables and hence we would be able to manipulate them.
Thus actual values of a and b remain unchanged even after exchanging the values of x and y.Thus actual values of a and b get changed after exchanging values of x and y.
In call-by-values, we cannot alter the values of actual variables through function calls.In call-by-reference, we can alter the values of variables through function calls.
Values of variables are passed by the Simple technique.Pointer variables are necessary to define to store the address values of variables.
Call By Value Example
// C program to illustrate
// call by value

#include<stdion.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass by Values
    swapx(a, b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Swap functions that swaps
// two values
void swapx(int x, int y)
{
    int t;

    t = x;
    x = y;
    y = t;

    printf("x=%d y=%d\n", x, y);
}
Output:
x=20 y=10
a=10 b=20
Call By Reference Example
// C program to illustrate
// Call by Reference

#include<stdio.h> 

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass reference
    swapx(&a, &b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Function to swap two variables
// by references
void swapx(int* x, int* y)
{
    int t;

    t = *x;
    *x = *y;
    *y = t;

    printf("x=%d y=%d\n", *x, *y);
}
Output:
x=20 y=10
a=20 b=10

What is a Pointer?

A pointer is a variable that contains the address of a variable. The main thing is that once you can talk about the address of a variable, you’ll then be able to goto that address and retrieve the data stored in it.

A pointer is declared by preceding the name of the pointer by an asterisk(*).

datatype *pointer_name;

When we need to initialize a pointer with the variable’s location, we use ampersand sign(&) before the variable name.
Example:

// Declaration of integer variable
int var=10;
  
// Initialization of pointer variable
int *pointer=&var;

Structures

A structure creates a data type that can be used to group items of possibly different types into a single type.

Structure syntax
struct structureName 
{
dataType member1;
dataType member2;
...
};

Dynamic Memory Allocation

If you are aware of the size of an array, then it is easy and you can define it as an array. For example, to store the name of any person, it can go up to a maximum of 100 characters. But now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description of a topic. Here we need to define a pointer to character without defining how much memory is required and later. So we use Dynamic Memory Allocation.

malloc() function
Stands for 'Memory allocation' and reserves a block of memory with the given amount of bytes.
var = (casting_type*)malloc(size);
//Example
var = (int*)malloc(n * sizeof(int))
calloc() function
Stands for “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.
var = (cast_type*)calloc(n, size);
realloc() function
If the allocated memory is insufficient, then we can change the size of previously allocated memory using this function for efficiency purposes.
var = realloc(var2,n);

File Handling

Creating File Pointer
FILE *file
Opening a File
file = fopen(file_name.txt,w)
fscanf() function
Used to read file content
fscanf(FILE *stream, const char *format, ..);
fprintf() function
Used to write the file content
fprintf(FILE *var, const char *str,..);
Closing a File
fclose(file);

The filename and mode are both strings.

The mode can be

  • r – read
  • w – write, overwrite file if it ex ists
  • a – write, but append instead of overwrite
  • r+ – read & write, do not destroy file if it exists
  • w+ – read & write, but overwrite file if it exists
  • a+ – read & write, but append instead of overwrite
  • b – may be appended to any of the above to force the file to be opened in binary mode rather than text mode
  • fp = fopen("data.dat","a"); – will open the disk file data.dat for writing, and any information written will be appended to the file.

The following useful table from the ANSI C Rationale lists the different actions and requirements of the different modes for opening a file:

filehandling

Command Line Arguments

The arguments that we pass on to main() at the command prompt are called command-line arguments. The full declaration of main looks like this:

int main (int argc, char *argv[])

The function main() can have two arguments, traditionally named as argc and argv. Out of these, argv is an array of pointers to strings and argc is an int whose value is equal to the number of strings to which argv points. When the program is executed, the strings on the command line are passed to main(). More precisely, the strings at the command line are stored in memory, and the address of the first string is stored in argv[0], the address of the second string is stored in argv[1] , and so on. The argument argc is set to the number of strings given on the command line.

For example, in our sample program, if at the command prompt we give,

filecopy PR1.C PR2.C

then, argc would contain 3

  • argv[0] – would contain base address of the string “filecopy”
  • argv[1] – would contain base address of the string “PR1.C”
  • argv[2] – would contain base address of the string “PR2.C”

Conclusion

Hope You like this C Programming Shorthand Tutorial or Cheatsheet of C Language. Here we have explained all C Concepts, and you will get the fundamentals of C Programming Language. For more latest updates, about different Cheatsheets, follow our blog Techno-RJ.

27 thoughts on “C Programming Language Cheatsheet 2022 [Latest Update!!]”

  1. Hi there! This post could not be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Many thanks for sharing!

    Reply
  2. Woah! I’m really digging the template/theme of this blog. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and visual appeal. I must say that you’ve done a fantastic job with this. Additionally, the blog loads very fast for me on Internet explorer. Superb Blog!

    Reply
  3. What’s Going down i am new to this, I stumbled upon this I have found It positively helpful and it has aided me out loads.
    I’m hoping to give a contribution & help other customers
    like its aided me. Great job.

    Feel free to surf to my site … gacor

    Reply
  4. I simply needed to thank you very much yet again. I do not know the things that I might have followed in the absence of the type of strategies shown by you on such problem. It has been a very troublesome problem for me personally, nevertheless viewing a new skilled strategy you dealt with that took me to jump for contentment. Now i’m happier for your advice and thus expect you know what an amazing job your are carrying out educating most people all through your web site. I am certain you haven’t encountered all of us.

    Reply
  5. I’d have to examine with you here. Which is not one thing I usually do! I take pleasure in reading a post that may make folks think. Additionally, thanks for permitting me to comment!

    Reply
  6. Hello There. I found your blog using msn. This is a really well written article. I will make sure to bookmark it and return to read more of your useful info. Thanks for the post. I’ll certainly comeback.

    Reply
  7. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to create my own blog and would like to find out where u got this from. appreciate it

    Reply
  8. I’ve been browsing on-line more than three hours as of late, yet I never discovered any attention-grabbing article like yours. It is pretty value sufficient for me. In my view, if all site owners and bloggers made just right content material as you probably did, the web might be much more useful than ever before.

    Reply
  9. Wow that was unusual. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyway, just wanted to say wonderful blog!

    Reply
  10. We are a gaggle of volunteers and starting a new scheme in our community. Your website provided us with helpful information to work on. You’ve done a formidable task and our entire neighborhood can be thankful to you.

    Reply
  11. Greetings from Ohio! I’m bored to tears at
    work so I decided to check out your website on my iphone during lunch break.
    I enjoy the knowledge you provide here and can’t wait to
    take a look when I get home. I’m surprised at how fast your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, great blog!

    Also visit my site slot gacor4d

    Reply
  12. Howdy I am so glad I found your blog, I really found you
    by error, while I was searching on Google for something else, Regardless I am here now and would just
    like to say many thanks for a remarkable post and a
    all round interesting blog (I also love the theme/design), I don’t have time to read it all at the moment but I have saved it and
    also added your RSS feeds, so when I have time I will be back to read
    a lot more, Please do keep up the fantastic work.

    Look into my page: slot303 (http://www.rgo303b.Com)

    Reply

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock