Introduction
जब हम arrays का उपयोग करते हैं, तो अक्सर हमें उन arrays पर operations करने होते हैं, जैसे:
- sum निकालना
- maximum/minimum find करना
- elements print करना
- sorting या searching करना
अगर हम ये सारे operations main() के अंदर ही करेंगे, तो program लंबा और complex हो जाएगा।
इसीलिए हम functions का उपयोग करते हैं और array को function में भेजते हैं ताकि:
- code reusable बने
- program modular बने
- logic अलग-अलग हिस्सों में divide हो
जब हम array को function में pass करते हैं, तो पूरा array नहीं बल्कि उसका address (base address) pass होता है।
इसलिए function original array पर ही काम करता है।
Definition
Passing Arrays to Functions का मतलब है array को function के parameter के रूप में भेजना ताकि function उस array के elements को process कर सके।
Important Concept
Array हमेशा call by reference की तरह behave करता है
- array का address pass होता है
- original array modify हो सकता है
Syntax
function_name(array_name, size);
Function definition:
return_type function_name(int arr[], int size)
{
// processing
}
Example 1: Array Elements Print करना
#include <stdio.h>
void display(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int a[5] = {1, 2, 3, 4, 5};
display(a, 5);
return 0;
}
Output:
1 2 3 4 5
Explanation:
- array function में pass हुआ
- function ने elements print किए
Example 2: Sum of Array Elements
#include <stdio.h>
int sum(int arr[], int n)
{
int i, s = 0;
for (i = 0; i < n; i++)
{
s = s + arr[i];
} return s;
}
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int result = sum(a, 5);
printf("Sum = %d", result);
return 0;
}
Output:
Sum = 15
Explanation:
- function ने array के elements add किए
- result return किया
Example 3: Array Modify करना
#include <stdio.h>
void modify(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
{
arr[i] = arr[i] * 2;
}
}
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int i;
modify(a, 5);
for (i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output:
2 4 6 8 10
Explanation:
- function ने original array को modify किया
- क्योंकि address pass हुआ था
Example 4: Find Maximum Element
#include <stdio.h>
int max(int arr[], int n)
{
int i, m = arr[0];
for (i = 1; i < n; i++)
{
if (arr[i] > m)
{
m = arr[i];
}
} return m;
}
int main()
{
int a[5] = {10, 25, 5, 40, 15};
printf("Max = %d", max(a, 5));
return 0;
}
Output:
Max = 40
Explanation:
- function ने array में largest value find की
Technical Understanding
- array pass करने पर उसका base address जाता है
- इसलिए memory copy नहीं बनती
- original data पर operation होता है
- performance better होती है
Difference: Normal Variable vs Array Passing
| Normal Variable | Array |
|---|---|
| Value pass होती है | Address pass होता है |
| Original change नहीं होता | Original change हो सकता है |
Exam Points
- Array processing programs बहुत important हैं
- Array function में pass किया जा सकता है
- Array हमेशा reference की तरह behave करता है
- Function original array को modify कर सकता है
- Size parameter pass करना जरूरी होता है