Basic Structure
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
Preprocessor
#include
: Includes header files like <stdio.h>, <string.h>, <math.h>,<conio.h> etc.
#define
: Defines constants.
Variables
Declaration:
int age;
Initialization:
char grade = 'A';
printf & scanf
-
printf (Output)
printf("Age: %d", age);
-
scanf (Input)
scanf("%d", &age);
Note: Always use the address-of operator (`&`) for variables.
Data Types & Ranges
- Sizes: int(2/4), float(4), double(8), char(1) bytes.
- char: -128 to 127
- int (16-bit): -32k to 32k
- int (32-bit): -2B to 2B
- float: 3.4E-38 to 3.4E+38
- double: 1.7E-308 to 1.7E+308
Operators
- Arithmetic:
+ - * / %
- Relational:
== != > < >= <=
- Logical:
&& || !
- Bitwise:
& | ^ ~ << >>
Type Conversion
Implicit:Low —> High, no loss of data.
int + float = float;
Explicit (Casting):High —> Low, loss of data.
int a = (int)10.5;
Control Structures
- Conditional:
if, else if, else
switch-case-break
- Unconditional:
break, continue, return, goto
- Loops:
for, while, do-while
Functions
Declaration:
int add(int, int);
Call:
int sum = add(5, 3);
Supports call by value & call by reference.
Types of Functions
- 1. No args & no return
- 2. With args & no return
- 3. No args & with return
- 4. With args & with return
Pointers
Stores the memory address of another variable.
int x = 10;
int *ptr = &x;
*ptr gets the value at x.
Arrays
Collection of same-type elements.
1D: int a[5] = {10, 20};
2D: int b[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Strings
Array of characters ending with `\0`.
char name[] = "Imad";
use string.h for string functions like strlen, strcpy, strcat.
Note: No '&' in 'scanf '.
String I/O Functions
- gets: Reads a line (Unsafe!)
- puts: Writes a string + `\n`
- fgets: Safely reads a line from a stream.
- fputs: Writes a string to a stream.
Structures
Collection of different data types. Each member has its own memory location.
struct Student {
int id;
char name[50];
};
struct Student s1;
s1.id = 101;
Unions
Collection of different data types in the same memory location. Only one member can hold a value at any given time.
union Data {
int i;
char str[20];
};
Typedef
Creates an alias for a data type.
typedef struct {
int id;
char name[20];
} Student;
Student s1;
Enum
Assigns names to integer constants.
enum Day {SUN, MON};
enum Day d = MON;
Note: Sturcture, Union and Enum are user-defined data types.
File Handling
FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "Text");
fscanf(fp, "%d", &var);
fclose(fp);
File Modes
- "r": Read Only (must exist)
- "w": Write Only (overwrites)
- "a": Append Only (creates)
- "r+": Read & Write
- "w+": Write & Read (overwrites)
- "a+": Append & Read
Recursion
A function that calls itself.
return_type func(params) {
if (base_case)
return value;
else
return func(new_params);
}