An array is a collection of elements of the same data type stored in contiguous memory locations. It allows efficient access and manipulation of data using an index.
Syntax: data_type array_name[size]; Example: int numbers[5] = {1, 2, 3, 4, 5}; Here, 'numbers' is a 1D array of integers with 5 elements.
Array elements can be accessed using their index, which starts from 0. To display elements, a loop is commonly used.
Example: int numbers[5] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } Output: 1 2 3 4 5
Sorting an array involves arranging its elements in a specific order (ascending or descending). Common algorithms include bubble sort, selection sort, and quicksort.
Example: Bubble Sort: int numbers[5] = {5, 2, 9, 1, 3}; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5 - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Sorted Array: 1 2 3 5 9
Arrays can be passed to functions to perform operations. When passed, only the reference to the first element is given, not the entire array.
Example: void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } } int main() { int numbers[5] = {10, 20, 30, 40, 50}; printArray(numbers, 5); return 0; } Output: 10 20 30 40 50
A two-dimensional array is an array of arrays, often visualized as a matrix. It requires two indices for accessing elements.
Declaration: data_type array_name[rows][columns]; Example: int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; Access: matrix[0][1] = 2
Arrays in C are stored in memory in either row-major or column-major order:
Example: Array: int matrix[2][2] = { {1, 2}, {3, 4} }; Row-Major: Memory Order: 1, 2, 3, 4 Column-Major: Memory Order: 1, 3, 2, 4
A multidimensional array is an array with more than two dimensions. It is declared and accessed similarly to 2D arrays but requires additional indices.
Example: Declaration: int cube[2][2][2]; Initialization: int cube[2][2][2] = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} }; Access: cube[1][0][1] = 6
A pointer is a variable that stores the memory address of another variable. It is
declared using the *
symbol.
Syntax: data_type *pointer_name; Example: int *ptr; float *fptr;
To initialize a pointer, assign it the address of a variable using the &
operator.
Example: int num = 10; int *ptr = # printf("Address of num: %p\n", ptr); printf("Value of num: %d\n", *ptr); Output: Address of num: 0x7ffeeaa3b8c4 (example) Value of num: 10
Indirection operator (*): Dereferences a pointer to access the value stored at the memory address. Address-of operator (&): Retrieves the memory address of a variable.
Example: int x = 5; int *p = &x; printf("Value of x: %d\n", *p); printf("Address of x: %p\n", &x); Output: Value of x: 5 Address of x: 0x7ffeeaa3b8c4 (example)
Pointers support arithmetic operations such as increment, decrement, and addition/subtraction of integers.
Example: int arr[3] = {10, 20, 30}; int *ptr = arr; printf("Value at ptr: %d\n", *ptr); ptr++; printf("Value at ptr: %d\n", *ptr); Output: Value at ptr: 10 Value at ptr: 20
Dynamic memory allocation allows memory to be allocated at runtime using functions like
malloc
, calloc
, realloc
, and freed using free
.
Example: int *ptr = (int *)malloc(5 * sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed.\n"); } else { for (int i = 0; i < 5; i++) { ptr[i] = i + 1; } for (int i = 0; i < 5; i++) { printf("%d ", ptr[i]); } } free(ptr); Output: 1 2 3 4 5
Arrays and pointers are closely related in C. The name of an array acts as a pointer to the first element of the array.
Example: int arr[3] = {10, 20, 30}; int *ptr = arr; printf("First element: %d\n", *ptr); printf("Second element: %d\n", *(ptr + 1)); Output: First element: 10 Second element: 20
Pointers can be used to pass variables by reference to functions, enabling functions to modify the original variables.
Example: void updateValue(int *p) { *p = 20; } int main() { int x = 10; updateValue(&x); printf("Updated value of x: %d\n", x); return 0; } Output: Updated value of x: 20
A string in C is an array of characters terminated by a null character
'\0'
. Strings can be declared and initialized like arrays.
Declaration: char str[size]; Initialization: char str1[] = "Hello"; char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; Access: printf("%c", str1[0]); // Output: H
C provides several standard library functions for performing operations on strings. These functions are
defined in string.h
.
strlen()
Returns the length of a string (excluding the null character).
Example: char str[] = "Hello"; printf("Length: %lu", strlen(str)); Output: Length: 5
strcpy()
Copies one string into another.
Example: char str1[] = "Hello"; char str2[10]; strcpy(str2, str1); printf("%s", str2); Output: Hello
strcat()
Concatenates (joins) two strings.
Example: char str1[20] = "Hello"; char str2[] = " World"; strcat(str1, str2); printf("%s", str1); Output: Hello World
strcmp()
Compares two strings lexicographically. Returns 0 if equal, a negative value if the first string is less, and a positive value if the first string is greater.
Example: char str1[] = "Hello"; char str2[] = "World"; int result = strcmp(str1, str2); printf("%d", result); Output: -15 (depends on the ASCII values of characters)
int stringLength(char str[]) { int length = 0; while (str[length] != '\0') { length++; } return length; } Example: char str[] = "Hello"; printf("Length: %d", stringLength(str)); Output: Length: 5
void stringCopy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; } Example: char src[] = "Hello"; char dest[10]; stringCopy(dest, src); printf("%s", dest); Output: Hello
void stringConcat(char str1[], char str2[]) { int i = 0, j = 0; while (str1[i] != '\0') i++; while (str2[j] != '\0') { str1[i++] = str2[j++]; } str1[i] = '\0'; } Example: char str1[20] = "Hello"; char str2[] = " World"; stringConcat(str1, str2); printf("%s", str1); Output: Hello World
int stringCompare(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0' && str2[i] != '\0') { if (str1[i] != str2[i]) { return str1[i] - str2[i]; } i++; } return str1[i] - str2[i]; } Example: char str1[] = "Hello"; char str2[] = "World"; int result = stringCompare(str1, str2); printf("%d", result); Output: -15
A structure in C is a user-defined data type that groups variables of different data
types into a single unit. It is declared using the struct
keyword.
Syntax: struct StructureName { data_type member1; data_type member2; ... }; Example: struct Student { int rollNo; char name[50]; float marks; };
Structure variables can be initialized during or after declaration.
Example: struct Student { int rollNo; char name[50]; float marks; }; // Initialization during declaration struct Student s1 = {1, "Alice", 95.5}; // Initialization after declaration struct Student s2; s2.rollNo = 2; strcpy(s2.name, "Bob"); s2.marks = 89.0;
Fields of a structure are accessed using the .
operator.
Example: struct Student { int rollNo; char name[50]; float marks; }; struct Student s1 = {1, "Alice", 95.5}; printf("Roll No: %d\n", s1.rollNo); printf("Name: %s\n", s1.name); printf("Marks: %.2f\n", s1.marks); Output: Roll No: 1 Name: Alice Marks: 95.50
Structures can contain other structures as members. This is called nested structures.
Example: struct Address { char city[50]; char state[50]; int zip; }; struct Student { int rollNo; char name[50]; struct Address addr; }; struct Student s = {1, "Alice", {"New York", "NY", 10001}}; printf("City: %s\n", s.addr.city); printf("State: %s\n", s.addr.state); printf("ZIP: %d\n", s.addr.zip); Output: City: New York State: NY ZIP: 10001
A union is similar to a structure, but its members share the same memory space. It is
declared using the union
keyword.
Syntax: union UnionName { data_type member1; data_type member2; ... }; Example: union Data { int i; float f; char str[20]; }; union Data d; d.i = 10; // Only one member can hold a value at a time
The key differences between structures and unions are:
Example: struct ExampleStruct { int a; float b; }; union ExampleUnion { int a; float b; }; struct ExampleStruct s = {5, 3.14}; union ExampleUnion u; u.a = 5; // Assigns value to a u.b = 3.14; // Overwrites value in a Memory Usage: Structure: Memory = sizeof(int) + sizeof(float) = 8 bytes (on 32-bit systems) Union: Memory = max(sizeof(int), sizeof(float)) = 4 bytes (on 32-bit systems)
The C Preprocessor is a tool that processes the source code before it is compiled.
Preprocessor directives begin with #
and are used for macro substitution, file inclusion,
and conditional compilation.
Example: #include#define PI 3.14 int main() { printf("Value of PI: %.2f\n", PI); return 0; } Output: Value of PI: 3.14
Macros are used to define constants or functions that are substituted in the code during preprocessing.
Example: #define SQUARE(x) ((x) * (x)) int main() { printf("Square of 4: %d\n", SQUARE(4)); return 0; } Output: Square of 4: 16
File inclusion allows including external files (header files or user-defined files) in a program using
#include
.
Syntax: #include// Standard library file #include "user_file.h" // User-defined file Example: #include #include "myheader.h" int main() { greet(); return 0; } // myheader.h void greet() { printf("Hello, World!"); } Output: Hello, World!
Conditional compilation allows compiling parts of code based on specified conditions using directives
like #if
, #else
, #elif
, and #endif
.
Example: #define DEBUG 1 int main() { #if DEBUG printf("Debug mode is ON.\n"); #else printf("Debug mode is OFF.\n"); #endif return 0; } Output: Debug mode is ON.
Bitwise operators operate on binary representations of integers. Common operators include:
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise NOTExample: int a = 5, b = 3; // Binary: a = 0101, b = 0011 printf("a & b: %d\n", a & b); // Output: 1 (0001) printf("a | b: %d\n", a | b); // Output: 7 (0111) printf("a ^ b: %d\n", a ^ b); // Output: 6 (0110) printf("~a: %d\n", ~a); // Output: -6 (2's complement)
Shift operators shift bits to the left or right:
<<
: Left shift>>
: Right shiftExample: int a = 5; // Binary: 0101 printf("a << 1: %d\n", a << 1); // Output: 10 (1010) printf("a >> 1: %d\n", a >> 1); // Output: 2 (0010)
Masks are used to manipulate specific bits in a number using bitwise operations.
Example: int num = 10; // Binary: 1010 int mask = 1; // Binary: 0001 int result = num & mask; printf("Result: %d\n", result); // Output: 0 (LSB is not set)
Bit fields allow struct members to occupy specific numbers of bits.
Example: struct { unsigned int a : 1; // 1 bit unsigned int b : 3; // 3 bits unsigned int c : 4; // 4 bits } bitField; bitField.a = 1; bitField.b = 7; bitField.c = 15; printf("a: %d, b: %d, c: %d\n", bitField.a, bitField.b, bitField.c); Output: a: 1, b: 7, c: 15
A file is a storage area in a computer where data is stored for long-term use. Files enable programs to read from and write to external storage.
Example: A text file stores characters and can be read using text-based editors. A binary file stores data in binary format and is not human-readable.
Files can be opened in various modes using the fopen()
function. Common modes include:
"r"
: Opens a file for reading."w"
: Opens a file for writing (overwrites if file exists)."a"
: Opens a file for appending (adds data at the end)."r+"
: Opens a file for reading and writing."w+"
: Opens a file for reading and writing (overwrites if file exists).Example: FILE *fp; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Error opening file."); } fclose(fp);
fopen()
and fclose()
The fopen()
function opens a file, and fclose()
closes an opened file.
Example: FILE *fp = fopen("data.txt", "w"); if (fp) { fclose(fp); }
feof()
Checks if the end of a file has been reached.
Example: FILE *fp = fopen("data.txt", "r"); char ch; while (!feof(fp)) { ch = fgetc(fp); printf("%c", ch); } fclose(fp);
fseek()
and rewind()
fseek()
moves the file pointer to a specific position. rewind()
resets the
pointer to the beginning of the file.
Example: FILE *fp = fopen("data.txt", "r"); fseek(fp, 10, SEEK_SET); // Move pointer to 10th byte rewind(fp); // Reset pointer to the start fclose(fp);
fgetc()
and fputc()
fgetc()
reads a character, and fputc()
writes a character to a file.
Example: FILE *fp = fopen("data.txt", "w"); fputc('A', fp); fclose(fp); fp = fopen("data.txt", "r"); char ch = fgetc(fp); printf("Read character: %c", ch); fclose(fp); Output: Read character: A
fscanf()
Reads formatted input from a file, similar to scanf()
.
Example: FILE *fp = fopen("data.txt", "r"); int num; fscanf(fp, "%d", &num); printf("Read number: %d", num); fclose(fp);
Command line arguments are passed to the main()
function in the form of parameters
argc
(argument count) and argv
(argument vector).
Example: #includeint main(int argc, char *argv[]) { if (argc == 2) { printf("File name: %s\n", argv[1]); } else { printf("Usage: ./program_name file_name\n"); } return 0; } Command: ./program_name data.txt Output: File name: data.txt