C Programming Concepts: File Handling, Data Structures, and Control Flow
File Opening Modes in C and File Copying
In C, you can open files in various modes, each serving a specific purpose:
File Opening Modes
- “r”: Opens a file for reading. The file must exist.
- “w”: Opens a file for writing. If the file exists, it’s truncated; if it doesn’t exist, a new file is created.
- “a”: Opens a file for appending. Writing operations append data to the end of the file.
- “r+”: Opens a file for both reading and writing. The file must exist.
- “w+”: Opens a file for reading and writing. If the file exists, it’s truncated; if it doesn’t exist, a new file is created.
- “a+”: Opens a file for reading and appending. Writing operations append data to the end of the file. It creates the file if it doesn’t exist.
C Program to Create an Exact Copy of a File
#include <stdio.h>
int main() {
FILE *original_file, *copy_file;
char ch;
// Open the original file for reading
original_file = fopen("original.txt", "r");
if (original_file == NULL) {
printf("Unable to open the original file.\n");
return 1;
}
// Open the copy file for writing
copy_file = fopen("copy.txt", "w");
if (copy_file == NULL) {
printf("Unable to create the copy file.\n");
return 1;
}
// Copy content from original to copy
while ((ch = fgetc(original_file)) != EOF) {
fputc(ch, copy_file);
}
// Close both files
fclose(original_file);
fclose(copy_file);
printf("File copied successfully.\n");
return 0;
}
Unions and Time Addition Using Structures
Understanding Unions
In programming, a union is a data structure that allows storing different data types in the same memory location. It’s similar to a struct but with the key difference that only one member of the union can be accessed at a time.
C Program to Add Time Values Using Structures
#include <stdio.h>
struct Time {
int minutes;
int seconds;
};
void addTime(struct Time t1, struct Time t2, struct Time *result) {
result->seconds = t1.seconds + t2.seconds;
result->minutes = t1.minutes + t2.minutes + result->seconds / 60;
result->seconds %= 60;
}
int main() {
struct Time time1, time2, result;
// Input time values
printf("Enter time 1 (mm:ss): ");
scanf("%d:%d", &time1.minutes, &time1.seconds);
printf("Enter time 2 (mm:ss): ");
scanf("%d:%d", &time2.minutes, &time2.seconds);
// Add the times
addTime(time1, time2, &result);
// Display the result
printf("Total time: %02d:%02d\n", result.minutes, result.seconds);
return 0;
}
Break and Continue Statements
In programming, a ‘break’ statement is used to exit a loop prematurely, while a ‘continue’ statement is used to skip the current iteration of a loop and proceed to the next iteration.
Python Example of Break and Continue
# Example of break statement
for i in range(1, 6):
if i == 3:
break
print(i)
# Output: 1
# 2
# Example of continue statement
for i in range(1, 6):
if i == 3:
continue
print(i)
# Output: 1
# 2
# 4
# 5
In the first example, when ‘i’ equals 3, the ‘break’ statement is encountered, causing the loop to terminate prematurely. In the second example, when ‘i’ equals 3, the ‘continue’ statement is encountered, skipping the rest of the loop’s body for that iteration and proceeding to the next iteration.
Dynamic Memory Allocation (DMA) and Odd Number Display
Understanding DMA
DMA stands for Dynamic Memory Allocation, which is a method of allocating memory during the runtime of a program. It allows programs to allocate memory dynamically as needed. In C programming, DMA is often used with functions like ‘malloc()’ and ‘calloc()’ to allocate memory dynamically.
C Program to Read N Numbers Using DMA and Display Odd Numbers
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int N;
// Prompt user for the number of elements
printf("Enter the number of elements: ");
scanf("%d", &N);
// Allocate memory dynamically for N numbers
numbers = (int *)malloc(N * sizeof(int));
// Check if memory allocation was successful
if (numbers == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Prompt user to enter the numbers
printf("Enter %d numbers:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &numbers[i]);
}
// Display odd numbers
printf("Odd numbers:\n");
for (int i = 0; i < N; i++) {
if (numbers[i] % 2 != 0) {
printf("%d ", numbers[i]);
}
}
printf("\n");
// Free the allocated memory
free(numbers);
return 0;
}
Recursion and Fibonacci Series
Understanding Recursion
Recursion is a programming technique where a function calls itself in order to solve smaller instances of the same problem.
Python Program to Display the First 10 Numbers in the Fibonacci Series Using Recursion
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
# Display the first 10 numbers in the Fibonacci series
for i in range(10):
print(fibonacci(i))
This program defines a function fibonacci that recursively calculates the Fibonacci number for a given index ‘n’. Then, it iterates through the first 10 indices and prints the corresponding Fibonacci numbers.
Pointers and Array-Pointer Similarity
Understanding Pointers
A pointer is a variable that stores the memory address of another variable. It allows indirect access to the value stored at that memory address.
C Example Illustrating Array-Pointer Similarity
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer initialized with the address of the first element of the array
// Accessing array elements using array notation
printf("Array elements using array notation:\n");
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Accessing array elements using pointer notation
printf("Array elements using pointer notation:\n");
for (int i = 0; i < 3; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
return 0;
}
In this example, ‘ptr’ is a pointer to an integer. It’s initialized with the address of the first element of the array ‘arr’. The loop demonstrates that we can access array elements either using array notation (‘arr[i]’) or pointer notation (‘*(ptr + i)’), showing the similarity between arrays and pointers in C.
Odd Loops
An “odd loop” isn’t a standard programming term. It could refer to a loop that operates on odd numbers or a loop with an odd condition. Here’s a Python program that illustrates both interpretations:
Python Example of Odd Loops
# Looping through odd numbers
print("Looping through odd numbers:")
for i in range(1, 11, 2):
print(i)
# Loop with odd condition
print("\nLoop with odd condition:")
counter = 0
while counter < 10:
if counter % 2 != 0:
print(counter)
counter += 1
This program first prints odd numbers from 1 to 10 using a ‘for’ loop, then it prints odd numbers using a ‘while’ loop with an odd condition.
