C programming is a foundational language developed in the 1970s by Dennis Ritchie. It is widely used for system programming, such as developing operating systems, embedded systems, and other performance-critical applications. Below is a detailed overview of C programming fundamentals:
A basic C program consists of:
Header Files: Libraries included at the start with #include, e.g., #include <stdio.h>.
Main Function: The main() function serves as the entry point of the program.
Statements and Code Blocks: Instructions are written inside { }.
Example:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
C provides various data types:
int: For integers (e.g., 10, -5)
float: For decimal numbers (e.g., 3.14)
char: For single characters (e.g., 'A')
double: For high-precision decimal numbers
Example:
int a = 10;
float b = 3.14;
char c = 'A';
Variables: Used to store data values. Example: int age = 25;
Constants: Immutable values. Example: const float PI = 3.14;
C provides different types of operators:
Arithmetic Operators: +, -, *, /, %
Relational Operators: ==, !=, <, >, <=, >=
Logical Operators: &&, ||, !
Example:
int a = 10, b = 5;
int sum = a + b; // sum = 15
Control the program flow using:
if-else: For decision-making.
switch: For choosing between multiple cases.
Loops: Repetition using for, while, do-while.
Example (if-else):
int num = 10;
if (num > 0) {
printf("Positive number");
} else {
printf("Negative number");
}
Functions break a program into smaller reusable components.
User-defined functions: Functions created by the programmer.
Built-in functions: Provided by C libraries.
Example:
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("Sum: %d", result);
return 0;
}
Arrays: Store a collection of elements of the same type. Example: int arr[5];
Pointers: Store memory addresses. Example: int *ptr;
Example (Pointer):
int a = 10;
int *ptr = &a;
printf("Value of a: %d", *ptr);
C allows data to be stored and retrieved using files:
Open a file: fopen()
Read data: fscanf() or fgets()
Write data: fprintf() or fputs()
Close a file: fclose()
Dynamic memory allocation functions in C include:
malloc(), calloc(), realloc(), and free().
Example:
int *ptr;
ptr = (int*) malloc(5 * sizeof(int)); // Allocating memory
if (ptr == NULL) {
printf("Memory not allocated.\n");
} else {
printf("Memory allocated successfully.\n");
}
free(ptr); // Free allocated memory
Start with simple programs like addition or multiplication.
Practice control statements and loops.
Build projects like a calculator or a number guessing game.
Explore data structures like arrays and linked lists.