C Programming Basics: Structures, Pointers, Files, and Multi-dimensional Arrays
What is the Basic Structure of a C Program?
Explanation of Each Part
The basic structure of a C program consists of:
- Preprocessor Directives: These include
#includestatements to include header files, such as<stdio.h>for input and output operations. - Main Function: Every C program must have a
main()function, which serves as the entry point of the program. - Declaration Section: This section declares any global variables or functions that will be used throughout the program.
- Executable Statements: These are the statements that perform the actual tasks of the program. They are contained within the
main()function or other user-defined functions. - Return Statement: At the end of the
main()function, areturnstatement is used to indicate the end of the program and return a value to the operating system.
Difference Between Break and Continue Statements with Example
Here’s a brief explanation with an example:
Break Statement
It is used to terminate the loop immediately when a certain condition is met, and control passes to the statement following the loop.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
Continue Statement
It skips the rest of the code inside the loop for the current iteration and continues with the next iteration of the loop.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
C Program to Check if a String is a Palindrome
Here’s a simple C program to check if a given string is a palindrome or not:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
return false;
}
}
return true;
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}
What is a Pointer?
Illustrating the Use of Double Pointers with Examples
A pointer is a variable that stores the memory address of another variable. It essentially “points to” the location of a data item in memory.
A double pointer is a pointer that points to another pointer. It’s often used in scenarios where we need to modify a pointer variable itself, not just the value it points to. One common example is dynamic memory allocation, where we allocate memory for a pointer dynamically and want to update the pointer itself.
Here’s a simple example in C to illustrate the use of a double pointer:
#include <stdio.h>
#include <stdlib.h>
void allocateMemory(int **ptr) {
*ptr = (int *)malloc(sizeof(int)); // Allocating memory for an integer
**ptr = 10; // Assigning a value to the allocated memory
}
int main() {
int *ptr = NULL; // Declare a pointer to int and initialize it to NULL
// Passing the address of the pointer to the function
allocateMemory(&ptr);
printf("Value stored in dynamically allocated memory: %d\n", *ptr);
// Freeing the dynamically allocated memory
free(ptr);
return 0;
}
File Handling in Programming
Different File Operating Modes
In programming, files are used to store data persistently. There are several file operating modes, including:
- Read mode (‘r’): Allows reading from a file, but doesn’t permit writing. If the file doesn’t exist, it raises an error.
- Write mode (‘w’): Enables writing to a file. If the file exists, it truncates it to zero length. If it doesn’t exist, it creates a new file.
- Append mode (‘a’): Allows appending data to the end of the file. If the file doesn’t exist, it creates a new one.
- Read and Write mode (‘r+’): Allows both reading and writing to a file. The file is not truncated.
- Write and Read mode (‘w+’): Allows both reading and writing to a file. It truncates the file to zero length if it exists, or creates a new file if it doesn’t.
Each mode serves different purposes depending on whether you need to read, write, or both to a file, and whether you want to create a new file or modify an existing one.
What are Multi-dimensional Arrays?
Program Logic to Add and Display the Sum of Two m × n Matrices
A multi-dimensional array is an array that has more than one dimension, meaning it’s an array of arrays. In the context of matrices, a multi-dimensional array can represent a matrix with rows and columns.
Here’s the program logic in Python to add and display the sum of two m × n matrices:
def add_matrices(matrix1, matrix2):
if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):
print("Matrices must have the same dimensions.")
return None
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
def display_matrix(matrix):
for row in matrix:
print(row)
# Example matrices
matrix1 = [
[1, 2, 3],
[4, 5, 6]
]
matrix2 = [
[7, 8, 9],
[10, 11, 12]
]
sum_matrix = add_matrices(matrix1, matrix2)
if sum_matrix:
print("Sum of matrices:")
display_matrix(sum_matrix)
