Professional Documents
Culture Documents
• Arrays are collections of elements of the same data type stored in contiguous memory
locations.
code
#include <stdio.h> int main() { int nums[5] = {1, 2, 3, 4, 5}; // Declaration and initialization of an array
int i; printf("Elements of the array: "); for (i = 0; i < 5; i++) { printf("%d ", nums[i]); // Accessing array
elements using indices } printf("\n"); return 0; }
Pointers in C:
• They are used to manipulate memory and facilitate dynamic memory allocation.
code
#include <stdio.h> int main() { int num = 10; int *ptr; // Pointer declaration ptr = # // Assigning
address of num to ptr printf("Value of num: %d\n", num); printf("Address of num: %p\n", &num);
printf("Value of num using pointer: %d\n", *ptr); // Dereferencing pointer return 0; }
• malloc(), calloc(), and realloc() functions are used to allocate memory dynamically.
code
#include <stdio.h> #include <stdlib.h> int main() { int *nums; int size = 5; nums = (int *)malloc(size *
sizeof(int)); // Allocating memory if (nums == NULL) { printf("Memory allocation failed\n"); return 1; }
printf("Enter %d numbers: ", size); for (int i = 0; i < size; i++) { scanf("%d", &nums[i]); // Reading input
into dynamically allocated array } printf("Numbers entered: "); for (int i = 0; i < size; i++) { printf("%d ",
nums[i]); // Accessing elements of dynamically allocated array } printf("\n"); free(nums); //
Deallocating memory return 0; }
File Handling in C:
• fopen(), fclose(), fread(), fwrite(), fprintf(), fscanf(), etc., are used for file handling in C.
code
#include <stdio.h> int main() { FILE *fp; char str[50]; fp = fopen("example.txt", "w"); // Opening file in
write mode if (fp == NULL) { printf("Error opening file\n"); return 1; } fprintf(fp, "Hello, World!\n"); //
Writing to file fclose(fp); // Closing file fp = fopen("example.txt", "r"); // Opening file in read mode if
(fp == NULL) { printf("Error opening file\n"); return 1; } fscanf(fp, "%[^\n]", str); // Reading from file
printf("Data from file: %s\n", str); fclose(fp); // Closing file return 0; }