C Programming Sticky Notes

Basic Structure

#include <stdio.h> int main() { printf("Hello, World!"); return 0; }

Preprocessor

Variables

Declaration:
int age;
Initialization:
char grade = 'A';

printf & scanf

Data Types & Ranges

Operators

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

Functions

Declaration:
int add(int, int);
Call:
int sum = add(5, 3);
Supports call by value & call by reference.

Types of Functions

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

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

Recursion

A function that calls itself.
return_type func(params) { if (base_case) return value; else return func(new_params); }