0% found this document useful (0 votes)
4 views14 pages

C Cheatsheet

This document is a comprehensive cheatsheet for the C programming language, covering basic syntax, data types, operators, control structures, functions, pointers, structures, unions, file handling, dynamic memory allocation, mathematical functions, and randomization functions. It includes examples and explanations of key concepts such as variables, literals, escape sequences, and how to compile C programs using GCC. Additionally, it lists standard header files and their respective functions.

Uploaded by

psydoctor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

C Cheatsheet

This document is a comprehensive cheatsheet for the C programming language, covering basic syntax, data types, operators, control structures, functions, pointers, structures, unions, file handling, dynamic memory allocation, mathematical functions, and randomization functions. It includes examples and explanations of key concepts such as variables, literals, escape sequences, and how to compile C programs using GCC. Additionally, it lists standard header files and their respective functions.

Uploaded by

psydoctor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

PRICING CHALLENGES COMPANY & MORE

C Programming language Cheatsheet


6129 4 years ago

Basics
scanf("%d", &x); -- read value into the variable x from input stream
printf("%d",x); -- printf value to the output stream
gets(str); -- reads a line from input stream into a variable
scanf("%[^\n]",s); --reads a line from input using scanf only

Sample C program

#include <stdio.h>
int main() {
printf("Hello World!!");
return 0;
}

#include is a keyword which is used to include header les like : <stdlib.h>


and <stdio.h>.
<stdio.h> library le is used to read the data from terminal and to display the
data on terminal. It has several in-built functions like printf(), scanf() etc.
main() function is the entry point of any C program.
printf and scanf are inbuilt library functions which are used for input and
output in C language. They are de ned in stdio.h header le.
return 0 is used to terminate the main() function and returns the value 0
// -- single line comment
/* comments */ -- Multi line comment

Data types

Types Data-type

Basic bool, void, int/long, long long, char, oat, double

Derived array, pointer, structure, union

Enumeration enum
Types Data-type

Void void

1. Basic Data types

Data type Description Range Memory Size Format speci er

-2,147,4
used to store 83,648
int whole to 4 bytes %d
numbers 2,147,48
3,647

used to store
0 to
unsigned non-negative
4,294,96 4 bytes %u
int whole
7,295
numbers

used to store -32,768


short int whole to 2 bytes %hd
numbers 32,767

used to store
unsigned non-negative 0 to
2 bytes %hu
short int whole 65535
numbers

-2,147,4
used to store 83,648
long int whole to 4 bytes %ld
numbers 2,147,48
3,647

used to store
0 to
unsigned non-negative
4,294,96 4 bytes %lu
long int whole
7,295
numbers

used to store -(2^63)


long long
whole to 8 bytes %lld
int
numbers (2^63)-1
Data type Description Range Memory Size Format speci er

used to store
unsigned
non-negative 0 to
long long 4 bytes %llu
whole (2^64)
int
numbers

used to store 6 to 7
oat fractional decimal 4 bytes %f
numbers digits

used to store 15
double fractional decimal 8 bytes %lf
numbers digits

used to store a one


char single characte 1 bytes %c
character r

2. Derived Data types

Arrays:

data-type array-name[size];

Pointers:

datatype *pointername;

Structures:

