Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views15 pages

Fundamentals of C Guide

Uploaded by

tunknown359
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)
9 views15 pages

Fundamentals of C Guide

Uploaded by

tunknown359
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/ 15

Fundamentals of C and DSA Readiness

FUNDAMENTALS OF C

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 programming languages.

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

Header Files Inclusion - Line 1 [#include <stdio.h>]


C programs usually begin with header files. These files have the extension .h and contain function
declarations and macro definitions that can be used in the program. For example, #include <stdio.h>
allows us to use input/output functions like printf() and scanf().
Think of header files as a toolbox: instead of building a tool from scratch, you open the ready-made set.
Some common header files are:
• stdio.h → Input/Output functions
• stdlib.h → Memory allocation, conversions, random numbers
• string.h → String handling functions
• math.h → Mathematical functions
• stdint.h → Integer types of exact widths
• stddef.h → Useful types and macros

Main Method Declaration - Line 2 [int main()]


Every C program begins its execution from the main function. It acts as the entry point. The keyword
int before main means it returns an integer value back to the operating system.
The returned value (often 0) indicates the status of program termination. A return of 0 generally means
the program ran successfully. You can think of main() as the entrance gate of a house — no matter
how many rooms (functions) there are, execution always starts here.
Body of Main Method - Line 3 to Line 6 [enclosed in {}]
The body of the main method in the C program refers to statements that are a part of the main function.
It can be anything like manipulations, searching, sorting, printing, etc. A pair of curly brackets define
the body of a function. All functions must start and end with curly brackets.
Comment - Line 7[// This prints "Hello World"]
The comments are used for the documentation of the code or to add notes in your program that are
ignored by the compiler and are not the part of executable program.
Statement - Line 4 [printf("Hello World");]
Statements are the instructions given to the compiler. In C, a statement is always terminated by
a semicolon (;). In this particular case, we use printf() function to instruct the compiler to display "Hello
World" text on the screen.

Return Statement - Line 5 [return 0;]


The last part of any C function is the return statement. The return statement refers to the return values
from a function. This return statement and return value depend upon the return type of the function. The
return statement in our program returns the value from main(). The returned value may be used by an
operating system to know the termination status of your program. The value 0 typically means
successful termination.
Execute C Programs
To run this program, you need to create a development environment for C. A development environment
mainly consists of a text editor, which is used to write the code, and a compiler that converts the written
code into the executable file.
Source File → Preprocessor (Preprocessed File .i file) → Compiler (Assembly code .s file) →
Assembler (Object code .o file) → Linker → Executable.

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.

Integer Data Type


The int data type is used to store whole numbers (positive, negative, or zero) without decimals. In C,
integers can be represented in decimal, octal, or hexadecimal formats.
• Size: 4 bytes
• Format Specifier: %d
• Variants:
▪ unsigned int → only non-negative numbers.
▪ short int → smaller storage, usually 2 bytes.
▪ long int → larger storage than int.
▪ unsigned short int → non-negative smaller values.
Character Data Type
The char type stores a single character, requiring just 1 byte of memory.
• Size: 1 byte
• Format Specifier: %c
• It can hold letters, digits, or symbols but only one at a time.
Float Data Type
The float type stores single-precision decimal numbers. It is commonly used when memory saving is
more important than precision.
• Size: 4 bytes
• Format Specifier: %f

Double Data Type


The double type stores double-precision decimal numbers, allowing greater accuracy and larger values
than float.
• Size: 8 bytes
• Format Specifier: %lf

3
Fundamentals of C and DSA Readiness

Void Data Type


The void type represents the absence of a value. You cannot declare variables of this type, but it is used
for:
• Function return type (when nothing is returned).
• Function parameters (when no parameters are passed).
• Void pointers (to hold address of any data type).

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 AND IDENTIFIERS IN C


Identifiers: In C programming, identifiers are the names used to represent variables, functions, arrays,
structures, or other user-defined elements. They act as unique labels that allow the programmer to
refer to these elements later in the program.
Rules for Naming Identifiers
• Can include letters (A–Z, a–z), digits (0–9), and the underscore (_).
• The first character must be a letter or underscore.
• Identifiers are case-sensitive (Age and age are different).
• Cannot be a C keyword (e.g., int, return, if, while).

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.

INPUT AND OUTPUT IN C


printf()
The printf() function is used to display formatted output on the screen. It allows text, variables, and
formatted strings to be printed together.
• Syntax:
printf("formatted_string", variables/values);
• Example:
printf("Age is %d\n", age); → prints the value of variable age along with text.
fputs()
The fputs() function outputs strings, typically to files, but it can also print to the console when used with
stdout.
• Syntax:
fputs("your text here", stdout);
• Example:
fputs("Hello World", stdout); → prints Hello World.

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

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 not.

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 {}.

Function Declaration vs Definition


• A declaration tells the compiler about the function’s name, return type, and parameters, but does
not provide the body. It is often placed at the top of a program or in header files.
• A definition includes the actual body (logic) of the function. The compiler needs the declaration
before a function is called if the definition comes later in the program.
Function Call
Once declared and defined, a function is executed by calling it. Function calls help avoid code
repetition, improve readability, and allow breaking large problems into smaller sub-problems.
Types of Functions
• Library Functions: Built-in functions provided by C, like printf(), scanf(), sqrt().
• User-Defined Functions: Written by programmers for specific tasks. These can be:
▪ No arguments, no return value
8
Fundamentals of C and DSA Readiness

▪ With arguments, no return value


▪ No arguments, with return value
▪ With arguments and return value
Parameters in Functions
• Formal Parameters: Variables in the function header that act as placeholders.
• Actual Parameters: The real values/variables passed during the function call.

Parameter Passing Methods


• Pass by Value: A copy of the value is passed. Changes inside the function don’t affect the original
variable. Simple but inefficient for large data.
• Pass by Pointers (Call by Reference in C): The memory address of the variable is passed. Changes
made inside the function affect the original variable. Efficient for large structures but error-prone if
pointers are misused.
Call by Value vs Call by Reference
• Call by Value: Original variable remains unchanged, uses more memory (copies).
• Call by Reference: Original variable may change, memory-efficient as only the address is passed.

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.

How Recursion Works


When a recursive function is called, the current state is stored on the call stack. Each new call pushes
another stack frame, and once the base case is reached, the stack starts to unwind in reverse order. This
leads to two phases:
• Descending Phase – function keeps calling itself, going deeper.
• Ascending Phase – after reaching the base case, functions return back step by step.
If the base case is missing or wrong, recursion can go infinite and cause a stack overflow error.

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....;

Basic Operations of Structure


Following are the basic operations commonly used on structures:
1. Access Structure Members
To access or modify members of a structure, we use the (.) dot operator. This is applicable when we are
using structure variables directly.
structure_name . member1;
structure_name . member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access the
members.
structure_ptr -> member1
structure_ptr -> member2

13
Fundamentals of C and DSA Readiness

2. Initialize Structure Members


Structure members cannot be initialized with the declaration. We can initialize structure members in 4
ways which are as follows:
• Initialization of Structures in C
By default, structure members are not initialized; they contain garbage values unless explicitly
assigned. However, if a structure is declared with an initializer, unspecified members are
automatically set to zero, e.g.,
struct Point p = {0}; // all members become 0
• Initialization using Assignment Operator – After declaration, individual members can be
assigned values directly, e.g.,
struct Point p1;
p1.x = 10;
p1.y = 20;
Note that arrays or strings inside structures cannot be assigned this way.
• Initialization using Initializer List – Values can be given in order at declaration:
struct Point p2 = {5, 15};
Here, values are assigned sequentially in the order of member declaration.
• Initialization using Designated Initializer List – Introduced in C99, this allows initializing
members in any order using their names:
struct Point p3 = {.y = 50, .x = 25};
3. typedef for Structures
The typedef keyword is used to define an alias for the already existing datatype. In structures, we have
to use the struct keyword along with the structure name to define the variables. This increases the length
and complexity of the code. We can use the typedef to define some new shorter name for the structure.

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);

14
Fundamentals of C and DSA Readiness

CRACK THE CODE: INTERVIEW-ORIENTED PRACTICE PROBLEMS


Boost your problem-solving skills with curated problems from HackerRank and LeetCode. These
questions are widely asked in technical interviews and company drives. Links are embedded for direct
access.

• 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

You might also like