C/C++ की मूल बातें

Conditions, Loops और switch

if condition से चुनता है, switch discrete cases संभालता है और loop block दोहराता है।

Conditions, Loops और switch क्या है?

if condition से चुनता है, switch discrete cases संभालता है और loop block दोहराता है।

एक छोटे program में branches और loops जोड़ें।

महत्वपूर्ण बातें

  • Compiler warnings चालू करके सभी ठीक करें।
  • हर value का type और lifetime समझें।
  • Input और array bounds validate करें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#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;
}
अपेक्षित output
Grade B
C++
कोड चलाएँ →
main.cpp
#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";
    }
}
अपेक्षित output
Grade B

C और C++ की तुलना

Syntax लगभग समान है। Braces उपयोग करें, accidental fall-through रोकें और index को array bounds में रखें।

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 अलग करें।