Theory
કયો box?
5 marks, એક નામ:
int marks[5] = {70, 55, 90, 62, 78};
marks[2] શું છે?
Think first
પહેલાં તમારો અંદાજ
તમારા મતે marks[2] માં જે value છે તે type કરો.
Show the answer
90. Boxes ની numbering 0 થી થાય છે: marks[0] 70 છે, marks[1] 55 છે, marks[2] 90 છે. 55 કહ્યું તો તમે 1 થી ગણ્યું.
Theory
Array declare કરવો
int marks[5]; એક નામ નીચે 5 int boxes reserve કરે છે, અને એનો size નક્કી રહે છે. int marks[5] = {70, 55}; બાકીના boxes ને 0 થી ભરે છે, અને int marks[] = {70, 55, 90}; માં compiler જાતે 3 ગણી લે છે. Valid indexes 0 થી n-1 સુધી ચાલે છે.
Practical
Topper શોધો
#include <stdio.h>
int main() {
int marks[5] = {70, 55, 90, 62, 78};
int i, top = marks[0];
for (i = 1; i < 5; i++) {
if (marks[i] > top)
top = marks[i];
}
printf("Topper: %d\n", top);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Think first
Trace કરો
ઉપરનો program શું print કરે છે, અને loop i = 1 થી કેમ શરૂ થાય છે?
Show the answer
Topper: 90. top માં પહેલેથી marks[0] છે, એટલે loop ફક્ત boxes 1 થી 4 ની સરખામણી કરે છે.
Theory
Text એ char array છે
String એ chars નો એક array છે જે એક છુપા null terminator, '\0', પર પૂરો થાય છે, અને એ જ બતાવે છે કે text ક્યાં અટકે છે. એટલે char name[10] = "Riya"; માં R, i, y, a, '\0' અને 5 ખાલી boxes હોય છે.
Quiz
char city[] = "Surat"; માટે compiler કેટલા boxes reserve કરે છે?
- 6: 5 letters અને '\0'
- 5: દરેક letter નો એક box
- એક પણ નહીં: ખાલી brackets error છે
- 6: 5 letters અને એક space
Show the answer
6: 5 letters અને '\0'
ખાલી brackets માં compiler જાતે ગણે છે, અને string પોતાનો '\0' સાથે લાવે છે: 5 letters + 1 = 6. Terminator ની value 0 છે, એ space નથી.
Watch out
Bounds ની બહાર
5 boxes વાળા array માં marks[5] હોતો જ નથી, છતાં code compile થઈને ચાલે છે અને એવી memory વાંચે કે બદલી નાખે છે જે તમારી નથી. C ક્યારેય array bounds ચકાસતું નથી.
Practical
Exam-style: output કહો
#include <stdio.h>
int main() {
int a[5] = {3, 1};
printf("%d %d", a[1], a[4]);
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: ઉપરના program નું output શું છે?
- 1 0
- 3 0
- 1 1
- 1 અને પછી એક garbage value
Show the answer
1 0
a[1] બીજી value છે, 1. બાકીની values 0 થી ભરાઈ જાય છે, એટલે a[4] 0 છે. જવાબ 3 0 1 થી ગણે છે.
Summary
Key takeaways
- Array: એક નામ, એક type ના n boxes, નક્કી size.
- Indexes 0 થી n-1 સુધી ચાલે છે.
- અધૂરી list બાકીના boxes ને 0 થી ભરે છે; string ને '\0' માટે એક વધારાનો box જોઈએ.
- યાદ રાખવાની યુક્તિ: 0 થી ગણો, terminator માટે જગ્યા રાખો.