C Programming Notes - Aishu
1. Introduction to C
C is a powerful general-purpose programming language developed by Dennis Ritchie.
It is widely used for system programming, developing operating systems, and embedded systems.
Basic structure:
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
2. Data Types and Variables
Primary data types: int, float, char, double.
int a = 10;
float b = 5.5;
char c = 'A';
double d = 3.14159;
3. Operators in C
Arithmetic: +, -, *, /, %
int a = 10, b = 3;
printf("%d", a % b); // 1
Relational: >, <, >=, <=, ==, !=
Logical: &&, ||, !
Assignment: =, +=, -=, *=, /=
Increment/Decrement: ++, --
Bitwise: &, |, ^, <<, >>
Example:
int x = 5, y = 3;
printf("%d", x & y); // 1
4. Control Statements
if, if-else, nested if, switch-case, loops
Example:
if (a > b) printf("A is greater");
else printf("B is greater");
Loop example:
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
5. Functions
Functions modularize code.
Syntax:
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(2, 3);
printf("%d", result);
}
6. Pointers
Pointer stores address of a variable.
int a = 10;
int *p = &a;
printf("%d", *p); // prints 10
Pointer to pointer:
int **pp = &p;
printf("%d", **pp);
7. Structures and Unions
Structure:
struct Student {
int rollNo;
char name[20];
};
struct Student s1 = {101, "Aishu"};
Union (shares memory):
union Data {
int i;
float f;
};
8. File Handling
FILE *fptr = fopen("file.txt", "w");
fprintf(fptr, "Hello!");
fclose(fptr);
Reading:
fptr = fopen("file.txt", "r");
char ch = fgetc(fptr);
while (ch != EOF) {
putchar(ch);
ch = fgetc(fptr);
}
9. Dynamic Memory Allocation
malloc, calloc, realloc, free
int *ptr = (int*) malloc(5 * sizeof(int));
ptr[0] = 10;
ptr = realloc(ptr, 10 * sizeof(int));
free(ptr);
10. Preprocessor Directives
#define PI 3.14
#define SQUARE(x) ((x)*(x))
printf("%f", PI);
printf("%d", SQUARE(5));
#ifdef DEBUG
printf("Debug mode");
#endif