struct structure_name {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

struct structure_name variable name;

3. Enumeration Data types non-negative

enum name{constant1, constant2, constant3, ....... };

4. Void Data types


Void speci es that there is no return value. Generally used when function returns no
value, pointer with type as void represents the address of an object but not it's type.

Variables

Syntax:

data-type variable-name = value;

Example:

int x = 10; // declaring int variable and assigning value 10 to it


char grade = 'A'; // declaring char variable and assigning value A to it

Based on scope, Variables can be classified into two types:


Local Variables
Global Variables

Literals
Literals are the constant values assigned to the constant variables.

Literal Example

Integer Literal- decimal 255

Integer Literal- octal 0377

Integer Literal- hexadecimal 0xFF

Float point Literal 53.0f, 79.02

Character literals 'a', '1'

String literals "OneCompiler", "Foo"

Escape sequences

Escape sequence Description

\n New line

\r Carriage Return

? Question mark

\t Horizontal tab
Escape sequence Description

\v Vertical tab

\f Form feed

\ Backslash

' Single quotation

" Double quotation

\0 Null character

\b Back space

\a Alarm or Beep

\nnn Octal Number

\xhh hexadecimal Number

Arrays
Array in C can be de ned as a method of clubbing multiple entities of similar type
into a larger group.

One dimentional Array:

data-type array-name[size];

Example

int a[5] = {1,2,3,4,5};

Two dimensional array:

data-type array-name[size][size];

Example

int a[2][3] = {
{1,2,3},
{4,5,6}
};

Operators
Operator type Description

Arithmetic Operators +,-,*,/,%

Comparison Operators < , > , <= , >=, != , ==

Bitwise Operators & , ^ , |, <<, >>

Logical Operators && , ||, !

Assignment Operators = , += , -= , *= , /= , %=, <<=, >>=, &=, ^=, |=

Ternary Operators ?:

sizeof operators sizeof()

Keywords(reserved words)
Keywords are words that have special meaning to the C compiler. These words help
us to use the functionality of C language.
There are 32 keywords in C language.

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
alignas nullptr typeof alignof

Identi ers
Identi ers are user de ned names for variables, functions and arrays.

Rules:

They must be less than or equal to 31 characters.


No special characters.
Must start with a letter or under score.
Can contain letters, digits, or underscore only.
We can not use C keywords as a variable name.

Strings
Strings are an array of characters ended with null character. Enclosed in double
quotes.

Declaration

char str[]="onecompiler";

Function Description Example

gets() It allows you to enter multi-word string gets("string")

puts() It is used to show string output puts("string")

It is used to calculate the length of the strlen(string_name


strlen()
string )

It is used to copy the content of second- strcpy(destination


strcpy()
string into the rst string passed to it , source)

strcat(first_strin
strcat() It is used to concatenate two strings
g, second_string)

strcmp(first_strin
strcmp() It is used to compare two strings
g, second_string)

strrev() It is used to return reverse of a string strrev("string")

strupr() It return string characters in uppercase strupr("string")

strlwr() It return string characters in lowercase strlwr("string")

strcasec It compares two strings without strcasecmp(string1


mp() comparing the sensitivity of the case , string2)

It concatenates n characters of one string strncat(destinatio


strncat()
to another string n , source, size)

It stores the value in a pointer variable strstr(string1 ,


strstr()
and takes two strings as input string2)

Constants
Constants are the xed values. They can be declared in two ways as shown below:

const datatype <constant-name> = <constant-value>;

#define <constant-name> <constant-value>

Special characters
{} : speci es start and end of code blocks
[] : used for arrays
() : used for functions
, : used to seperate variables, constants etc
* : used for pointers
# : used as a macro processor.

Conditional Statements

1. If

if(conditional-expression)
{
//code
}

2. If-else

if(conditional-expression)
{
//code
} else {
//code
}

3. If-else-if ladder

if(conditional-expression-1)
{
//code
} else if(conditional-expression-2) {
//code
} else if(conditional-expression-3) {
//code
}
....
else {
//code
}

4. Switch

switch(conditional-expression){
case value1:
//code
break; //optional
case value2:
//code
break; //optional
...

default:
//code to be executed when all the above cases are not matched;
}

Loops

1. For

for(Initialization; Condition; Increment/decrement){


//code
}

2. While

while (condition){
//code
}

3. Do-While

do {
//code
} while (condition);

Functions
Function is a sub-routine which contains set of statements.

// declaring a function
return_type function_name(parameters);

// defining a function
return_type function_name(parameters){
//code
}

// calling a function
function_name (parameters)

Pointers
Pointer is a variable which holds the memory information(address) of another
variable of same data type.
datatype *pointername;

Example

int x = 10, *ptr;

/*ptr = x; // Error because ptr is adress and x is value


*ptr = &x; // Error because x is adress and ptr is value */

ptr = &x; // valid because &x and ptr are addresses


*ptr = x; // valid because both x and *ptr values

int a[10];
ptr = a; // since a is the address of the first element in array (a[0])
ptr++; // pointer points to next array element (a[1])

Types of Pointers

Serial Number Pointer Description

We can create a null pointer by assigning


Null the null value at the time when we are
1
Pointer declaring the pointer.It always contains the
value 0

This pointer has no associated data-type


with it. A void pointer can hold addresses
Void
2 of any data-type and can be typecasted to
Pointer
another.It is created by using the keyword
void

They are also called as uninitialised


pointers.They are called so because they
Wild point to some arbitary memory location that
3
Pointer is randomly alloted and the program can
misbehave badly.This type of pointer is not
efficient.

The pointers that are pointing to


Dangli deallocated memory or deleted memory block
4 ng are known as Dangling pointers.They can
Pointer raise an error because they point to a
deallocated memory block.

Structures
Structure is a user-de ned data type where it allows you to combine data of
different data types.

struct structure_name {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

struct structure_name variable name; //declaring structure variables

Unions
Union is a user-de ned datatype similar to structs which allows to store different
data types in the same memory location. In Unnions, one member can contain a
value at any given time.

union union_name {
member definition;
member definition;
...
member definition;
} [one or more union variables];

union union_name variable name; // Declaring Union Variables

File handling
File operations like create, update, read, and deleting les which are stored on the
local le system can be performed in C.

FILE *fptr; //declaring a pointer of type File


fptr = fopen("filename",mode); //opening a file
fscanf(fptr, "format specifier", data); //read a file
fprintf(fptr, "format specifier", data); //write a file
fclose(fptr);

Mode Description

r Opens for reading.

rb Opens for reading in binary mode.

r+ Opens for both reading and writing.

w Opens for writing.


Mode Description

wb Opens for writing in binary mode.

a Opens for append.

ab Opens for append in binary mode.

w+ Opens for both reading and writing.

wb+ Opens for both reading and writing in binary mode.

rb+ Opens for both reading and writing in binary mode.

a+ Opens for both reading and appending.

ab+ Opens for both reading and appending in binary mode.

Dynamic Memory Allocation


A set of functions for dynamic memory allocation from the heap. These methods are
used to use the dynamic memory which makes our C programs more ef cient

Function Description Example

ptr =
(castType*
Stands for 'Memory allocation' and reserves a block
malloc() )
of memory with the given amount of bytes.
malloc(siz
e)

ptr =
Stands for 'Contiguous allocation' and reserves n (castType*
calloc()
blocks of memory with the given amount of bytes. )calloc(n,
size)

free It is used to free the allocated memory. free(ptr)

If the allocated memory is insuf cient, then we can ptr =


realloc() change the size of previously allocated memory realloc(pt
using this function for ef ciency purposes r, x)

Header Files

Header Files Description

stdio.h Input/Output functions


Header Files Description

conio.h Console Input/Output functions

stdlib.h General utility functions

math.h Mathematics functions

string.h String functions

ctype.h Character handling functions

time.h Date and time functions

oat.h Limits of oat types

limits.h Size of basic types

Functions to determine the type contained in wide character


wctype.h
data

assert.h Contain macro used to assist with detecting logical error

Mathematical Functions
All functions de ned under <math.h> header le.

Function Description

sin(a) Computes sine of the double angle (in radians)

cos(a) Computes cosine of the double angle (in radians)

tan(a) Computes tangent of the double angle (in radians)

asine(a) Computes principle inverse of the sine (in radians)

acos(a) Computes principle inverse of the cosine (in radians)

atan(a) Computes principle inverse of the tangent (in radians)

atan2(a) Computes principle inverse of tan(y/x) in same quadrant as (x,y)

sqrt(x) Computes square root of x

log(x) Computes natural logarithm of x (to the base e)

log2(x) Computes natural logarithm of x (to the base 2)

log10(x) Computes natural logarithm of x (to the base 10)

exp(p) Computes e to the power of p


Function Description

exp2(p) Computes 2 to the power of p

exp10(p) Computes 10 to the power of p

pow(x,y) Computes x to the power of y

ceil(x) Computes smallest integer (returned as double) no less than x

oor(x) Computes largest integer (returned as double) no greater than x

abs(x) Computes the absolute value of x

Randomize Functions
All functions de ned under <stdlib.h> header le. These randomized functions are
pseudo-random (time-based random functions).

random() : returns a random long


srandom(seed) : seeds the random generator with a new random seed

How To Compile in GCC


gcc prog.c : compiles prog.c into a.out, run result with ./a.out.
gcc -o prog prog.c : compiles prog.c into prog, run result with ./prog.
gcc -g -o prog prog.c : as above, but allows for debugging.

use of f ush()
*used to clear the buffer
*used to accept the next string

You might also like