Conditions, Loops और switch
एक छोटे program में branches और loops जोड़ें।
Conditions, Loops और switch क्या है?
if condition से चुनता है, switch discrete cases संभालता है और loop block दोहराता है।
महत्वपूर्ण बातें
- Compiler warnings चालू करके सभी ठीक करें।
- हर value का type और lifetime समझें।
- Input और array bounds validate करें।
देखें यह कैसे काम करता है
अंक बदलने के लिए स्लाइडर खिसकाएँ। फ़्लोचार्ट में वह रास्ता चमकता है जिस पर प्रोग्राम चलता है, और कोड की संबंधित पंक्ति हाइलाइट होती है।
C और C++ code examples
#include <stdio.h>
int main(void) {
int scores[] = {92, 71, 84};
int total = 0;
for (int i = 0; i < 3; ++i) total += scores[i];
int average = total / 3;
switch (average / 10) {
case 10: case 9: puts("Grade A"); break;
case 8: puts("Grade B"); break;
default: puts("Keep practicing");
}
return 0;
}
Grade B
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores{92, 71, 84};
int total = 0;
for (int score : scores) total += score;
switch ((total / static_cast<int>(scores.size())) / 10) {
case 10: case 9: std::cout << "Grade A\n"; break;
case 8: std::cout << "Grade B\n"; break;
default: std::cout << "Keep practicing\n";
}
}
Grade B
C और C++ की तुलना
Syntax लगभग समान है। Braces उपयोग करें, accidental fall-through रोकें और index को array bounds में रखें।
C छोटे procedural APIs और representation details स्पष्ट करता है।
C++ low-level model रखकर safer library types जोड़ता है।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Invalid और boundary inputs जोड़ें।
- -Wall -Wextra -Wpedantic से compile करें।
- Declarations और implementation अलग करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Letter Grade Turn a test score into a letter grade. आसान
- फिज़ बज़ 3 और 5 से विभाज्यता का उपयोग करके एक अनुक्रम बनाएँ। आसान
- Triangle Classification Classify three side lengths as invalid, equilateral, isosceles, or scalene. आसान