C Programming
Complete C cheatsheet
Complete C Programming Cheatsheet
A comprehensive reference guide to C programming, covering basic to advanced concepts, syntax, examples, operators, data types, arrays, strings, functions, pointers, structures, unions, memory management, and file handling.
1. Introduction to C
C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell Laboratories in 1972.
Features of C
- Simple and efficient programming language.
- Procedural and structured programming.
- Portable across different platforms.
- Fast execution.
- Supports pointers and direct memory access.
- Rich collection of standard library functions.
- Suitable for system programming and embedded systems.
- Supports modular programming through functions.
Applications of C
- Operating systems
- Embedded systems
- Device drivers
- Compilers and interpreters
- Database systems
- Networking applications
- IoT projects
- System utilities
File Extensions
| Extension | Description |
|---|---|
.c | C source file |
.h | Header file |
.o | Object file |
.exe | Windows executable |
2. Structure of a C Program
#include <stdio.h> int main() { printf("Hello, World!"); return 0; }
Explanation
| Component | Description |
|---|---|
#include | Includes header files |
<stdio.h> | Standard input/output header |
int main() | Main function |
{ } | Defines a block |
printf() | Displays output |
return 0 | Indicates successful execution |
; | Terminates a statement |
Compilation Using GCC
gcc program.c -o program ./program
Compile with warnings:
gcc -Wall -Wextra -std=c11 -g program.c -o program
3. Character Set and Tokens
Tokens are the smallest individual elements of a C program.
Types of Tokens
| Token | Example |
|---|---|
| Keywords | int, return, if |
| Identifiers | total, number |
| Constants | 10, 3.14, 'A' |
| String literals | "Hello" |
| Operators | +, -, * |
| Punctuators | ;, {}, () |
Rules for Identifiers
- Must begin with a letter or underscore.
- Cannot begin with a digit.
- Cannot contain spaces.
- Cannot be a reserved keyword.
- C is case-sensitive.
int total; int _number; int marks1; // Invalid identifiers: // int 1marks; // int my marks; // int return;
4. Keywords in C
C11 contains 44 keywords.
| Category | Keywords |
|---|---|
| Data types | int, char, float, double, void |
| Decision-making | if, else, switch, case, default |
| Loops | for, while, do |
| Jump statements | break, continue, goto, return |
| Storage classes | auto, register, static, extern |
| Type modifiers | short, long, signed, unsigned |
| User-defined types | struct, union, enum, typedef |
| Type qualifiers | const, volatile, restrict |
| Other keywords | sizeof, _Alignof, _Alignas, _Atomic, _Bool, _Complex, _Generic, _Imaginary, _Noreturn, _Static_assert, _Thread_local |
Note: inline is a C99 keyword. bool, true, and false are available through <stdbool.h> in C99 and later.
5. Data Types
Data types specify the kind of data a variable can store.
5.1 Basic Data Types
| Data Type | Typical Size | Example |
|---|---|---|
char | 1 byte | 'A' |
int | 4 bytes | 100 |
float | 4 bytes | 10.5f |
double | 8 bytes | 25.567 |
void | No value | void |
Note: Sizes are implementation-dependent. The sizes above are common on modern systems.
5.2 Type Modifiers
| Modifier | Description |
|---|---|
signed | Supports positive and negative values |
unsigned | Supports non-negative values |
short | Short integer type |
long | Extended integer type |
long long | At least 64-bit integer range |
short int a = 10; long int b = 100000; long long int c = 123456789; unsigned int d = 50; signed int e = -20; long double f = 12.345L;
5.3 Derived Data Types
- Arrays
- Pointers
- Functions
5.4 User-Defined Data Types
- Structure (
struct) - Union (
union) - Enumeration (
enum) - Type definition (
typedef)
6. Variables and Constants
6.1 Variable Declaration
int age; float salary; char grade;
6.2 Variable Initialization
int age = 22; float price = 99.50f; char grade = 'A';
6.3 Multiple Variable Declaration
int a = 10, b = 20, c = 30;
6.4 Constants Using const
const float PI = 3.14159f;
6.5 Constants Using #define
#define MAX 100 #define PI 3.14159
Difference Between const and #define
const | #define |
|---|---|
| Defines a qualified object | Defines a macro |
| Has a data type | No data type |
| Follows normal scope rules | Textual substitution |
| Cannot be modified through that identifier | No variable to modify |
7. Input and Output
Header file: <stdio.h>
7.1 printf()
Displays output.
printf("Hello"); printf("Age = %d", age);
7.2 scanf()
Accepts input.
int age; scanf("%d", &age);
7.3 Common Input/Output Functions
| Function | Purpose |
|---|---|
printf() | Displays formatted output |
scanf() | Reads formatted input |
getchar() | Reads one character |
putchar() | Displays one character |
fgets() | Reads a line |
puts() | Displays a string |
fputs() | Writes a string |
sprintf() | Formats output into a string |
snprintf() | Formats bounded string output |
sscanf() | Reads formatted data from a string |
7.4 Format Specifiers
| Specifier | Data Type |
|---|---|
%d | int |
%i | int |
%u | unsigned int |
%hd | short int |
%ld | long int |
%lld | long long int |
%f | float in printf; float pointer in scanf |
%lf | double in scanf |
%Lf | long double |
%c | char |
%s | String |
%x | Hexadecimal |
%o | Octal |
%p | Pointer address |
%zu | size_t |
%% | Percentage symbol |
Example
#include <stdio.h> int main() { int age = 22; float marks = 85.5f; char grade = 'A'; printf("Age: %d\n", age); printf("Marks: %.2f\n", marks); printf("Grade: %c\n", grade); return 0; }
8. Escape Sequences
Escape sequences represent special characters.
| Escape Sequence | Meaning |
|---|---|
\n | New line |
\t | Horizontal tab |
\b | Backspace |
\r | Carriage return |
\a | Alert/bell |
\\ | Backslash |
\' | Single quotation mark |
\" | Double quotation mark |
\0 | Null character |
\v | Vertical tab |
\f | Form feed |
Example
printf("Hello\nWorld"); printf("Name:\tUday"); printf("\"C Programming\"");
9. Operators
Operators perform operations on variables and values.
9.1 Arithmetic Operators
| Operator | Operation | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
int a = 10, b = 3; printf("%d", a + b); // 13 printf("%d", a / b); // 3 printf("%d", a % b); // 1
Integer division discards the fractional part.
9.2 Relational Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Relational expressions produce 1 for true and 0 for false.
9.3 Logical Operators
| Operator | Meaning |
|---|---|
&& | Logical AND |
| ` | |
! | Logical NOT |
int age = 20; if (age >= 18 && age <= 60) { printf("Eligible"); }
9.4 Assignment Operators
| Operator | Example | Equivalent |
|---|---|---|
= | a = 5 | Assign |
+= | a += 5 | a = a + 5 |
-= | a -= 5 | a = a - 5 |
*= | a *= 5 | a = a * 5 |
/= | a /= 5 | a = a / 5 |
%= | a %= 5 | a = a % 5 |
&= | a &= 5 | Bitwise AND assignment |
| ` | =` | `a |
^= | a ^= 5 | Bitwise XOR assignment |
<<= | a <<= 1 | Left shift assignment |
>>= | a >>= 1 | Right shift assignment |
9.5 Increment and Decrement Operators
| Operator | Meaning |
|---|---|
++a | Pre-increment |
a++ | Post-increment |
--a | Pre-decrement |
a-- | Post-decrement |
int a = 5; printf("%d", ++a); // 6 int b = 5; printf("%d", b++); // 5 // b becomes 6
9.6 Bitwise Operators
| Operator | Operation |
|---|---|
& | Bitwise AND |
| ` | ` |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Left shift |
>> | Right shift |
int a = 5; // 0101 int b = 3; // 0011 printf("%d", a & b); // 1 printf("%d", a | b); // 7 printf("%d", a ^ b); // 6 printf("%d", a << 1); // 10 printf("%d", a >> 1); // 2
9.7 Conditional (Ternary) Operator
Syntax:
condition ? expression1 : expression2;
Example:
int a = 10, b = 20; int max = (a > b) ? a : b; printf("%d", max);
9.8 Other Operators
| Operator | Purpose |
|---|---|
sizeof | Returns size in bytes |
& | Address-of |
* | Pointer dereference |
, | Comma operator |
. | Structure member access |
-> | Structure pointer member access |
[] | Array subscript |
() | Function call |
10. Operator Precedence
Operators with higher precedence are evaluated first.
| Priority | Operators | Associativity |
|---|---|---|
| 1 | () [] . -> x++ x-- | Left to right |
| 2 | ++x --x ! ~ sizeof * & | Right to left |
| 3 | * / % | Left to right |
| 4 | + - | Left to right |
| 5 | << >> | Left to right |
| 6 | < <= > >= | Left to right |
| 7 | == != | Left to right |
| 8 | & | Left to right |
| 9 | ^ | Left to right |
| 10 | ` | ` |
| 11 | && | Left to right |
| 12 | ` | |
| 13 | ?: | Right to left |
| 14 | Assignment operators | Right to left |
| 15 | , | Left to right |
Tip: Use parentheses to make complex expressions easier to understand.
11. Type Conversion and Type Casting
Type conversion changes a value from one data type to another.
11.1 Implicit Type Conversion
Automatically performed by the compiler.
int a = 10; float b = 5.5f; float result = a + b;
11.2 Explicit Type Casting
Performed manually by the programmer.
int a = 10, b = 3; float result = (float)a / b; printf("%.2f", result);
Output:
3.33
12. Decision-Making Statements
12.1 if Statement
if (condition) { // Statements }
Example:
int age = 20; if (age >= 18) { printf("Eligible"); }
12.2 if-else Statement
if (condition) { // True block } else { // False block }
12.3 else-if Ladder
int marks = 75; if (marks >= 90) { printf("Grade A"); } else if (marks >= 75) { printf("Grade B"); } else if (marks >= 50) { printf("Grade C"); } else { printf("Fail"); }
12.4 Nested if
if (age >= 18) { if (age <= 60) { printf("Eligible"); } }
12.5 switch Statement
Used for multiple selection conditions.
int choice = 2; switch (choice) { case 1: printf("One"); break; case 2: printf("Two"); break; case 3: printf("Three"); break; default: printf("Invalid choice"); }
Important Points:
caselabels must be integer constant expressions.breakprevents fall-through.defaultis optional.- Switch expressions must have an integer or enumeration type.
13. Looping Statements
Loops execute a block of code repeatedly.
13.1 for Loop
Syntax:
for (initialization; condition; update) { // Statements }
Example:
for (int i = 1; i <= 5; i++) { printf("%d\n", i); }
13.2 while Loop
Condition is checked before execution.
int i = 1; while (i <= 5) { printf("%d\n", i); i++; }
13.3 do-while Loop
Executes at least once.
int i = 1; do { printf("%d\n", i); i++; } while (i <= 5);
13.4 Nested Loop
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { printf("* "); } printf("\n"); }
13.5 Loop Control Statements
| Statement | Purpose |
|---|---|
break | Terminates the nearest loop or switch |
continue | Skips the remaining loop body iteration |
goto | Transfers control to a labeled statement |
14. Arrays
An array stores multiple values of the same data type in contiguous memory.
14.1 One-Dimensional Array
Declaration:
int numbers[5];
Initialization:
int numbers[5] = {10, 20, 30, 40, 50};
Accessing elements:
printf("%d", numbers[0]);
Array indexing starts at 0.
14.2 Input and Output of Array
#include <stdio.h> int main() { int a[5]; for (int i = 0; i < 5; i++) { scanf("%d", &a[i]); } for (int i = 0; i < 5; i++) { printf("%d ", a[i]); } return 0; }
14.3 Two-Dimensional Array
Used to represent matrices and tabular data.
Declaration:
int matrix[3][3];
Initialization:
int matrix[2][2] = { {1, 2}, {3, 4} };
Accessing elements:
printf("%d", matrix[0][1]);
14.4 Matrix Traversal
for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("%d ", matrix[i][j]); } printf("\n"); }
14.5 Three-Dimensional Array
int a[2][3][4];
Used for multidimensional data.
14.6 Important Array Operations
| Operation | Description |
|---|---|
| Traversal | Visiting each element |
| Insertion | Adding an element |
| Deletion | Removing an element |
| Searching | Finding an element |
| Sorting | Arranging elements |
| Merging | Combining arrays |
| Reversing | Reversing the order |
15. Strings
A string is an array of characters terminated by the null character \0.
15.1 String Declaration
char name[20];
15.2 String Initialization
char name[] = "Uday";
Equivalent character array:
char name[] = {'U', 'd', 'a', 'y', '\0'};
15.3 String Input and Output
char name[50]; fgets(name, sizeof(name), stdin); printf("%s", name);
Avoid gets() because it is unsafe and removed from modern C standards.
15.4 String Handling Functions
Header file: <string.h>
| Function | Purpose |
|---|---|
strlen() | Returns string length |
strcpy() | Copies a string |
strncpy() | Copies up to a specified number of characters |
strcat() | Concatenates strings |
strncat() | Concatenates a limited number of characters |
strcmp() | Compares two strings |
strncmp() | Compares a limited number of characters |
strchr() | Finds a character |
strrchr() | Finds the last occurrence of a character |
strstr() | Finds a substring |
strtok() | Splits a string into tokens |
Example:
#include <stdio.h> #include <string.h> int main() { char str1[50] = "Hello"; char str2[] = " World"; printf("Length: %zu\n", strlen(str1)); strcat(str1, str2); printf("Combined: %s\n", str1); return 0; }
Note: Functions such as strcpy() and strcat() require sufficient destination storage to prevent buffer overflow.
16. Functions
A function is a reusable block of code that performs a specific task.
16.1 Function Declaration (Prototype)
int add(int, int);
16.2 Function Definition
int add(int a, int b) { return a + b; }
16.3 Function Calling
int result = add(10, 20);
Complete Example
#include <stdio.h> int add(int, int); int main() { int result = add(10, 20); printf("Sum = %d", result); return 0; } int add(int a, int b) { return a + b; }
16.4 Types of Functions
| Type | Arguments | Return Value |
|---|---|---|
| 1 | No | No |
| 2 | Yes | No |
| 3 | No | Yes |
| 4 | Yes | Yes |
16.5 Recursive Function
A function that calls itself.
Example: Factorial.
int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }
16.6 Call by Value
A copy of the variable is passed.
void change(int x) { x = 100; }
Changes do not affect the original variable.
16.7 Modifying Original Values Through Pointers
C passes arguments by value, but pointers allow a function to modify the caller's objects.
void change(int *x) { *x = 100; } int main() { int a = 10; change(&a); printf("%d", a); // 100 return 0; }
17. Pointers
A pointer is a variable that stores the address of another object or function.
17.1 Pointer Declaration
int *ptr;
17.2 Pointer Initialization
int a = 10; int *ptr = &a;
17.3 Pointer Operators
| Operator | Purpose |
|---|---|
& | Address-of |
* | Dereferencing |
Example:
#include <stdio.h> int main() { int a = 10; int *ptr = &a; printf("Value: %d\n", a); printf("Address: %p\n", (void *)ptr); printf("Pointer value: %d\n", *ptr); return 0; }
17.4 NULL Pointer
A pointer that does not point to a valid object or function.
int *ptr = NULL;
17.5 Void Pointer
A generic object pointer.
int a = 10; void *ptr = &a; printf("%d", *(int *)ptr);
17.6 Pointer to Pointer
int a = 10; int *p = &a; int **pp = &p; printf("%d", **pp);
17.7 Pointer Arithmetic
int a[] = {10, 20, 30}; int *p = a; printf("%d", *p); printf("%d", *(p + 1)); printf("%d", *(p + 2));
Pointer arithmetic is scaled by the size of the pointed-to type.
17.8 Array and Pointer Relationship
int a[3] = {10, 20, 30}; printf("%d", *(a + 1)); printf("%d", a[1]);
Both access the second element.
Important: Arrays and pointers are related, but they are not the same type.
18. Storage Classes
Storage classes determine aspects of variable lifetime, scope, and linkage.
| Storage Class | Scope | Lifetime |
|---|---|---|
auto | Block | Automatic |
register | Block | Automatic |
static local | Block | Entire program |
static file-scope | File | Entire program |
extern | Depends on declaration | Usually entire program for the external object |
18.1 auto
void test() { auto int x = 10; }
18.2 static
void counter() { static int count = 0; count++; printf("%d\n", count); }
Calling counter() three times prints:
1 2 3
18.3 extern
extern int total;
Declares an object defined elsewhere.
18.4 register
register int i;
A hint to the implementation that a variable may be accessed frequently.
19. Structures
A structure groups variables of different data types under one name.
19.1 Structure Declaration
struct Student { int roll; char name[50]; float marks; };
19.2 Structure Variable
struct Student s1;
19.3 Structure Initialization
struct Student s1 = {101, "Uday", 90.5f};
19.4 Accessing Structure Members
printf("%d", s1.roll); printf("%s", s1.name); printf("%.2f", s1.marks);
19.5 Structure with Pointer
struct Student *ptr = &s1; printf("%d", ptr->roll);
19.6 Array of Structures
struct Student s[3];
19.7 Nested Structure
struct Address { char city[30]; }; struct Student { int roll; struct Address addr; };
20. Unions
A union is a user-defined data type in which all members share the same memory location.
20.1 Union Declaration
union Data { int i; float f; char ch; };
20.2 Union Example
union Data d; d.i = 10; printf("%d", d.i);
Difference Between Structure and Union
| Structure | Union |
|---|---|
| Each member has separate storage | Members share storage |
| Can store multiple member values simultaneously | Only one member value is meaningfully stored at a time |
| Size includes storage for all members and padding | Size is enough for the largest member plus possible padding |
| Members have different addresses | Members start at the same address |
21. Enumerations (enum)
An enumeration defines named integer constants.
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
Example:
enum Day today = WED; printf("%d", today); // 2
Custom Values
enum Status { SUCCESS = 1, FAILURE = 0, PENDING = 5 };
22. typedef
typedef creates an alternative name for an existing type.
typedef unsigned int uint; uint age = 22;
typedef with Structure
typedef struct { int roll; char name[30]; } Student; Student s1;
23. Dynamic Memory Allocation
Header file: <stdlib.h>
Dynamic memory allocation reserves memory during program execution.
23.1 malloc()
Allocates a block of uninitialized memory.
int *ptr = malloc(5 * sizeof *ptr); if (ptr == NULL) { return 1; }
23.2 calloc()
Allocates memory for multiple elements and initializes all bytes to zero.
int *ptr = calloc(5, sizeof *ptr);
23.3 realloc()
Changes the size of an allocated memory block.
int *temp = realloc(ptr, 10 * sizeof *ptr); if (temp != NULL) { ptr = temp; }
23.4 free()
Releases dynamically allocated memory.
free(ptr); ptr = NULL;
Comparison
| Function | Purpose | Initial Contents |
|---|---|---|
malloc() | Allocates memory | Uninitialized |
calloc() | Allocates multiple elements | All bytes zero |
realloc() | Resizes allocation | Preserves existing contents up to the smaller size |
free() | Releases allocation | Not applicable |
24. File Handling
File handling allows programs to create, read, write, and modify files.
Header file: <stdio.h>
24.1 File Pointer
FILE *fp;
24.2 Opening a File
fp = fopen("data.txt", "r");
24.3 File Opening Modes
| Mode | Description |
|---|---|
"r" | Read existing file |
"w" | Write; creates or truncates file |
"a" | Append; creates if needed |
"r+" | Read and write existing file |
"w+" | Read and write; truncates or creates |
"a+" | Read and append; creates if needed |
"rb" | Read binary file |
"wb" | Write binary file |
"ab" | Append binary file |
"rb+" | Read and write binary file |
24.4 Writing to a File
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "w"); if (fp == NULL) return 1; fprintf(fp, "Hello C Programming"); fclose(fp); return 0; }
24.5 Reading from a File
FILE *fp = fopen("data.txt", "r"); if (fp == NULL) return 1; char str[100]; while (fgets(str, sizeof str, fp) != NULL) { printf("%s", str); } fclose(fp);
24.6 Important File Functions
| Function | Purpose |
|---|---|
fopen() | Opens a file |
fclose() | Closes a file |
fprintf() | Writes formatted data |
fscanf() | Reads formatted data |
fgetc() | Reads a character |
fputc() | Writes a character |
fgets() | Reads a line |
fputs() | Writes a string |
fread() | Reads binary data |
fwrite() | Writes binary data |
fseek() | Changes file position |
ftell() | Returns current file position |
rewind() | Moves position to beginning |
feof() | Tests end-of-file indicator |
ferror() | Tests error indicator |
remove() | Deletes a file |
rename() | Renames a file |
25. Preprocessor Directives
Preprocessor directives are processed before compilation.
25.1 #include
#include <stdio.h> #include "myheader.h"
25.2 #define
#define PI 3.14159 #define SQUARE(x) ((x) * (x))
25.3 #undef
#undef PI
25.4 Conditional Compilation
#ifdef DEBUG printf("Debug mode"); #endif
Other directives:
#if #elif #else #endif #ifndef
25.5 Header Guards
Prevent repeated inclusion of the same header.
#ifndef MYHEADER_H #define MYHEADER_H void display(void); #endif
26. Command-Line Arguments
Command-line arguments allow users to pass values while executing a program.
#include <stdio.h> int main(int argc, char *argv[]) { printf("Arguments: %d\n", argc); for (int i = 0; i < argc; i++) { printf("%s\n", argv[i]); } return 0; }
argc: Number of command-line arguments.argv: Array of argument strings.argv[0]: Normally the program name.
27. Important Header Files
| Header File | Purpose |
|---|---|
<stdio.h> | Input and output |
<stdlib.h> | Memory allocation, conversions, utilities |
<string.h> | String manipulation |
<math.h> | Mathematical operations |
<ctype.h> | Character testing and conversion |
<time.h> | Date and time |
<limits.h> | Integer limits |
<float.h> | Floating-point limits |
<stdbool.h> | Boolean type and constants |
<stdint.h> | Fixed-width integer types |
<stddef.h> | Common definitions such as size_t |
<assert.h> | Debugging assertions |
<errno.h> | Error reporting |
<signal.h> | Signal handling |
<locale.h> | Localization |
<stdarg.h> | Variable argument lists |
28. Mathematical Functions
Header file: <math.h>
| Function | Purpose | Example |
|---|---|---|
sqrt(x) | Square root | sqrt(25) |
pow(x,y) | Power | pow(2,3) |
ceil(x) | Rounds upward | ceil(4.2) |
floor(x) | Rounds downward | floor(4.8) |
round(x) | Rounds to nearest integer value | round(4.5) |
fabs(x) | Absolute floating-point value | fabs(-5.5) |
fmod(x,y) | Floating-point remainder | fmod(10,3) |
sin(x) | Sine | sin(x) |
cos(x) | Cosine | cos(x) |
tan(x) | Tangent | tan(x) |
log(x) | Natural logarithm | log(10) |
log10(x) | Base-10 logarithm | log10(100) |
exp(x) | Exponential | exp(2) |
Trigonometric functions use radians.
29. Character Functions
Header file: <ctype.h>
| Function | Purpose |
|---|---|
isalpha() | Checks alphabetic character |
isdigit() | Checks digit |
isalnum() | Checks alphabet or digit |
islower() | Checks lowercase |
isupper() | Checks uppercase |
isspace() | Checks whitespace |
ispunct() | Checks punctuation |
isprint() | Checks printable character |
isxdigit() | Checks hexadecimal digit |
tolower() | Converts to lowercase |
toupper() | Converts to uppercase |
Example:
#include <stdio.h> #include <ctype.h> int main() { char ch = 'a'; printf("%c", toupper((unsigned char)ch)); return 0; }
30. Common Programming Problems
These are useful for practical examinations and programming interviews.
| Problem | Basic Logic |
|---|---|
| Even or odd | n % 2 == 0 |
| Positive or negative | Compare with zero |
| Largest of two numbers | Compare a and b |
| Largest of three numbers | Multiple comparisons |
| Swap two numbers | Temporary variable |
| Factorial | Repeated multiplication |
| Prime number | Check divisors up to square root |
| Fibonacci series | Add previous two terms |
| Reverse a number | Extract digits using % 10 |
| Palindrome number | Compare with reversed number |
| Armstrong number | Sum each digit raised to number of digits |
| Sum of digits | Repeated % 10 |
| Count digits | Repeated division by 10 |
| GCD | Euclidean algorithm |
| LCM | a / gcd(a,b) * b for nonzero inputs |
30.1 Even or Odd
if (n % 2 == 0) printf("Even"); else printf("Odd");
30.2 Factorial
int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; }
30.3 Prime Number
int isPrime = 1; if (n <= 1) { isPrime = 0; } else { for (int i = 2; i <= n / i; i++) { if (n % i == 0) { isPrime = 0; break; } } } if (isPrime) printf("Prime"); else printf("Not Prime");
31. Pattern Programs
31.1 Square Pattern
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { printf("* "); } printf("\n"); }
Output:
* * * * * * * * * * * * * * * * * * * * * * * * *
31.2 Right Triangle
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { printf("* "); } printf("\n"); }
Output:
* * * * * * * * * * * * * * *
31.3 Inverted Triangle
for (int i = 5; i >= 1; i--) { for (int j = 1; j <= i; j++) { printf("* "); } printf("\n"); }
31.4 Number Triangle
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { printf("%d ", j); } printf("\n"); }
32. Common Errors in C
| Error | Meaning |
|---|---|
| Syntax error | Incorrect programming syntax |
| Runtime error | Error during program execution |
| Logical error | Program executes but produces incorrect output |
| Linker error | Problem linking program components |
| Compilation error | Compiler cannot compile the source code |
Common Mistakes
// Missing semicolon int a = 10 // Incorrect comparison if (a = 10) // Uninitialized pointer int *ptr; *ptr = 10; // Array out-of-bounds int arr[5]; arr[5] = 10; // Incorrect scanf int age; scanf("%d", age);
Correct Versions
int a = 10; if (a == 10) { printf("Equal"); } int *ptr = NULL; int arr[5]; arr[4] = 10; int age; scanf("%d", &age);
33. Memory Concepts
| Concept | Description |
|---|---|
| Stack | Commonly holds automatic local variables and call information |
| Heap | Used for dynamic memory allocation |
| Data segment | Stores initialized static and global objects |
| BSS segment | Stores zero-initialized and uninitialized static/global objects |
| Text segment | Contains executable instructions |
Common Memory Problems
- Memory leak: Allocated memory is never released.
- Dangling pointer: Pointer refers to an object whose lifetime has ended.
- Wild pointer: Uninitialized pointer.
- Null pointer dereference: Attempting to access through a null pointer.
- Buffer overflow: Writing beyond an object's allocated bounds.
34. Advanced C Concepts
| Concept | Description |
|---|---|
| Function pointer | Stores a function's address |
| Pointer to array | Points to an entire array |
| Array of pointers | Array containing pointer elements |
| Variadic function | Accepts a variable number of arguments |
| Bit fields | Structure members with specified bit widths |
| Flexible array member | Array member with unspecified size at the end of a structure |
volatile | Indicates an object may change outside normal program flow |
const | Prevents modification through a particular identifier |
restrict | Provides an aliasing-related optimization promise |
inline | Suggests inline function substitution |
_Generic | Enables compile-time generic selection |
| Function recursion | Function calling itself |
35. Quick C Syntax Reference
| Task | Syntax |
|---|---|
| Print output | printf("Hello"); |
| Read integer | scanf("%d", &a); |
| Declare integer | int a; |
| Declare float | float a; |
| Declare character | char ch; |
| Declare array | int arr[10]; |
| Declare string | char str[50]; |
| Declare pointer | int *ptr; |
| Declare function | int add(int a, int b); |
| Declare structure | struct Student s; |
| Declare union | union Data d; |
| Declare enum | enum Day d; |
| Allocate memory | malloc() |
| Release memory | free() |
| Open file | fopen() |
| Close file | fclose() |
| Calculate size | sizeof() |
| Return from function | return value; |
| Include library | #include <stdio.h> |