Professional Documents
Culture Documents
C PDF
C PDF
C PDF
Overview of C
Importance of C
● Foundation for Other Languages: Understanding C is essential for learning many other
programming languages, as C's syntax and concepts form the basis for languages like
C++, Java, and C#.
● System Programming: C remains the go-to language for developing operating systems,
device drivers, and other system-level software due to its direct hardware interaction
capabilities.
● Efficiency: C programs can be highly optimized for performance, making them ideal for
applications where speed is critical, such as embedded systems and graphics
programming.
Advantages of C Programming
● Speed and Performance: C code often executes faster than code written in higher-level
languages due to its compiled nature and direct memory access.
● Portable: C code can be easily ported (adapted) to different platforms with minimal changes
because it's standardized (ANSI C) and less reliant on machine-specific features.
● Memory Management: C provides fine-grained control over memory allocation and
deallocation, allowing for efficient memory usage in resource-constrained environments.
● Large Community and Resources: C has a vast community of developers and a wealth of
learning materials, libraries, and tools available.
Getting Started with C Programming
Add Headings (Format > Paragraph styles) and they will appear in your table of contents.
1. Choose a C compiler: Popular options include GCC (GNU Compiler Collection) and
Clang.
2. Set up a development environment: You can use a simple text editor or an Integrated
Development Environment (IDE) that provides features like code completion, debugging,
and project management.
3. Learn the basics: Start with fundamental concepts like variables, data types, operators,
control flow statements (if, else, for, while), and functions.
4. Practice and experiment: Write small programs to solidify your understanding and
explore different functionalities.
5. Explore resources: Refer to online tutorials, books, and C programming communities for
further guidance and in-depth learning.
Structure of C
The structure of a C program typically consists of six main sections:
// Documentation (Optional)
// This program calculates the area of a rectangle
Character Set
In C, the character set refers to the collection of all valid characters that can be used to create
programs. These characters include:
● Alphanumeric characters: Lowercase letters (a-z), uppercase letters (A-Z), and digits
(0-9). These are used to form identifiers, keywords, and constants.
● Special characters: Symbols like +, -, *, /, %, =, !, @, #, $, &, ^, *, (, ),
[, ], {, }, ;, :, ', ", ~, \, ?, |, and whitespace characters (space, tab,
newline). These have specific meanings in C.
● Control characters: Non-printable characters like carriage return, backspace, and form
feed, often used for formatting or controlling program behavior (typically not used directly in
code).
C Tokens
Tokens are the basic building blocks that the C compiler recognizes to construct programs.
They fall into several categories:
1. Keywords:
○ Reserved words with predefined meanings in C. You cannot use them as variable or
function names.
○ Examples: int, float, char, if, else, for, while, do, switch, case, return, void, static, auto,
register, extern, sizeof, typedef, enum, struct, union, volatile (32 keywords in total).
2. Identifiers:
○ User-defined names given to variables, functions, constants, structures, and unions.
○ Rules:
■ Must start with a letter (a-z, A-Z) or underscore (_).
■ Subsequent characters can be letters, digits, or underscores.
■ Cannot be the same as a keyword.
○ Examples: age, calculateArea, PI, student, myStructure.
3. Constants:
○ Fixed values that cannot be changed during program execution.
○ Types:
■ Integer constants: Whole numbers, positive, negative, or zero (e.g., 10, -25, 0).
■ Floating-point constants: Numbers with decimal points (e.g., 3.14-1.23e-5).
■ Character constants: Enclosed in single quotes (e.g., 'a', 'Z', '\n').
■ String literals: Sequences of characters enclosed in double quotes (e.g., "Hello,
world!", "This is a string").
4. Operators:
○ Symbols that perform operations on data (e.g., +, -, *, /, %, =, ++, --, ==,
!=, <, >, <=, >=, &&, ||, !).
5. Punctuators:
○ Special characters that separate tokens or have specific meanings (e.g., (, ), {, },
[, ], ?, :, ;, ,, ., ->, *).
Understanding Examples:
Variables
● In C programming, variables are named memory locations that store data during program
execution. They act as containers for values that your code can manipulate.
● To use a variable effectively, you need to follow these steps:
○ Declaration: This step informs the compiler about the name of the variable, its data type
(the kind of data it can hold), and optionally, its initial value. Declaration allocates the
necessary memory space for the variable.
○ Initialization (optional): During declaration, you can assign a starting value to the
variable using the assignment operator (=). This is helpful for setting initial conditions or
ensuring the variable is in a known state when the program starts.
Syntax:
Examples:
int age = 25; // Integer variable named 'age' with initial value 25
float pi = 3.14159; // Floating-point variable named 'pi' with initial
value for pi
char initial = 'A'; // Character variable named 'initial' with initial
value 'A'
Data Types
● Data types are essential in C because they define the type of data a variable can hold and
the operations that can be performed on it. They determine the size of memory allocated to
the variable, the range of values it can represent, and the set of valid operations (like
addition, subtraction, etc.) that can be applied to it.
● C provides several fundamental data types, each with its own characteristics:
1. Integer Types:
○ Represent whole numbers, positive, negative, or zero.
○ Types:
■ int: The most common integer type, its size varies depending on the system
architecture (typically 4 bytes on modern systems). Use this for general-purpose
integer calculations.
■ short int: Smaller integer type, often 2 bytes. Useful for conserving memory when you
know the values will be within a limited range.
■ long int: Larger integer type, often 4 or 8 bytes. Suitable for storing larger integer
values.
■ unsigned int: Stores only non-negative integers, often used in conjunction with bitwise
operations.
2. Floating-Point Types:
○ Represent numbers with decimal points for more precise calculations.
○ Types:
■ float: Single-precision floating-point type, typically 4 bytes. Provides a balance
between precision and memory usage.
■ double: Double-precision floating-point type, usually 8 bytes. Offers greater precision
but requires more memory.
3. Character Type:
○ Stores a single character, usually represented using ASCII or Unicode encoding.
○ Type:
■ char: Stores a single character, often 1 byte. Use this for storing individual characters
or short text strings.
4. Void Type:
○ A special type that doesn't hold any value.
○ Used to indicate that a function doesn't return a value (e.g., a function that only prints
output to the console).
Example:
int numPeople = 100; // Use int for whole numbers like people count
float interestRate = 0.05; // float for decimal values like interest rates
char initial = 'C'; // char for single characters
module -2
Operators
C operators are symbols that perform specific operations on variables, constants, and
expressions. They play a vital role in manipulating data and controlling program flow. Here's a
breakdown of the main C operators with examples:
1. Arithmetic Operators:
Examples:
int x = 10, y = 5;
int sum = x + y; // sum will be 15
int difference = x - y; // difference will be 5
int product = x * y; // product will be 50
int quotient = x / y; // quotient will be 2 (integer division truncates
decimals)
int remainder = x % y; // remainder will be 0
2. Assignment Operators:
Examples:
int count = 0;
count += 5; // Equivalent to count = count + 5; (count becomes 5)
float price = 10.5;
price *= 1.1; // Equivalent to price = price * 1.1; (price becomes 11.55)
3. Comparison Operators:
● Compare values and return true (1) or false (0) based on the condition.
● Operators: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or
equal to), >= (greater than or equal to).
Examples:
4. Logical Operators:
Examples:
5. Bitwise Operators:
● Perform operations on individual bits within a variable (often used for low-level
programming).
● Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift),
>> (right shift).
Example:
6. Increment/Decrement Operators:
● Increase or decrease the value of a variable by 1.
● Operators: ++ (increment), -- (decrement).
● Pre-increment (++x) increments the value and then uses it in the expression.
● Post-increment (x++) uses the current value and then increments it. Similar logic applies for
decrement.
Example:
int count = 0;
count++; // count becomes 1 (post-increment)
int value = count++; // value becomes 1 (uses current value of count, then
increments)
count = ++count
Special operators
1. Comma Operator (,):
● Evaluates multiple expressions from left to right, but returns the value of the rightmost
expression.
● Often used for side effects (e.g., incrementing a counter while assigning another value).
Example:
int x = 5, y = 10;
int result = (x++, y = 20); // result becomes 20 (y is assigned 20, then
the expression returns 20)
Example:
// In a source file:
int main() {
printf("Global variable value: %d\n", ::global_var); // Accessing
global_var using scope resolution
}
4. Conditional (Ternary) Operator (?:):
● Provides a concise way to write an if-else statement in a single expression.
● Syntax: condition ? expression_if_true : expression_if_false
Example:
● Explicitly converts a value from one data type to another. Useful for type coercion when
necessary.
Example:
double pi = 3.14159;
int int_pi = (int)pi; // int_pi will become 3 (truncating decimal part)
Remember:
● Special operators might have specific precedence rules compared to other operator types.
Consult a C operator precedence table when necessary.
● Use casting operators with caution, as incorrect casting can lead to unexpected behavior or
data loss.
Arithmetic Expressions
In C programming, arithmetic expressions are combinations of variables, constants,
operators, and function calls that evaluate to a numerical value. They form the building blocks
for performing calculations within your programs.
Expression Evaluation
Examples:
1. x + y * z
○ Evaluated as x + (y * z) because * has higher precedence than +.
2. (x + y) * z
○ Parentheses force x + y to be evaluated first, then the result is multiplied by z.
3. x * y ^ 2
○ Right-to-left associativity: y ^ 2 is evaluated first, then x is multiplied by the result.
Understanding expression evaluation is crucial for writing correct and predictable C programs.
Incorrect evaluation can lead to unexpected results, so it's essential to use parentheses or
choose expressions with clear precedence when necessary.
Additional Notes:
● C performs integer division by default. When dividing integers, the result is truncated
(decimal part discarded). To perform floating-point division, use floating-point operands
(e.g., 3.0 / 2).
● Be mindful of data type mixing and potential overflows/underflows when performing
calculations. Consider casting or using appropriate data types to avoid unexpected
behavior.
Operator Precedence
Operator precedence defines the order of operations within an expression. Operators with
higher precedence are evaluated first. If no parentheses are used, the compiler adheres to a
predefined hierarchy, ensuring consistent evaluation across your code. Here's a breakdown of
operator precedence in C (from highest to lowest):
Associativity
Associativity comes into play when multiple operators of the same precedence level appear in
an expression. It specifies the direction (left to right or right to left) in which these operators
are evaluated.
Increment/decr
ement after the x++ (post-increment, x is used
Postfix ++ -- operand Highest Right to left first, then incremented)
Plus/minus,
logical NOT,
+, -, !, ~, (type bitwise NOT,
Unary cast) type casting High Right to left -x (unary minus, x is negated)
Multiplication,
division,
Multiplicative *, /, % modulo Medium Left to right x * y / z ((x * y) / z)
Addition,
Additive +, - subtraction Low Left to right x + y - z ((x + y) - z)
Shift <<, >> Left/right shift Low Left to left x << 2 (x is shifted left by 2 bits)
Less than,
greater than,
less than or
equal to,
greater than or x < y (evaluates to 1 if true, 0 if
Relational <, >, <=, >= equal to Low Left to right false)
● Data Loss: Truncation during conversion from larger to smaller types can lead to
unexpected results. Be cautious when assigning values that might overflow the target data
type's range.
● Loss of Precision: When converting from floating-point to integer, precision is lost due to
truncation. Consider using appropriate data types if high precision is crucial.
● Explicit Casting: You can explicitly cast a value to a specific data type using the (type)
operator. This can be useful to force the conversion and potentially avoid unintended
consequences.
Example:
float pi = 3.14159;
int int_pi = (int)pi; // Explicitly cast pi (float) to int_pi (int),
potentially losing precision
Best Practices
● Choose Appropriate Data Types: Select data types that can accommodate the expected
range and precision of values to minimize the need for conversion.
● Be Mindful of Truncation: When mixing different data types, be aware of the possibility of
data loss and take steps to mitigate it if necessary.
● Use Explicit Casting Cautiously: While casting offers control, use it judiciously to avoid
unintended side effects.
predefined functions
In C programming, leveraging library functions is essential for building efficient and versatile
programs. These predefined functions, grouped in header files, provide a rich set of
functionalities to perform various tasks without reinventing the wheel. Here's a breakdown of
some commonly used library functions in C:
● Trigonometric Functions:
○ sin(x): Sine of angle x (in radians).
○ cos(x): Cosine of angle x (in radians).
○ tan(x): Tangent of angle x (in radians).
○ asin(x): Arcsine (inverse sine) of x.
○ acos(x): Arccosine (inverse cosine) of x.
○ atan(x): Arctangent (inverse tangent) of x.
● Exponential and Logarithmic Functions:
○ exp(x): Raises e (Euler's number) to the power of x.
○ log(x): Natural logarithm (base-e) of x.
○ log10(x): Base-10 logarithm of x.
● Power Function:
○ pow(x, y): Raises x to the power of y.
● Rounding and Absolute Value Functions:
○ ceil(x): Returns the smallest integer greater than or equal to x.
○ floor(x): Returns the largest integer less than or equal to x.
○ round(x): Rounds x to the nearest integer.
○ abs(x): Returns the absolute value (non-negative) of x.
● Square Root:
○ sqrt(x): Square root of x.
● Other Functions:
○ fmod(x, y): Remainder of floating-point division x / y.
○ remainder(x, y): Integer remainder of division x / y.
● Formatted Input/Output:
○ printf(format, ...): Prints formatted output to the console or a file. The format string
specifies placeholders for arguments (...) that are inserted during printing.
○ scanf(format, ...): Reads formatted input from the console or a file. The format string
specifies the expected format of input, and arguments (...) store the read values.
● Character I/O:
○ getchar(): Reads a single character from the console.
○ putchar(c): Writes a single character c to the console.
● File I/O:
○ fopen(filename, mode): Opens a file named filename in the specified mode (e.g., "r" for
reading, "w" for writing). Returns a file pointer if successful.
○ fclose(fp): Closes the file pointed to by fp.
○ fscanf(fp, format, ...): Reads formatted data from a file pointed to by fp.
○ fprintf(fp, format, ...): Writes formatted data to a file pointed to by fp.
● strlen(str): Returns the length (number of characters) of the string str (excluding the null
terminator).
● strcpy(dest, src): Copies the string src (including the null terminator) to dest. (Caution:
potential buffer overflow if dest is too small)
● strcat(dest, src): Appends the string src to the end of dest. (Caution: potential buffer
overflow)
● strcmp(str1, str2): Compares strings str1 and str2. Returns 0 if equal, negative if str1 is less
than str2, positive if str1 is greater than str2.
● strstr(haystack, needle): Searches for the first occurrence of the string needle within
haystack. Returns a pointer to the beginning of the substring if found, or NULL if not found.
● strncpy(dest, src, num): Copies at most num characters from src to dest, padding with null
characters if src is shorter.
Module 3
basic c programs
1. Hello World Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
1. Program to Add Two Integers
#include <stdio.h>
int main() {
int number1, number2, sum;
return 0;
}
1. Program to Check if a Number is Even or Odd
#include <stdio.h>
int main() {
int number;
if (number % 2 == 0)
printf("%d is even.\n", number);
else
printf("%d is odd.\n", number);
return 0;
}
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// ...
default:
// code to be executed if expression doesn't match any case
}
The break keyword exits the switch block. The default case is optional and can
appear anywhere in the switch block; it's executed only if none of the cases are
true.
nested if
A nested if is an if statement that appears inside another if or else block. It allows
you to test multiple conditions in a sequence or hierarchy. Here's an example:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num >= 0) {
if (num == 0) {
printf("The number is zero.\n");
} else {
printf("The number is positive.\n");
}
} else {
printf("The number is negative.\n");
}
return 0;
}
In this program, the outer if checks if the number is non-negative. If it's true, the
nested if then checks if the number is zero or positive. If the outer if condition is
false, it means the number is negative, and the corresponding message is printed.
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max;
return 0;
}
In this example, if a is greater than b, max will be assigned the value of a;
otherwise, max will be assigned the value of b.
#include <stdio.h>
int main() {
int num = 0;
start:
num++;
if (num < 5) {
printf("num is %d\n", num);
goto start; // Jumps back to the label "start"
}
printf("Finished counting.\n");
return 0;
}
In this example, the program will print numbers from 1 to 4. When num is less
than 5, it jumps back to the label start and continues incrementing and printing
num.
Remember that using goto can make your code hard to follow and is generally
discouraged in modern programming practices.
loops
For Loop:Used when the number of iterations is known beforehand.
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
Do-While Loop:Similar to the while loop, but the code block is executed at least
once.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);
Nested Loop:A loop inside another loop.
● One-dimensional array: It's like a list of elements. You can declare it as int
arr[5]; which creates an array arr that can hold 5 integers.
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
}; // A 2x3 array
● Multi-dimensional array: This extends the concept to more dimensions. A
three-dimensional array can be thought of as an array of arrays of arrays.
int arr[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
}; // A 2x3x2 array
You access elements using indices that start from 0. For example, arr[0][1]
accesses the second element in the first row of a two-dimensional array.
Remember that in C, the size of the arrays must be known at compile time if they
are declared statically. For dynamic sizes, you'd use pointers and memory
allocation functions like malloc().
string manipulation functions in c program
In C, a string is an array of characters terminated by a null character '\0'. Here's
how you can declare and initialize a string:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
return 0;
}
Remember to include the <string.h> header at the top of your program to use
these functions.
concept of modularization in c
Modularization in C programming is the process of dividing a program into
separate modules or functions that can be developed, tested, and maintained
independently. This approach enhances readability, reusability, and
manageability of code.
● Functions: Break down tasks into functions. Each function should perform
a specific task and can be called from other parts of the program.
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3);
printf("The sum is: %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
● Separate Files: For larger projects, you can split your code into multiple
files. For example, you can have main.c for the main program,
math_functions.c for math-related functions, and utility.c for utility
functions. You include them in your main file using header files (.h).
This way, each part of your program has a clear purpose, making it easier to
understand and maintain.
// Passing by reference
void increment(int *num) {
(*num)++;
}
● Calling Functions: You call a function by using its name followed by
parentheses containing any arguments.
int main() {
int number = 5;
printNumber(number); // Call by value
increment(&number); // Call by reference
printNumber(number); // Now prints 6
return 0;
}
● Categories of Functions:
○ Functions with no arguments and no return value.
○ Functions with arguments and no return value.
○ Functions with arguments and a return value.
○ Functions that return pointers or arrays.
Each category serves different purposes depending on what you need the
function to do. Remember to declare your functions before calling them or
provide a function prototype at the beginning of your file.
#include <stdio.h>
// Function prototypes
void greet();
int add(int a, int b);
int main() {
greet(); // Call greet function
int sum = add(10, 20); // Call add function
printf("Sum is: %d\n", sum);
return 0;
}
// Function definitions
void greet() {
printf("Hello, World!\n");
}
Recursion
is a technique where a function calls itself directly or indirectly. Here's a simple
example of a recursive function that calculates the factorial of a number:
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
For functions and arrays, you can pass an array to a function as an argument.
Here's how you can pass an array to a function that calculates the sum of its
elements:
// Usage
int main() {
int myArray[] = {1, 2, 3, 4, 5};
int result = sumArray(myArray, 5);
printf("Sum is: %d", result);
return 0;
}
Remember that when arrays are passed to functions, they are passed by
reference, meaning the function can modify the original array elements.
scope
In C, the scope of a variable determines where it can be accessed:
● Local variables have a block scope, accessible only within the function or
block where they're defined.
● Global variables have a file scope, accessible from any function within the
same file.
● Local variables have an automatic lifetime; they are created when the
function is called and destroyed when the function exits.
● Global variables and static local variables have a static lifetime; they are
created when the program starts and destroyed when the program ends.
In multi-file programs, global variables can be shared across files using the
extern keyword to declare them in other files.
void function1() {
int localVar = 20; // Local variable
}
// File2.c
extern int globalVar; // Accessing globalVar from File1.c
void function2() {
static int staticVar = 30; // Static local variable
}
struct Person {
char name[50];
int age;
float salary;
};
To use it, you would create a variable of the structure type and access
its members using the dot operator:
struct Person person1;
person1.age = 30;
strcpy(person1.name, "Alice");
person1.salary = 25000.50;
Union
A union is similar to a structure because it's also a user-defined data type that
allows you to store different data types in the same memory location. However,
you can only use one field at a time. Here's an example of a union:
union Data {
int i;
float f;
char str[20];
};
When you use a union, you can store data in one member at a time:
struct Person {
char name[50];
int age;
float salary;
};
strcpy(person1.name, "Bob");
person1.age = 25;
person1.salary = 30000.75;
Comparison:To compare two structure variables, you need to compare each
member individually because C does not support operator overloading:
struct Person {
char name[50];
int age;
float salary;
};
struct Student {
char name[50];
int marks[5]; // Array within a structure
};
struct Classroom {
struct Student students[30]; // Structures within an array
};
// Usage
struct Person person1 = {"Alice", 30, 25000.50};
printPerson(&person1);
Unions:As mentioned earlier, unions allow you to store different data types in
the same memory location. Here's an example of using unions with functions:
// Usage
union Data data;
data.i = 10;
printData(&data); // Only 'i' has a meaningful value here
Bit Fields:Bit fields allow you to use less than an integer's worth of memory to
store a value. They are defined inside structures. Here's an example:
struct Bits {
unsigned int a : 1;
unsigned int b : 3;
unsigned int c : 4;
};
pointers
Pointers in C
Pointers are a fundamental concept in C programming that enable you to work with memory
addresses. They act as variables that store memory locations rather than data values
themselves. This indirection through pointers offers several advantages:
● Memory Efficiency: Pointers can be used to pass references to variables to functions,
reducing the need for copying large data structures.
● Dynamic Memory Allocation: Pointers allow you to allocate memory at runtime using
functions like malloc and free, providing flexibility for managing memory as your
program's needs evolve.
● Array Manipulation: Pointers and arrays are closely linked in C. Array names
essentially behave like constant pointers to the first element's address, enabling efficient
array traversal and modification.
2. Address of a Variable: Using the address-of operator to store the memory address of
another variable.
int num = 25;
int *ptr = # // ptr now points to the memory address of num
Code Examples
1. Basic Pointer Example:
#include <stdio.h>
int main() {
int age = 30;
int *ptr = &age;
printf("Value of age: %d\n", age);
printf("Address of age: %p\n", &age);
printf("Value stored at the address pointed to by ptr: %d\n",
*ptr);
return 0;
}
This code outputs:
Value of age: 30
Address of age: 0x7ffe5... // Memory address will vary
Value stored at the address pointed to by ptr: 30
int main() {
int a = 10, b = 20;
return 0;
}
This code outputs:
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
By understanding pointers, you unlock a powerful mechanism for memory management and
manipulating data in C programs.
Pointer Expressions
Pointer expressions involve arithmetic operations on pointers. However, these operations
have specific rules:
● Addition/Subtraction: You can only add/subtract integers to/from pointers if they point
to elements of the same array. The amount added/subtracted depends on the data type
the pointer points to (e.g., adding 1 to an integer pointer moves it to the next integer
location).
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr1 = numbers;
int *ptr2 = ptr1 + 2; // ptr2 now points to the third element (index 2)
● Comparison: You can compare pointers to see if they point to the same memory
location (using == or !=) or compare their relative order within the same array (using <,
>, <=, or >=).
int num1 = 10;
int num2 = 20;
int *ptr1 = &num1;
int *ptr2 = &num2;
printf("\n");
By effectively using pointers, you can achieve efficient memory management and array
manipulation in C programs.
return 0;
}
int main() {
char str[] = "Geeks";
return 0;
}
Remember that pointers are a powerful tool in C, but they require careful handling to avoid
memory-related errors. Ensure proper initialization and memory management when using
pointers.
int main() {
int rows = 3, cols = 4;
int **matrix;
// Free memory
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}
This code dynamically allocates a 2D array using pointer to pointer. Remember to free
the allocated memory using free to prevent memory leaks.
Creating and Processing a Data File
1. Include header:
#include <stdio.h>
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
○ Use appropriate format specifiers (%d for integers, %f for floats, etc.) based
on your data types.
4. Close the file using fclose:
fclose(fp);
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
2. Read data from the file using fscanf or fgets (for strings):
int value;
fscanf(fp, "%d", &value); // Read an integer
char buffer[100];
fgets(buffer, 100, fp); // Read a line of text into a buffer
Command-Line Arguments
C programs can access command-line arguments passed during execution. You can
use these arguments to specify filenames or other parameters.
1. Include header:
#include <stdio.h>
2. In main function, access arguments using argc (argument count) and argv
(argument vector):
int main() {
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char buffer[100];
fgets(buffer, 100, fp);
printf("Read from file: %s", buffer);
fclose(fp);
return 0;
Remember to error handle file operations and close files to avoid resource leaks.