Variables
Three Elements of Variables:
- Name (identifier)
- Memory address (&variable_name)
- Value
Variables are separated by commas and terminated by semicolons.
int- Integer type - Format specifiers:%ddecimal,%ooctal,%xhexadecimalfloat- Floating-point type - Format specifier:%fchar- Character type - Format specifiers:%ccharacter,%sstring
%4d outputs value in 4 spaces right-aligned, padding with spaces if needed
%-4d outputs value in 4 spaces left-aligned, padding with spaces if needed
#include <stdio.h>
void main() {
}
Enteger Constants
- Octal numbers: start with 0 (e.g., 010, 012)
- Hexadecimal numbers: start with 0x (e.g., 0x10, 0x12, 0x22)
Floating-point Constants
- Decimal form: e.g., 3.14, -9.8
- Scientific notation: e.g., 1.2E+5, 3.14E+9, 9.8E+3
- Format specifiers:
%escientific,%fdecimal,%gchoose smallest representation
Escape Sequences
\n- New line\t- Horizontal tab\b- Backspace\r- Carriage return\'or\"- Quote characters\\- Backslash
Note: Single quotes can only contain one character, e.g., 'a', not 'ab'
ASCII Codes
- a → 97, A → 65, 0 → 48, space → 32
Symbolic Constants
#include <stdio.h>
# define PI 3.14
void main() {
...
area = PI * radius * radius; // PI replaced with 3.14
...
}
Operators
Precedence
- Logical NOT (!)
- Multiplication, division, modulo (* / %)
- Addition, subtraction (+ -)
- Relational operators (>, <, >=, <=)
- Equality operators (==, !=)
- Logical AND (&&)
- Logical OR (||)
- Assignment operator (=)
In C, division (/) performs integer division: 5/2 = 2
Modulo (%) requires both operands to be integers
Arithmetic Operators
Arithmetic operators have higher precedence than assignment operators
int a = 12;
a += a *= a; // a = a + (a * a) = 12 + 144 = 156
Examples: .7 == 0.7, 12. == 12.0, .8 == 0.8
Increment and Decrement
int i = 10;
int j = ++i; // increment first, then use
int k = i++; // use first, then increment
int x = 10;
int y = --x; // decrement first, then use
int z = x--; // use first, then decrement
Relational Operators
Equal (==), Not equal (!=)
C uses integer 1 for true, 0 for false
AND (&&), OR (||), NOT (!)
0, 0.0, '\0', NULL evaluate to false
"a" && 2 evaluates to true
Logical AND Optimization
int a = 0, b = 0;
int result = a && ++b; // b not incremented due to optimization
Logical OR Optimization
int a = 1, b = 0;
int result = a || ++b; // b not incremented due to optimization
Conditional Statements
Switch Statement
switch(expression) {
case constant1: statements; break;
case constant2: statements; break;
case constant3: statements; break;
default: statements; break;
}
If-Else Statement
if(condition1) {
statement1;
}
else if(condition2) {
statement2;
}
else {
statement3;
}
Loops
While Loop
while(condition) {
statement;
}
Do-While Loop
do {
statement;
} while(condition);
For Loop
for(initialization; condition; increment) {
statement;
}
Functions
Built-in Functions
val = getchar()- read one charactergets(val)- read string into valputchar('a')- output characterputs('abc')- output stringpow(x,y)- calculate x raised to power y
User-defined Functions
Function signature: return type, function name, parameters
return_type function_name(parameter_type parameter_name, ...) {
statements;
}
Function Call
Calling Function
The function that calls another function (with actual arguments)
return_type variable_name = function_name(actual_parameter1, actual_parameter2);
Callee Function
The function being called (with formal parameters)
Formal parameters are independent of actual parameters
#include <stdio.h>
int add(int a, int b); // function declaration
int main() {
int a = 2, b = 4, c = 0;
c = add(a, b); // calling function
printf("Result: %d", c);
return 0;
}
int add(int a, int b) { // definition
return a + b;
}
Arrays
One-dimensional Arrays
type array_name[size] = {value1, value2, ...};
int array[4] = {120, 340, 65, 97};
Access element: array[index], index starts at 0
Two-dimensional Arrays
type array_name[rows][columns];
float array[4][2]; // 4 rows, 2 columns
int array[2][3] = {{1,2,3},{4,5,6}};
Strings
char array[constant_expression];
char array[6] = "china"; // includes null terminator
String Operations
#include <string.h>
strcpy(destination, source); // copy entire string including null
strncpy(destination, source, count); // copy up to count characters
strcat(destination, source); // append source to destination
strcmp(string1, string2); // compare strings
Pointers
Pointer Basics
A pointer stores memory address of another variable
type *pointer_name;
int n = 99, *p = &n;
printf("%d\n", *p); // prints 99
*p = 20; // changes n to 20
Multi-level Pointers
int i = 99, *q = &i, **p = &q;
Pointer and Arrays
int arr[] = {1,2,3,4,5,6};
int *p = arr;
for(int i = 0; i < 6; i++) {
printf("%d\n", *(p+i)); // same as p[i]
}
Function Calls
Nested Calls
A function can call another function during execution
Recursive Calls
long factorial(int n) {
if(n == 1 || n == 0) return 1;
else return n * factorial(n-1);
}
Preprocessing and Conditional Compilation
Preprocessor Directives
#include <file.h> // standard library
#include "file.h" // user header file
Conditional Compilation
#ifndef HEADER_NAME
#define HEADER_NAME
...
#endif
Macros
#define MACRO_NAME VALUE
#define SQUARE(x) ((x)*(x))
int result = SQUARE(5); // expands to (5)*(5)
Storage Classes
Local Variables
Declared inside functions, accessible only within that scope
Global Variables
Declared outside functions, available throughout program
Static Variables
Initialized once, retains value between calls
static int counter = 0;
Register Variables
Hint to compiler to store in CPU register for faster access
register int variable;
External Variables
Extend scope of variables beyond their current block
extern int global_var;
Structures, Unions, and Enums
Structures
struct student {
char name[20];
int age;
float score;
};
struct student person;
person.age = 20;
Unions
union data {
int i;
float f;
char c;
};
union data u;
u.i = 10; // overwrites f and c values
Enums
enum days {MONDAY, TUESDAY, WEDNESDAY};
enum days today = MONDAY;
File Operations
File Types
- Text files: ASCII encoded, for text data
- Binary files: raw data, for multimedia
File Handling
FILE *fp;
fp = fopen("filename.txt", "r");
fclose(fp);
File Access Modes
- "r" - read only
- "w" - write (overwrites existing)
- "a" - append
- "r+" - read/write
- "w+" - write/read
Reading/Writing
fprintf(fp, "%s %d", name, age);
fscanf(fp, "%s %d", name, &age);
Character Functions
char ch = fgetc(fp);
fputc(ch, fp);
String Functions
char buffer[100];
fgets(buffer, 100, fp);
fputs(buffer, fp);
Binary Data
fwrite(data, sizeof(data), count, fp);
fread(data, sizeof(data), count, fp);
Dynamic Memory Allocation
#include <stdlib.h>
int *ptr = (int*)malloc(5 * sizeof(int));
free(ptr);
int *new_ptr = (int*)realloc(ptr, 10 * sizeof(int));
int *array = (int*)calloc(5, sizeof(int));