C Programming For CA
C Programming For CA
UNIT 1 :
INTRODUCTION TO C LANGUAGE:
C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell
Laboratories in 1972. It is a foundational language in computer science, known for its efficiency,
performance, and ability to interact closely with hardware.
Key Characteristics:
Mid-level Language:
C bridges the gap between low-level assembly languages and high-level languages, offering both
control over hardware and readability for programmers.
Procedural:
C programs are structured around functions, which are blocks of code designed to perform specific
tasks. This promotes modularity and code reusability.
Efficiency and Performance:
C provides direct memory access through pointers and offers features for optimizing code, making it
suitable for resource-constrained environments and performance-critical applications.
Portability:
C programs are generally highly portable, meaning they can be compiled and run on different operating
systems and hardware platforms with minimal modifications.
Influence on Other Languages:
Many modern programming languages, including C++, Java, Python (CPython), and JavaScript, have
borrowed syntax and concepts from C.
Applications:
C is widely used in various domains, including:
Operating Systems:
Kernels of operating systems like Unix and Linux are primarily written in C.
Device Drivers:
C is extensively used to develop device drivers that allow operating systems to interact with hardware
components.
Embedded Systems:
Due to its efficiency and low-level access, C is popular for programming microcontrollers and
embedded systems.
Compilers and Interpreters:
C is often used to create compilers and interpreters for other programming languages.
Databases, Networking, and Game Engines:
C's performance and control make it suitable for developing core components in these areas.
FEATURES OF C:
The main features of the C programming language include it being a fast, efficient, and portable
language with structured programming capabilities, a rich set of built-in operators and libraries, support
for dynamic memory allocation, and low-level memory access through pointers. C is a general-purpose,
middle-level language that offers the benefits of both high-level and low-level languages, making it
suitable for operating systems, embedded systems, and various applications.
Key Features of C:
Portability:
C programs can be written on one machine and run on different platforms with little to no
modification.
Speed and Efficiency:
As a compiled language, C translates directly to machine code, resulting in faster compilation and
execution compared to interpreted languages.
Structured Language:
C supports modular programming, allowing programs to be broken down into smaller, reusable units
called functions, which improves code organization and readability.
Middle-Level Language:
C combines the features of high-level (like high-level abstraction) and low-level (like direct hardware
manipulation) languages, providing flexibility and power.
Rich Libraries:
The C language includes a rich standard library with numerous built-in functions for various tasks, and
programmers can also create and add their own functions.
Dynamic Memory Allocation:
C provides mechanisms for dynamic memory allocation, enabling programs to manage memory
efficiently during runtime.
Pointers:
The language offers direct memory manipulation through pointers, a powerful feature that allows for
efficient memory management and complex data structures.
Extensibility:
C programs can be easily extended by adding new functionalities through custom functions or third-
party libraries.
General-Purpose Language:
C is versatile and used in a wide range of applications, from developing operating systems and
embedded systems to creating compilers and databases.
Simple and Efficient:
C's simple syntax and efficient design make it easy to learn and implement, providing a strong
foundation for more complex programming concepts.
BENEFITS OF C:
The C programming language offers several significant benefits, particularly in areas requiring high
performance and close interaction with hardware:
Efficiency and Speed:
C is a compiled language that provides direct access to memory and hardware, resulting in highly
efficient and fast-executing programs. This makes it suitable for system programming, embedded
systems, and applications where performance is critical.
Portability:
C programs are generally highly portable, meaning code written on one system can often be compiled
and run on different platforms with minimal or no modifications. This is due to its standardized nature
and the widespread availability of C compilers.
Low-Level Memory Management:
C offers features like pointers and dynamic memory allocation, allowing programmers fine-grained
control over memory management. This is crucial for optimizing resource usage and developing
efficient data structures and algorithms.
Foundation for Other Languages:
Learning C provides a strong understanding of fundamental programming concepts, computer
architecture, and how software interacts with hardware. This knowledge forms a solid base for learning
other languages like C++, Java, Python, and more.
System Programming Capabilities:
C's ability to interact directly with hardware and operating system features makes it ideal for
developing operating systems, device drivers, compilers, and other system-level software.
Extensibility and Rich Libraries:
C is an extensible language, allowing users to create and integrate their own functions. It also boasts a
rich set of standard libraries that provide pre-built functions for various common tasks, simplifying
development.
Structured Programming:
C supports structured programming paradigms, enabling the breakdown of complex problems into
smaller, manageable functions or modules. This enhances code readability, maintainability, and
debugging.
COMPILATION OF C PROGRAM:
The compilation of a C program is the process of transforming human-readable source code into an
executable machine code file. This process typically involves four distinct stages:
Preprocessing:
The preprocessor handles directives like #include (for including header files), #define (for macro
expansion), and conditional compilation directives.
Comments are removed during this stage.
The output is an expanded source file, usually with a .i extension.
Compilation:
The compiler takes the preprocessed source code and translates it into assembly language specific to
the target architecture.
Syntax and semantic errors are detected and reported during this phase.
Code optimization may be performed to improve the efficiency of the generated assembly code.
The output is an assembly file, typically with a .s extension.
Assembly:
The assembler converts the assembly language code into machine code (binary instructions) or
relocatable object code.
This object code is specific to the target machine and contains instructions that the CPU can directly
understand.
The output is an object file, typically with a .o (Linux/macOS) or .obj (Windows) extension.
Linking:
The linker combines one or more object files, along with necessary library files (containing pre-
compiled functions), to create a single executable file.
It resolves references to external functions and variables, ensuring all required components are
available.
The output is the final executable file, which can be run on the operating system (e.g., .out on
Linux/macOS, .exe on Windows).
Example using GCC (GNU Compiler Collection):
To compile a C program named main.c into an executable named myprogram:
Code:
gcc main.c -o myprogram
This single command performs all four stages of compilation to produce the final executable. You can
also perform each stage individually using specific GCC options.
FIRST PROGRAM IN C:
The "Hello World" program is traditionally the first program written when learning a new
programming language, including C.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Explanation of the code:
#include <stdio.h>:
This line is a preprocessor directive. It tells the C compiler to include the contents of the stdio.h header
file. stdio.h stands for "standard input/output" and contains declarations for functions like printf(),
which is used to display output.
int main():
This is the main function where the program's execution begins. Every C program must have
a main() function.
int indicates that the main function is expected to return an integer value to the operating system.
The empty parentheses () signify that the main function does not take any arguments.
{ ... }:
These curly braces define the body of the main function. All the statements within these braces will be
executed when the program runs.
printf("Hello, World!\n");:
This statement uses the printf() function to display the string "Hello, World!" on the console.
\n is an escape sequence that represents a newline character, moving the cursor to the next line after
printing the message.
return 0;:
This statement indicates that the main function has completed successfully and returns the integer
value 0 to the operating system.
PREPROCESSOR IN C:
The C preprocessor is a separate program that processes the source code before the actual compilation
begins. It is responsible for handling preprocessor directives, which are special instructions beginning
with a hash sign (#). These directives are interpreted by the preprocessor and result in modifications to the
source code before it is passed to the compiler.
The main functionalities provided by the C preprocessor include:
File Inclusion (#include): This directive is used to include the content of other files (typically header files)
into the current source file. This allows for modular programming and reuse of declarations and
definitions.
C
#include <stdio.h>
#include "myheader.h"
Macro Expansion (#define): Macros are symbolic names or code snippets that are replaced by their
defined values or code during preprocessing. They can be used to define constants or create function-like
macros.
C
#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))
Conditional Compilation (#ifdef, #ifndef, #if, #else, #elif, #endif): These directives allow parts of the
code to be included or excluded from compilation based on certain conditions, such as whether a macro is
defined or the value of an expression.
C
#ifdef DEBUG
#else
#endif
Other Directives:
o #undef: Undefines a previously defined macro.
o #pragma: Provides compiler-specific instructions or settings.
o #error: Generates a compilation error with a specified message.
o #warning: Generates a compilation warning with a specified message.
The preprocessor essentially acts as a text substitution tool, transforming the source code into a form
suitable for the compiler. This process helps in creating more flexible, modular, and maintainable C
programs.
PREPROCESSOR DIRECTIVES:
Preprocessor Directives
#include:
Inserts the contents of another file (like a header file) into the current source file.
#define:
Creates a macro, which is a placeholder for a value or code snippet that the preprocessor replaces
before compilation.
#undef:
Undefines a previously defined macro.
#if, #ifdef, #ifndef:
Used for conditional compilation, these directives control whether certain sections of code are compiled
based on whether a macro is defined or a condition is met.
#else:
Provides an alternative code block if the preceding #if or #ifdef condition fails.
#elif:
Combines the functionality of #else and #if, allowing for checking another condition if the previous
one failed.
#endif:
Marks the end of a conditional compilation block started by #if, #ifdef, or #ifndef.
#error:
Generates a compilation error with a custom message, stopping the compilation process.
#pragma:
Issues special commands to the compiler for controlling its behavior, such as enabling or disabling
warnings.
Key Characteristics
Starts with '#':
Every preprocessor directive begins with the '#' symbol as the first non-whitespace character on the
line.
First Phase:
They are processed as the very first step before the main compilation process takes place.
Textual Changes:
The effect of each directive is a direct modification of the source code's text.
UNIT 2:
VARIABLES:
In C programming, a variable is a named storage location in memory used to hold data.
Key aspects of variables in C:
Declaration: Before using a variable, it must be declared. This involves specifying its data type and
name.
C
int age;
float price;
char initial;
Initialization: Variables can be assigned an initial value during declaration or later in the program.
C
int age = 25;
float price;
price = 19.99;
Data Types:
C supports various data types for variables, including:
int: For whole numbers (integers).
float: For single-precision floating-point numbers (decimals).
double: For double-precision floating-point numbers (more precise decimals).
char: For single characters.
bool: For boolean values (true/false) – requires <stdbool.h> header.
Naming Rules:
Variable names (identifiers) must follow specific rules:
Can contain letters (A-Z, a-z), digits (0-9), and the underscore (_).
Must begin with a letter or an underscore.
Cannot be a C reserved keyword (e.g., int, if, while).
Are case-sensitive (e.g., age and Age are different variables).
Scope:
The scope of a variable defines where in the program it can be accessed.
Local variables: Declared inside a function or block, accessible only within that block.
Global variables: Declared outside any function, accessible throughout the program.
Constants:
Variables whose values cannot be changed after initialization are called constants. They are declared
using the const keyword.
EX:
const float PI = 3.14159;
DATA TYPES IN C:
C programming language utilizes various data types to specify the type of data a variable can hold. These
data types are broadly categorized into:
Primary (or Basic) Data Types:
These are fundamental types built into the language.
int: Stores whole numbers (integers) without decimal points. Can be further modified
with short, long, signed, and unsigned.
char: Stores single characters, including letters, numbers, and symbols. Typically occupies one byte of
memory.
float: Stores single-precision floating-point numbers (numbers with decimal points).
double: Stores double-precision floating-point numbers, offering higher precision and a larger range
than float.
void: A special data type that indicates the absence of a value, commonly used as a return type for
functions that do not return any value, or as a generic pointer type.
OPERATORS IN C:
Operators in C are symbols that instruct the compiler to perform specific mathematical,
relational, logical, or bitwise operations on data.
Types of Operators in C:
1. Arithmetic Operators:
Used for performing mathematical calculations.
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus - returns the remainder of integer division)
++ (Increment - increases value by 1)
-- (Decrement - decreases value by 1)
2.Relational Operators:
Used for comparing two values and determining the relationship between them. They
return a Boolean value (true or false).
== (Equal to)
!= (Not equal to)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
3.Logical Operators:
Used to combine or manipulate Boolean expressions.
&& (Logical AND - true if both operands are true)
|| (Logical OR - true if at least one operand is true)
! (Logical NOT - reverses the logical state of an operand)
4.Bitwise Operators:
Used to perform operations on the binary representation of variables at the bit level.
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT / One's Complement)
<< (Left Shift)
>> (Right Shift)
5.Assignment Operators:
Used to assign values to variables.
= (Simple Assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
Conditional Operator (Ternary Operator):
A shorthand for an if-else statement.
? : (e.g., condition ? expression1 : expression2; )
Special Operators:
A variable name cannot start with a number. It can consist of alphabets, number, underscore “_”.
Here is the syntax of declaring variables in C language,
type variable_name;
Keywords:
Keywords are predefined, reserved words in C language and each of which is associated with specific
features. These words help us to use the functionality of C language. They have special meaning to the
compilers.
do if static while
SCOPE RULES IN C:
Scope rules in C define the visibility and accessibility of identifiers (variables, functions, etc.) within
different parts of a program. They determine where an identifier can be used and how long it remains in
memory.
There are three primary types of scope in C:
Local Scope:
o Variables declared inside a function or a block of code (enclosed within curly braces {}) have local scope.
o They are only accessible within that specific function or block where they are declared.
o Local variables are created when their block is entered and destroyed when the block is exited.
Global Scope:
o Variables declared outside of all functions, typically at the beginning of the program, have global scope.
o They are accessible from any part of the program, including all functions.
o Global variables are created when the program starts and exist until the program terminates.
DATA TYPES IN C:
1.Basic/Primary Data Types:
These are fundamental building blocks.
int: Stores whole numbers (integers) without decimal points. Can be modified with short, long, signed,
and unsigned.
Example: int age = 30;
char: Stores single characters, enclosed in single quotes.
Example: char grade = 'A';
float: Stores single-precision floating-point numbers (numbers with decimal points).
Example: float price = 19.99;
double: Stores double-precision floating-point numbers, offering higher precision than float.
Example: double pi = 3.1415926535;
void: A special data type indicating the absence of a value, often used as a return type for functions that
don't return any value or as a generic pointer type.
Example: void printMessage();
2.Derived Data Types:
These are built upon the basic data types.
Arrays: Collections of elements of the same data type.
Example: int numbers[5];
Pointers: Variables that store memory addresses of other variables.
Example: int *ptr;
Functions: Blocks of code designed to perform a specific task.
User-Defined Data Types:
These are created by the programmer.
Structures (struct): Allow grouping of different data types under a single name.
Example:
struct Student {
char name[50];
int rollNo;
};
Unions (union):
Similar to structures but allow different data types to share the same memory location.
Enumerations (enum):
Provide a way to assign names to integer constants, improving code readability.
Example: enum Day { SUNDAY, MONDAY, TUESDAY };
the size and range of these data types can vary depending on the system architecture (e.g., 32-bit or 64-
bit). Modifiers like signed, unsigned, short, and long can be used with int and char to further specify the
range and storage size.
TYPE CASTING IN C:
Type casting in C is the process of converting a variable or value from one data type to
another. This can be done either implicitly (automatically by the compiler) or explicitly (manually by the
programmer).
Syntax:
int x;
float y;
y = (float) x;
1. Implicit Type Casting (Type Coercion):
This occurs automatically when the compiler converts a data type to another compatible data type without
any explicit instruction from the programmer. This usually happens during assignments or operations
involving mixed data types, where the compiler promotes the "smaller" type to the "larger" type to avoid
data loss.
2. Explicit Type Casting (Manual Type Conversion):
This is performed by the programmer using the cast operator (new_data_type). It allows for explicit
control over data type conversions, especially when the compiler wouldn't perform an implicit conversion
or when a specific type conversion is required.
In C programming, there are 5 built-in type casting functions.
atof(): This function is used for converting the string data type into a float data type.
atbol(): This function is used for converting the string data type into a long data type.
Itoa(): This function is used to convert the long data type into the string data type.
itoba(): This function is used to convert an int data type into a string data type.
atoi(): This data type is used to convert the string data type into an int data type.
UNIT 3:
CONTROL FLOW STATEMENTS:
Control flow statements in C programming dictate the order in which instructions are executed,
allowing for decision-making, repetition, and program flow alteration. These statements are categorized
into three main types:
if (condition)
{
// code to be executed if condition is true
}
IF-ELSE STATEMENT:
Executes one block of code if the condition is true, and another if it's false.
SYNTAX:
if (condition)
{
// code if condition is true
}
Else
{
// code if condition is false
}
ELSE-IF LADDER:
Allows for multiple conditions to be checked sequentially.
SYNTAX:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if none of the above conditions are true
}
SWITCH STATEMENT:
Provides a way to execute different blocks of code based on the value of a single variable or
expression.
SYNTAX:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no match is found
}
WHILE LOOP:
Repeats a block of code as long as a condition remains true.
SYNTAX:
while (condition) {
// code to be executed repeatedly
}
DO-WHILE LOOP:
Executes a block of code at least once, and then repeatedly as long as a condition remains true.
SYNTAX:
do {
// code to be executed repeatedly
} while (condition);
3. JUMP STATEMENTS:
These statements transfer control unconditionally to another part of the program.
BREAK STATEMENT:
Terminates the execution of the innermost loop or switch statement.
CONTINUE STATEMENT:
Skips the rest of the current iteration of a loop and proceeds to the next iteration.
GOTO STATEMENT:
Transfers control to a labeled statement within the same function. Use with caution as it can lead to
less readable and maintainable code.
SYNTAX:
// ...
goto label;
// ...
label:
// code after the jump
RETURN STATEMENT:
Terminates the execution of a function and returns control to the calling function, optionally
returning a value.
ARRAYS IN C:
An array is a linear data structure that stores a fixed-size sequence of elements of the same data
type in contiguous memory locations. Each element can be accessed directly using its index, which
allows for efficient retrieval and modification.
Creating an Array
The whole process of creating an array can be divided into two primary sub processes i.e.
1. Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In C, we have
to declare the array like any other variable before using it.
data_type array_name[size];
Example:
// Creates array arr to store 5 integer values.
int arr[5];
2. Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we need to
initialize the array to some meaningful values.
Syntax:
int arr[5] = {2, 4, 8, 12, 16};
Advantages of Array
The following are the main advantages of an array:
1. Random and fast access of elements using the array index.
2. Use of fewer lines of code as it creates a single array of multiple elements.
3. Traversal through the array becomes easy using a single loop.
4. Sorting becomes easy as it can be accomplished by writing fewer lines of code.
Disadvantages of Array
1. Arrays are not dynamic they only allow a fixed number of elements to be entered which is decided
at the time of declaration.
2. Insertion and deletion of elements can be costly since the elements are needed to be rearranged
after insertion and deletion.
Example
int arr[5]; // Declares an array of size 5
Initialization
int arr[5] = {1, 2, 3, 4, 5};
Accessing Elements
printf("%d", arr[2]); // Accesses the third element, which is 3
2-DIMENSIONAL ARRAY IN C:
A 2D array organizes data in rows and columns, making it ideal for matrix representation.
Declaration
data_type array_name[rows][columns];
Example
int arr[3][4]; // Declares a 2D array with 3 rows and 4 columns
Initialization
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
In this article, we will explore the definition of arrays in C, their common uses, and practical
examples to help you understand how to implement them effectively in your programs. Whether
you're a beginner looking to grasp the basics or an experienced programmer refining your skills,
this guide will equip you with valuable insights into using arrays in real-world scenarios.
Array in C is a collection of variables stored in contiguous memory locations. It can be accessed using a
single name and an index. These entities or elements can be int, float, char, double, or user-defined data
types, like structures.
In C, an array is a collection of elements of the same data type stored in contiguous memory
locations. To declare an array, you must specify the data type, the array name, and the size
(number of elements the array can hold).
data_type array_name[array_size];
data_type: Specifies the type of elements the array will hold (e.g., int, float, char).
array_size: The number of elements the array can hold (must be a positive integer).
Key Points
If the size is omitted during the declaration, it must be determined from the initialization.
Become job-ready for Programmer/ Developer roles today with C Basics Online Tutorial Course for
Beginners!
C Array Initialization
Array initialization is the process of assigning values to the elements of an array at the time of
declaration. You can initialize arrays either partially or fully using curly braces {}.
Examples
1. Full Initialization
2. Partial Initialization
int numbers[5] = {1, 2}; // Initializes first two elements; remaining are set to 0
When fewer values are provided, the remaining elements are initialized to zero (for numeric
types).
3. Implicit Size Determination
Arrays are essential in C programming because they allow us to store and manage multiple
elements of the same data type using a single variable. Instead of declaring separate variables for
each element, arrays provide a structured way to handle data collection, making programs more
efficient and easier to read. They are beneficial for tasks like managing lists, performing
mathematical operations on datasets, and handling data sequences in loops.
Array elements can be accessed using their index values. The index starts at 0, so the first
element is at position 0, the second at position 1, and so on.
Example
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Declare and initialize an array
// Accessing elements
printf("First element: %d\n", arr[0]);
printf("Third element: %d\n", arr[2]);
return 0;
}
Output
First element: 10
Third element: 30
#include <stdio.h>
int main() {
int arr[3];
// Input elements
printf("Enter 3 integers: ");
for (int i = 0; i < 3; i++) {
scanf("%d", &arr[i]);
}
// Output elements
printf("You entered: ");
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output
Enter 3 integers: 5 10 15
You entered: 5 10 15
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
// Print elements
for (int i = 0; i < 3; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}
return 0;
}
Output
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Advantages of Arrays in C
1. Efficient Memory Usage: Arrays provide a way to store data sequentially, reducing memory wastage.
2. Easy Data Access: Elements can be accessed directly using their indices.
3. Compact Code: Using loops, operations can be performed on multiple elements, reducing repetitive
code.
4. Static Storage: Data is allocated contiguously, enabling faster access and manipulation.
5. Ideal for Fixed-Size Data: Arrays are perfect when the number of elements is known in advance.
Disadvantages of Arrays in C
1. Fixed Size: The size of an array must be defined at the time of declaration, limiting flexibility.
2. Homogeneous Data: Arrays can only store elements of the same data type.
3. No Built-in Bounds Checking: Accessing indices outside the declared range can lead to undefined
behavior.
4. Insertion and Deletion: These operations are time-consuming as they require shifting elements.
5. Memory Allocation: If improperly handled, large arrays can lead to excessive memory usage.
Types of Array in C
Arrays are a fundamental data structure in C programming that stores multiple elements of the
same type in a contiguous memory block. Based on their dimensions, arrays in C can be
categorized into One-dimensional and Multidimensional arrays. Below, we’ll explore these types
in detail.
A one-dimensional array is the simplest form of an array, storing elements in a single linear
sequence. It can be visualized as a row of elements.
Declaration
data_type array_name[size];
Example
Boost your career with our Full Stack Developer - MERN Stack Master's program! Gain in-depth
expertise in development and testing with the latest technologies. Enroll today and become a skilled
MERN Stack Developer!
2. MULTIDIMENSIONAL ARRAY
Multidimensional arrays are arrays within arrays, allowing for data storage in a tabular or matrix
form. They extend the concept of one-dimensional arrays by adding more dimensions.
2-DIMENSIONAL ARRAY IN C
A 2D array organizes data in rows and columns, making it ideal for matrix representation.
Declaration
data_type array_name[rows][columns];
Example
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Points to Remember While Initializing a 2D Array:
Examples of 2D Array in C
return 0;
}
3-DIMENSIONAL ARRAY IN C:
A 3D array extends the concept of 2D arrays by adding another dimension. It stores elements
in a cube-like structure.
Declaration
data_type array_name[size1][size2][size3];
Example
int arr[2][3][4];
STRING HANDLING IN C:
In C programming, strings are handled as arrays of characters, terminated by a null
character \0. This null terminator is crucial as it signifies the end of the string, allowing functions to
correctly process its length and content.
C provides a rich set of functions in the <string.h> header for manipulating strings:
strlen():
Returns the length of the string (excluding the null terminator).
strcpy():
Copies the string src to dest. Be cautious of buffer overflows if dest is not large enough.
strncpy():
Copies at most n characters from src to dest. It does not guarantee null termination if src is longer
than n.
strcat():
Concatenates (appends) the string src to the end of dest.
strncat():
Concatenates at most n characters from src to dest.
strcmp():
Compares two strings lexicographically. Returns 0 if equal, a negative value if str1 is less than str2,
and a positive value if str1 is greater than str2.
strncmp():
Compares at most n characters of two strings.
strstr():
Finds the first occurrence of the substring needle within haystack. Returns a pointer to the beginning
of the found substring or NULL if not found.
strchr():
Finds the first occurrence of the character c within str. Returns a pointer to the character or NULL if
not found.
UNIT 4:
FUNCTIONS IN C:
Functions in C are self-contained blocks of code designed to perform a specific task. They are
fundamental for structuring C programs, promoting modularity, reusability, and readability.
COMPONENTS OF A FUNCTION:
Function Declaration (Prototype): This specifies the function's return type, name, and parameters. It
informs the compiler about the function's existence and signature before its actual definition.
return_type function_name(parameter_list);
Function Definition: This contains the actual code (function body) that the function executes when
called.
return_type function_name(parameter_list) {
// Function body: statements to be executed
// ...
return value; // if return_type is not void
}
Function Call: This is the act of invoking a function to execute its code.
function_name(arguments);
Return Value:
A function can return a value to the calling code using the return statement. The return_type in the
declaration and definition specifies the data type of the value returned. If a function does not return any
value, its return_type is void.
Parameters and Arguments:
Functions can accept input values through parameters. When calling a function, the values passed to these
parameters are called arguments.
FUNCTION PROTOTYPE:
Syntax of a function prototype:
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, ...);
Example:
#include <stdio.h>
int add(int a, int b);
int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2);
printf("Sum: %d\n", sum);
return 0;
}
int add(int a, int b) {
return a + b;
}
PARAMETER PASSING TECHNIQUES IN C:
When you call a function in C, you often send it some values — these are called parameters.
There are two main ways to pass them:
1.Pass by Value
You send a copy of the variable.
Changes made inside the function don’t affect the original variable.
#include <stdio.h>
void changeValue(int x) {
x = 100;
}
int main() {
int a = 10;
changeValue(a);
printf("Value of a: %d\n", a); // Output: 10
return 0;
}
🔹 Example:
#include <stdio.h>
int main() {
int a = 10;
changeValue(&a);
printf("Value of a: %d\n", a); // Output: 100
return 0;
}
Here, a becomes 100 because we passed its address and modified the actual value.
STORAGE CLASS :
In C, there are four main storage classes: auto, register, static, and extern. Each controls a
variable’s scope, lifetime, and visibility.
🔹 Example:
void func() {
auto int x = 5; // same as int x = 5;
}
🔹 Example:
c
void func() {
register int counter = 0;
}
#include <stdio.h>
int main() {
int n, i;
int first = 0, second = 1, next;
return 0;
}
Sample Output:
Enter the number of terms: 6
Fibonacci Series: 0 1 1 2 3 5
Types of Recursion
Direct Recursion: Function calls itself directly.
Indirect Recursion: Function A calls B, and B calls A.
Tail Recursion: Recursive call is the last statement in the function.
UNIT 5:
POINTERS:
Pointers in C are variables that store the memory address of another variable. They
allow direct access and manipulation of memory, making them powerful for tasks like
dynamic memory allocation and efficient data handling.
A pointer is a variable that holds the address of another variable. Instead of storing a value like
10, it stores something like 0x7ffe1234 — the location in memory where that value is kept.
Basic Syntax
int a = 10;
int *p; // Declare a pointer to int
p = &a;
Types of Pointers
Null Pointer: Points to nothing (int *p = NULL;)
Void Pointer: Generic pointer (void *p;)
Dangling Pointer: Points to freed memory
Wild Pointer: Uninitialized pointer
Function Pointer: Points to a function
STRUCTURES IN C:
Structures in C are user-defined data types that let you group different types of variables under one
name. They're useful for organizing complex data like student records, employee details, etc.
A structure (or struct) is a way to combine variables of different types into a single unit. Each
variable inside a structure is called a member.
🔹 Syntax:
c
struct Student {
int id;
char name[50];
float marks;
};
🔹 Key Points:
Advanced Concepts
Array of Structures: Store multiple records.
Nested Structures: Structure inside another structure.
Pointer to Structure: Use -> operator to access members.
UNION IN C:
a union is a special data type that allows you to store different types of data in the same memory
location. Unlike a struct, where each member has its own memory, all members of a union share the same
memory space.
Syntax of Union
c
union Data {
int i;
float f;
char str[20];
};
ENUMURATION IN C:
Enumeration (enum) in C is a user-defined data type that assigns names to a set of integer
constants, making code more readable and easier to maintain.
What Is an Enum?
An enum lets you define a group of related constants with meaningful names. By default, the
first name gets the value 0, the next 1, and so on — but you can also assign custom values.
Syntax
enum Weekday { MON, TUE, WED, THU, FRI, SAT, SUN };
EXAMPLE:
1.MON = 0, TUE = 1, ..., SUN = 6
Now:
Notes
Enum variables can hold only one value at a time.
Enums are stored as integers.
You can use typedef to simplify enum usage:
POINTER VS ARRAY:
Example: Array
int arr[3] = {10, 20, 30};
printf("%d\n", arr[1]); // Output: 20
printf("%p\n", arr); // Address of arr[0]
Example: Pointer
int a = 10;
int *p = &a;
printf("%d\n", *p); // Output: 10
printf("%p\n", p); // Address
Pointer and Array Relationship
You can use pointers to access array elements: