C Programming Concepts and Examples
1. Lifetime of Variables
The lifetime of a variable refers to the duration for which the variable exists in memory during program
execution.
Types:
1. Automatic: Local variables inside functions, exist during function execution.
2. Static: Declared with 'static', exist for the lifetime of the program.
3. Dynamic: Allocated using malloc/calloc, exist until freed.
4. Global: Declared outside any function, exist till program ends.
2. Storage Classes in C
C has four storage classes:
1. auto: Default for local variables. Example: auto int a;
2. register: Suggests storing variable in CPU register. Example: register int speed;
3. static: Retains value across function calls. Example: static int count;
4. extern: Refers to a global variable defined elsewhere. Example: extern int x;
3. Recursion vs Iteration
| Feature | Recursion | Iteration |
|----------------|----------------------------------|--------------------------------------|
| Definition | Function calls itself | Loop repeats a set of instructions |
| Memory Usage | More (stack memory) | Less |
| Performance | Slower | Faster |
| Simplicity | Elegant for complex tasks | Better for simple repetitive tasks |
4. GCD using Recursion
int gcd(int a, int b) {
if (b == 0)
return a;
else
C Programming Concepts and Examples
return gcd(b, a % b);
5. Fibonacci using Recursion
int fibonacci(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fibonacci(n - 1) + fibonacci(n - 2);
6. Array Operations
a) Insertion: Shift elements to make space.
b) Deletion: Shift elements left to fill gap.
c) Searching: Loop through array to find value.
7. Transpose of 3x3 Matrix
int matrix[3][3], transpose[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];