Write a C++ program that Accept 5 digits number from the user then display following option. No=12345 Result =15
Write a C++ program that Accept 5 digits no from the user then display following option.
No=12345
Result =15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int number, sum = 0; cout << "Enter a 5-digit number: "; cin >> number; // Extracting each digit without a loop int digit5 = number % 10; int digit4 = (number / 10) % 10; int digit3 = (number / 100) % 10; int digit2 = (number / 1000) % 10; int digit1 = number / 10000; sum = digit1 + digit2 + digit3 + digit4 + digit5; cout << "Result = " << sum << endl; return 0; } |
Output
Enter a 5-digit number: 23575
Result = 22
Write a C++ program with loop that Accept 5 digits no from the user then display following option.
No=12345
Result =15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int number, digit, sum = 0; cout << "Enter a 5-digit number: "; cin >> number; // Loop to extract digits and calculate the sum for (int i = 0; i < 5; ++i) { digit = number % 10; // Extract the rightmost digit sum += digit; // Add the digit to the sum number /= 10; // Remove the rightmost digit } cout << "Result = " << sum << endl; return 0; } |
Output
Enter a 5-digit number: 45612
Result = 18