Find the Second Largest Value
यह शुरुआती exercise Find the Second Largest Value के जरिए core syntax और problem solving का अभ्यास कराती है।
Find the Second Largest Value क्या है?
यह शुरुआती exercise Find the Second Largest Value के जरिए core syntax और problem solving का अभ्यास कराती है।
Find the Second Largest Value को C और C++ दोनों में runnable code से हल करें।
महत्वपूर्ण बातें
- Compiler warnings चालू करके सभी ठीक करें।
- हर value का type और lifetime समझें।
- Input और array bounds validate करें।
C और C++ code examples
main.c
#include <limits.h>
#include <stdio.h>
int main(void) {
int values[] = {7, 23, 12, 23, 9}, first = INT_MIN, second = INT_MIN;
// Maintain the two largest distinct values.
for (int i = 0; i < 5; ++i) { int value = values[i]; if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
printf("second=%d\n", second);
}
second=12
C++
main.cpp
#include <iostream>
#include <limits>
#include <vector>
int main() {
std::vector values{7, 23, 12, 23, 9}; int first = std::numeric_limits<int>::min(), second = first;
// Maintain the two largest distinct values.
for (int value : values) { if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
std::cout << "second=" << second << '\n';
}
second=12
C और C++ की तुलना
C और C++ implementations की तुलना करें, input बदलें और अतिरिक्त edge cases test करें।
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 अलग करें।