Fundamentals of C Guide
Fundamentals of C Guide
FUNDAMENTALS OF C
Why Learn C?
• C is considered mother of all programming languages as many later languages like Java, PHP
and JavaScript have borrowed syntax/features directly or indirectly from the C.
• If a person learns C programming first, it helps to learn any modern programming language as it
provide a deeper understanding of the fundamentals of programming and underlying
architecture of the operating system like pointers, working with memory locations etc.
• C is widely used in operating systems, embedded systems, compilers, databases, networking,
game engines, and real-time systems for its efficiency to work in low resource environment and
hardware-level support.
STRUCTURE OF C PROGRAM
1
Fundamentals of C and DSA Readiness
2
Fundamentals of C and DSA Readiness
DATA TYPES IN C
C is a statically type language where each variable's type must be specified at the declaration and once
specified, it cannot be changed.
3
Fundamentals of C and DSA Readiness
Additional Concepts
• Size of Data Types: Architecture-dependent. Always use sizeof() to confirm sizes on your system.
• Literals in C: Fixed values directly assigned to variables. Example: int a = 10; → 10 is a literal.
• Type Conversion: Changing one data type into another.
▪ Implicit conversion (type promotion) is done automatically by the compiler.
▪ Explicit conversion (type casting) is done manually by the programmer.
Keywords: Keywords are predefined or reserved words that have special meaning to the C compiler.
They form part of the syntax and cannot be used as identifiers (variable names, function names, etc.).
Each keyword serves a specific purpose in the language.
Ex: auto, break, case, char, const, continue, do, double, else, enum, extern, float, for, etc.
4
Fundamentals of C and DSA Readiness
scanf()
The scanf() function is used to read input from the user. It requires format specifiers and the address of
variables where input will be stored.
• Syntax:
scanf("formatted_string", &variables);
• Examples:
▪ scanf("%d", &age); → reads an integer.
▪ scanf("%c", &ch); → reads a single character.
▪ scanf("%s", str); → reads a single word (stops at space).
fgets()
The fgets() function is a safer alternative to scanf for strings since it can read multiple words (with
spaces) and prevents buffer overflow.
• Syntax:
fgets(str, n, stdin);
• Example:
fgets(str, 100, stdin); → reads a line of input (up to 99 characters).
OPERATORS IN C
Operators 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 operands.
Unary, Binary and Ternary Operators
On the basis of the number of operands they work on, operators can be classified into three types:
1. Unary Operators: Operators that work on single operand. Ex: Increment (++), Decrement (--)
2. Binary Operators: Operators that work on two operands. Ex: Addition (+), Subtraction (-)
3. Ternary Operators: Operators that work on three operands. Ex: Conditional Operator(? : )
5
Fundamentals of C and DSA Readiness
1. if
The simplest form of decision-making, used to execute a block only when a condition is true. It acts like
a gatekeeper — for instance, checking whether a value meets a certain threshold before moving forward.
Since it only checks one condition, it’s efficient for simple validations.
2. if-else
Provides a clear choice between two paths, ensuring that when one condition is false, the alternate block
is executed. This makes programs more robust, as both scenarios are accounted for. It’s widely used in
situations where there are exactly two outcomes, such as checking login credentials.
3. Nested if-else
Used when decisions depend on multiple levels of conditions, like a chain of validations where one
check leads to another. It offers more control but can reduce readability if overused, so interviewers
often ask about alternatives like switch or logical operators to simplify nested structures.
4. if-else-if Ladder
Best suited when multiple conditions are evaluated in sequence. As soon as one condition is true, the
rest are skipped, making it efficient for range-based checks such as grading systems or salary brackets.
A common interview point is knowing that order matters — once a condition matches, others won’t be
checked.
6
Fundamentals of C and DSA Readiness
5. switch
A cleaner alternative to if-else-if when comparing the same variable against many values. It improves
readability and avoids deeply nested conditions. However, it only works with integral or character
values (not floats or strings in standard C). In interviews, you might be asked why switch is sometimes
preferred: the answer is that compilers often optimize it using jump tables, making execution faster in
cases with many discrete options.
6. Jump Statements in C
Jump statements in C allow an unconditional change in control flow, making execution jump directly
to another part of the program. They are often used in loops and functions to alter the normal sequence
of execution.
• break: The break statement is used to terminate a loop or switch immediately and pass control to
the statement after it. It is useful when the required result is already found, avoiding unnecessary
iterations.
• continue: The continue statement skips the current iteration of a loop and jumps to the next one. It
is often used when certain cases need to be ignored without stopping the loop.
• goto: The goto statement provides an unconditional jump to a labelled part of the same function.
While powerful, it makes code harder to maintain and is rarely recommended except in special
scenarios like exiting nested loops.
• return: The return statement ends the execution of a function and optionally sends a value back to
the caller. It is essential for modular programming and differs from other jump statements by exiting
the whole function rather than just a loop.
LOOPS
Loops in C programming are used to repeat a block of code until the specified condition is met. It allows
programmers to execute a statement or group of statements multiple times without writing the code
again and again.
1. for loop
The for loop is an entry-controlled loop where the initialization, condition, and update are all written in
one line. It is mainly used when the number of iterations is known in advance, like printing numbers 1
to 10 or traversing an array.
7
Fundamentals of C and DSA Readiness
2. while loop
The while loop is also entry-controlled but only checks a condition. Initialization and updates must be
handled manually. It is useful when the number of iterations is not fixed, such as reading input until a
user enters a specific value.
3. do-while loop
The do-while loop is exit-controlled, meaning the loop body executes at least once before checking the
condition. It is often used in menu-driven programs where the menu must appear at least once regardless
of the user’s choice.
4. Infinite loop
An infinite loop occurs when the condition never becomes false, causing the loop body to repeat
endlessly. While usually an error, it is sometimes deliberately used in event-driven systems, like waiting
for user input or running servers.
5. Nested loops
Nested loops are loops inside loops, where the inner loop runs fully for each iteration of the outer loop.
They are especially useful for working with matrices, 2D arrays, or pattern-printing problems.
FUNCTIONS IN C
Functions are the block of statements enclosed that perform some specific task. They provide code
reusability and modularity to the program.
Function Syntax:
return_type function_name(parameter_list) {
// body of the function
}
• Return type: Specifies the type of value the function will return. Use void if the function does not
return anything.
• Function name: A unique name that identifies the function. It follows the same naming rules as
variables.
• Parameter list: set of input values passed to the function. If the function takes no inputs, this can
be left empty or written as void.
• Function body: The block of code that runs when the function is called. It is enclosed in curly
braces {}.
RECURSION IN C
Recursion is a technique where a function calls itself until a base condition is met. Such a function is
called a recursive function, and each call is known as a recursive call. It helps in solving complex
problems by breaking them into smaller subproblems.
A recursive function has two parts:
1. Base Case – defines when the recursion stops.
2. Recursive Case – the step where the function calls itself with modified arguments.
Types of Recursion
Recursion can take different forms depending on the structure of calls:
• Linear Recursion – one recursive call at a time.
• Tree Recursion – multiple recursive calls (like in divide-and-conquer).
• Tail Recursion – the recursive call is the last operation in the function.
Applications of Recursion
Recursion is widely used in problem-solving, competitive programming, and interviews. Common
applications include:
• Mathematical Problems – factorial, Fibonacci, GCD.
• Tree/Graph Algorithms – DFS, traversals.
• Divide and Conquer – Merge Sort, Quick Sort, Binary Search.
• Dynamic Programming – solving overlapping subproblems efficiently.
9
Fundamentals of C and DSA Readiness
ARRAYS
An 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.
1. Array Declaration
Before using an array, it must be declared by specifying its data type, name, and size. For example,
declaring an integer array of size 5 reserves memory for 5 integers placed one after another. This ensures
fast random access, but the size remains fixed once declared.
2. Array Initialization
Initialization means assigning values when the array is created. Some common ways are:
int arr[5] = {2, 4, 8, 12, 16}; // full initialization
int arr[5] = {2, 4, 8}; // partial (remaining set to 0)
int arr[] = {2, 4, 8, 12, 16}; // size skipped, compiler decides
int arr[5] = {0}; // all elements initialized to 0
Key Note: If no initialization is provided, the array holds garbage values, which is unsafe for problem-
solving.
3. Accessing and Updating Elements
Elements are accessed by their index (0 to size–1). For example, the first element is at index 0, and the
last is at index size–1. Updating is just replacing the value at a specific index. This provides O(1) access
time, which is one of the biggest advantages of arrays.
4. Array Traversal
Traversal means visiting each element, usually through loops. Arrays can be traversed in forward order
or reverse order depending on the requirement. Traversal is important for searching, summing, or
processing array data, and it usually costs O(n) time.
2D Arrays
A 2D array is like an array of arrays, often used to represent tables or matrices. Elements are arranged
in rows and columns, and access requires two indices: one for the row and one for the column. For
example, a 3×3 2D array can represent a matrix in mathematics.
Syntax: data_type arr_name [size1][size2];
10
Fundamentals of C and DSA Readiness
STRINGS
A 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.
1. Declaration and Initialization
In C, a string is simply a one-dimensional array of characters. It can be declared using the syntax:
char string_name[size];
Strings can be initialized either by providing a list of characters or directly using a string literal.
For example:
// Using character list
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Using string literal
char str[] = "Hello";
When initialized with double quotes, the compiler automatically appends a null character '\0' at
the end to indicate the end of the string.
2. Taking User Input
Strings can also be read from the user. For single words, scanf("%s", str); works but stops at
spaces. To read full lines with spaces safely, fgets(str, sizeof(str), stdin); is preferred, as it captures
the entire line until a newline is encountered.
3. Printing Strings
printf("The string is: %s\n", str);
The %s format specifier prints characters from the array until it finds the null character '\0', which
marks the end of the string.
C language provides some useful functions for string manipulation in <string.h> header file. Some of
them are as follows:
11
Fundamentals of C and DSA Readiness
POINTERS
A pointer is a variable that stores the memory address of another variable instead of the actual value. It
is a powerful feature in C for memory manipulation. Accessing the pointer directly gives its stored
address, while dereferencing it retrieves the actual value.
1. Declaration – A pointer is declared by placing an asterisk * before its name along with the data
type it points to. For ex: int *ptr; declares a pointer to an integer, while float *fptr; declares a
pointer to a float. The type ensures the pointer can only store the address of that particular data
type.
2. Initialization – Pointers must be initialized with the address of a variable using the address-of
operator &. Example:
int var = 10;
int *ptr = &var;
3. Dereferencing – To access the value stored at the memory address, we use the dereference
operator *. For instance, printf("%d", *ptr); prints the value of var. Here, *ptr gives the value at
the location ptr is pointing to.
4. Size of Pointers – The size of a pointer depends on the system architecture, not on the data type.
On a 32-bit system, all pointers typically occupy 4 bytes, while on a 64-bit system, they occupy 8
bytes. This is because all pointers only store memory addresses.
5. Special Types of Pointers –
• NULL Pointer: Points to nothing (int *ptr = NULL;). Used for safe checks before accessing
memory.
• Void Pointer: A generic pointer that can store the address of any type (void *ptr;). Requires
typecasting before dereferencing.
• Wild Pointer: An uninitialized pointer that may point to a random memory location. Dangerous
if used.
• Dangling Pointer: A pointer that refers to memory already freed or deleted, leading to undefined
behavior.
Key Note: Always initialize pointers (preferably with NULL) before use to avoid wild or dangling
pointer issues.
12
Fundamentals of C and DSA Readiness
C STRUCTURES
In C, a structure is a user-defined data type that can be used to group items of possibly different types
into a single type. The struct keyword is used to define a structure. The items in the structure are called
its members and they can be of any valid data type. Applications of structures involve creating data
structures Linked List and Tree. Structures in C are also used to represent real world objects in a software
like Students and Faculty in a college management software.
Syntax of Structure
There are two steps of creating a structure in C:
1. Structure Definition
2. Creating Structure Variables
Structure Definition
A structure is defined using the struct keyword followed by the structure name and its members. It is
also called a structure template or structure prototype, and no memory is allocated to the structure in
the declaration.
struct structure_name {
data_type1 member1;
data_type2 member2;
...
};
• structure_name: Name of the structure.
• member1, member2, ...: Name of the members.
• data_type1, data_type2, ...: Type of the members.
Be careful not to forget the semicolon at the end.
Creating Structure Variable
After structure definition, we have to create variable of that structure to use it. It is similar to the any
other type of variable declaration:
struct structure_name var;
We can also declare structure variables with structure definition.
struct structure_name {
...
}var1, var2....;
13
Fundamentals of C and DSA Readiness
14
Fundamentals of C and DSA Readiness
• HACKERRANK PROBLEMS
1. Solve Me First
2. C - Hello World!
3. Pointer in C
4. 1D Arrays in C
5. Functions in C
6. Bitwise Operators
7. Students Marks Sum
8. Calculate the Nth term
9. Dynamic Array in C
10. Printing Tokens
• LEETCODE PROBLEMS
1. Two Sum
2. Reverse Integer
3. Palindrome Number
4. Remove Duplicates from Sorted Array
5. Remove Element
6. Implement strStr()
7. Search Insert Position
8. Maximum Subarray
9. Length of Last Word
10. Plus One
15