C++ Exercises: Test a positive integer and return true if it contains the number 2
Check if Number Contains Digit '3'
Write a C++ program to check a positive integer and return true if it contains the number 3. Otherwise return false.
Test Data:
(143) -> 1
(678) -> 0
(963) -> 1
Sample Solution:
C++ Code :
#include <iostream>  // Including input-output stream header file
using namespace std;  // Using standard namespace
// Function to check if a given integer contains the digit 3
bool test(int n) {
    while (n > 0) {
        if (n % 10 == 3)  // Checking if the last digit of 'n' is 3
            return true;  // Returning true if 'n' contains the digit 3
        n /= 10;  // Removing the last digit of 'n' by integer division
    }
    return false;  // Returning false if 'n' does not contain the digit 3
}
// Main function
int main() {
    int n = 143;  // Initializing 'n' with an integer value
    cout << "Original number: " << n;  // Displaying the original number
    cout << "\nCheck the said integer contains 3? " << test(n);  // Checking if 'n' contains the digit 3
    n = 678;  // Changing the value of 'n' to a different integer
    cout << "\n\nOriginal number: " << n;  // Displaying the new original number
    cout << "\nCheck the said integer contains 3? " << test(n);  // Checking if 'n' contains the digit 3
    n = 963;  // Changing the value of 'n' to another integer
    cout << "\n\nOriginal number: " << n;  // Displaying the new original number
    cout << "\nCheck the said integer contains 3? " << test(n);  // Checking if 'n' contains the digit 3
    return 0;  // Returning 0 to indicate successful completion of the program
}
Sample Output:
Original number: 143 Check the said integer contains 3? 1 Original number: 678 Check the said integer contains 3? 0 Original number: 963 Check the said integer contains 3? 1
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to check if a positive integer contains the digit '3' in its decimal representation and output a boolean result.
 - Write a C++ program that reads an integer, converts it to a string, and searches for the character '3', returning true if found.
 - Write a C++ program to analyze a number and return 1 if any digit equals 3, otherwise return 0.
 - Write a C++ program that determines whether the digit '3' appears in an input number by iterating through its digits.
 
Go to:
PREV : Create Array with Strings of Given Length from String Array. 
NEXT : Create Array of Odd Numbers with Specific Length.
C++ Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
