C Programming Notes
1. Arrays
Definition:
An array is a collection of elements of the same data type stored in contiguous memory locations.
Syntax:
datatype array_name[size];
Example:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
return 0;
2. 1D Array
Definition:
A one-dimensional array is a linear array where elements are accessed using a single index.
Syntax:
datatype array_name[size];
Example:
#include <stdio.h>
int main() {
int marks[4] = {85, 90, 78, 92};
for(int i = 0; i < 4; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
return 0;
3. 2D Array
Definition:
A two-dimensional array is an array of arrays, often used to represent matrices.
Syntax:
datatype array_name[row_size][column_size];
Example:
#include <stdio.h>
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
return 0;
4. Functions
Definition:
A function is a block of code that performs a specific task.
Syntax:
datatype function_name(parameter_list) {
// body
return value;
Example:
#include <stdio.h>
int add(int a, int b) {
return a + b;
int main() {
printf("Sum: %d", add(3, 4));
return 0;
5. Function Types
Built-in Functions:
Functions provided by C libraries.
Example:
#include <stdio.h>
int main() {
printf("Hello World\n"); // printf is a built-in function
return 0;
User-defined Functions:
Functions created by users to perform specific tasks.
6. User-defined Function Types
a) With return type and arguments:
int sum(int a, int b) {
return a + b;
b) No return type, but with arguments:
void printSum(int a, int b) {
printf("Sum: %d", a + b);
c) With return type, but no arguments:
int getNumber() {
int num = 10;
return num;
d) No return type, no arguments:
void greet() {
printf("Hello!\n");
7. Call by Value
Definition:
Passing copies of actual arguments to functions.
Example:
void modify(int x) {
x = 10;
int main() {
int a = 5;
modify(a);
printf("%d", a); // Output: 5
return 0;
8. Call by Reference
Definition:
Passing the address of arguments to functions.
Example:
void modify(int *x) {
*x = 10;
int main() {
int a = 5;
modify(&a);
printf("%d", a); // Output: 10
return 0;
9. Difference between Call by Value and Call by Reference
| Feature | Call by Value | Call by Reference |
|---------------------|----------------------------|-------------------------------|
| Argument Passed | Copy of actual value | Address of actual variable |
| Modifies Original? | No | Yes |
| Memory Usage | More | Less |
| Syntax | func(var); | func(&var); func(type *ptr) |
| Example Output | Value unchanged | Value changed |