फ़िबोनाची अनुक्रम
पहली दस फ़िबोनाची संख्याएँ बनाएँ।
फ़िबोनाची अनुक्रम क्या है?
हर फ़िबोनाची संख्या अपने से पहले की दो संख्याओं का योग है।
महत्वपूर्ण बातें
- Compiler warnings चालू करके सभी ठीक करें।
- हर value का type और lifetime समझें।
- Input और array bounds validate करें।
C और C++ code examples
main.c
#include <stdio.h>
int main(void) {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
printf("%s%d", i ? " " : "", first);
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
puts("");
}
0 1 1 2 3 5 8 13 21 34
C++
main.cpp
#include <iostream>
int main() {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
if (i) std::cout << ' ';
std::cout << first;
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
std::cout << '\n';
}
0 1 1 2 3 5 8 13 21 34
C और C++ की तुलना
दो स्टेट वेरिएबल काफ़ी हैं, क्योंकि हर चक्कर में सिर्फ़ पिछली जोड़ी चाहिए।
C
C छोटे procedural APIs और representation details स्पष्ट करता है।
C++
C++ low-level model रखकर safer library types जोड़ता है।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Invalid और boundary inputs जोड़ें।
- -Wall -Wextra -Wpedantic से compile करें।
- Declarations और implementation अलग करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज