Introduction to C Programming
1. Overview
C is a general-purpose, procedural programming language developed by Dennis Ritchie in the 1970s at Bell Labs. It is widely used for system programming, embedded systems, and application development due to its efficiency and control over system resources.
2. Basic Structure of a C Program
A C program typically consists of the following components:
- **Preprocessor Directives**: Instructions for the compiler to preprocess the code before compilation (e.g., `#include`, `#define`).
- **Main Function**: The entry point of every C program.
- **Statements and Expressions**: Instructions executed by the program.
- **Comments**: Notes within the code for readability (not executed).
**Example:**
```c
#include <stdio.h> // Preprocessor directive
// Main function — execution starts here
int main() {
printf(“Hello, World!\n”); // Print statement
return 0; // Return statement
}
```
3. Basic Syntax and Structure
- **Header Files**: Include standard libraries.
```c
#include <stdio.h>
```
- **Main Function**: Required in every C program.
```c
int main() {
// Code
return 0;
}
```
- **Statements**: End with a semicolon `;`.
- **Blocks**: Enclosed in curly braces `{ }`.
4. Data Types
C supports several data types:
- **Basic Data Types**:
— `int`: Integer type
— `float`: Floating-point type
— `double`: Double-precision floating-point type
— `char`: Character type
- **Derived Data Types**:
— Arrays
— Pointers
— Structures
— Unions
- **Void Type**: Represents the absence of a type.
**Example:**
```c
int age = 25; // Integer
float salary = 50000.50; // Float
double pi = 3.14159; // Double
char grade = ‘A’; // Character
```
5. Operators
Operators perform operations on variables and values.
- **Arithmetic Operators**: `+`, `-`, `*`, `/`, `%`
```c
int a = 10, b = 5;
int sum = a + b; // sum = 15
```
- **Relational Operators**: `==`, `!=`, `>`, `<`, `>=`, `<=`
```c
int a = 10, b = 20;
if (a < b) {
printf(“a is less than b”);
}
```
- **Logical Operators**: `&&`, `||`, `!`
```c
int a = 10, b = 20;
if (a < b && b < 30) {
printf(“Both conditions are true”);
}
```
- **Bitwise Operators**: `&`, `|`, `^`, `~`, `<<`, `>>`
```c
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a & b; // result = 1 (0001 in binary)
```
- **Assignment Operators**: `=`, `+=`, `-=`, `*=`, `/=`, `%=`
```c
int a = 10;
a += 5; // a = 15
```
6. Control Flow
Control flow statements direct the order of execution of statements.
- **If-Else Statements**:
```c
int num = 10;
if (num > 0) {
printf(“Positive number”);
} else {
printf(“Non-positive number”);
}
```
- **Switch-Case Statements**:
```c
int day = 3;
switch(day) {
case 1: printf(“Monday”); break;
case 2: printf(“Tuesday”); break;
case 3: printf(“Wednesday”); break;
default: printf(“Invalid day”);
}
```
- **Loops**:
— **For Loop**:
```c
for (int i = 0; i < 5; i++) {
printf(“%d “, i); // Output: 0 1 2 3 4
}
```
- **While Loop**:
```c
int i = 0;
while (i < 5) {
printf(“%d “, i); // Output: 0 1 2 3 4
i++;
}
```
- **Do-While Loop**:
```c
int i = 0;
do {
printf(“%d “, i); // Output: 0 1 2 3 4
i++;
} while (i < 5);
```
7. Functions
Functions are blocks of code that perform a specific task. They help in modularizing code and reusing it.
- **Function Declaration**:
```c
int add(int, int); // Function prototype
```
- **Function Definition**:
```c
int add(int a, int b) {
return a + b;
}
```
- **Function Call**:
```c
int result = add(10, 20); // Calling the function
```
8. Arrays
Arrays are collections of elements of the same type stored in contiguous memory locations.
- **Declaration and Initialization**:
```c
int arr[5] = {1, 2, 3, 4, 5}; // Array of integers
```
- **Accessing Elements**:
```c
int firstElement = arr[0]; // Accessing the first element
```
9. Pointers
Pointers store the address of another variable.
- **Declaration and Initialization**:
```c
int a = 10;
int *ptr = &a; // Pointer to integer
```
- **Dereferencing**:
```c
int value = *ptr; // value = 10
```
10. Structures
Structures allow grouping of different data types.
- **Declaration**:
```c
struct Person {
char name[50];
int age;
};
```
- **Usage**:
```c
struct Person person1;
strcpy(person1.name, “Alice”);
person1.age = 30;
```
11. File I/O
C provides functions to read from and write to files.
- **File Operations**:
```c
FILE *file = fopen(“example.txt”, “w”); // Open file for writing
fprintf(file, “Hello, File!”); // Write to file
fclose(file); // Close file
```
```c
FILE *file = fopen(“example.txt”, “r”); // Open file for reading
char buffer[100];
fgets(buffer, 100, file); // Read from file
fclose(file); // Close file
```
12. Dynamic Memory Allocation
Dynamic memory allocation allows for allocating memory at runtime.
- **Functions**:
— `malloc(size_t size)`: Allocates memory
— `calloc(size_t num, size_t size)`: Allocates and initializes memory
— `realloc(void *ptr, size_t size)`: Reallocates memory
— `free(void *ptr)`: Frees allocated memory
- **Example**:
```c
int *arr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
free(arr); // Free the allocated memory
```
13. Error Handling
C does not have built-in exception handling but uses return values and error codes.
- **Error Checking Example**:
```c
FILE *file = fopen(“example.txt”, “r”);
if (file == NULL) {
perror(“Error opening file”);
return 1;
}
```
14. Preprocessor Directives
Preprocessor directives are used to modify the code before compilation.
- **Include Files**:
```c
#include <stdio.h>
```
- **Define Constants**:
```c
#define PI 3.14159
```
- **Conditional Compilation**:
```c
#ifdef DEBUG
printf(“Debug mode\n”);
#endif
```