Basic Structure of a C Program
#include <stdio.h>
int main() {
// Code goes here
return 0;
}
Comments
Single-line comment: // This is a comment
Multi-line comment: /* This is a comment */
Data Types
Basic Types: int, float, double, char
Modifiers: short, long, signed, unsigned
Void: void (for no return type or empty parameter lists)
Variable Declaration
int x;
float y;
char ch;
const int x = 1; //constant
Input
scanf("%d", &x);
Here, %d refers to the datatype of the input variable & x refers to the input variable.
%d: Integer
%l: Long
%ld: Long Integer
%lld: Long Long Integer
%f: float
%lf: Double
%c: Character
%s: string
Output
printf("Hello, World!\n");
Operators
Arithmetic: +, -, *, /, %
Relational: ==, !=, <, >, <=, >=
Logical: &&, ||, !
Assignment: =, +=, -=, *=, /=, %=
Increment/Decrement: ++, —
Bitwise: &, |, ^, ~, <<, >>
Control Structures
Conditional Statements:
if (condition) {
// code
} else if(condition) {
// code
} else {
// code
}Switch Case:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}Loops
For loop
for (initialization; condition; update) {
// code
}While loop
while (condition) {
// code
}Do-While loop
do {
// code
} while (condition);Functions
Function Declaration:
return_type function_name(parameters);
Function Definition:
return_type function_name(parameters) {
// code
}Function Call:
function_name(arguments);Pointers
Declaration: int *ptr;
Initialization: ptr = &x;
Dereferencing: *ptr
Function Pointers
void (*funcPtr)(int);
funcPtr = &functionName;Arrays
Declaration:
int arr[10]; // Declaring an array of size 10Accessing Elements:
arr[0] = 5;Strings
Declaration:
char str[20]; // Declares a string with space for 20 characters
Initialization:
char str[] = "Hello";Structures
Declaration:
struct StructName {
data_type member1;
data_type member2;
};Accessing Members:
struct StructName s;
s.member1 = value;Unions
Declaration:
union UnionName {
data_type member1;
data_type member2;
};Accessing Members:
union UnionName u;
u.member1 = value;
Typedef
Creating an Alias for a Data Type:
typedef unsigned long int ULI;
ULI number;Enums
Declaration:
enum Day {Sunday, Monday, Tuesday};
enum Day today;File Handling
Opening a File:
FILE *filePointer = fopen("filename.txt", "r");Closing a File:
fclose(filePointer);Preprocessor Directives
Includes: #include <stdio.h>
Define Constants: #define PI 3.14
Dynamic Memory Allocation
int *ptr = (int*) malloc(size * sizeof(int));
free(ptr);sizeof Operator
int size = sizeof(variable);