C#: Check a positive integer and return true if it contains a number 2
Check If Number Contains 2
Write a C# Sharp program to check a positive integer and return true if it contains a number 2.
Visual Presentation:
Sample Solution:
C# Sharp Code:
using System; // Importing the System namespace for basic functionality
using System.Collections; // Importing collections for non-generic interfaces
using System.Collections.Generic; // Importing collections for generic interfaces
using System.Linq; // Importing LINQ for querying collections
using System.Text; // Importing classes for handling strings
using System.Threading.Tasks; // Importing classes for handling asynchronous tasks
namespace exercises // Defining a namespace called 'exercises'
{
class Program // Defining a class named 'Program'
{
static void Main(string[] args) // The entry point of the program
{
// Output the result of the 'test' method with different integer values
Console.WriteLine(test(123));
Console.WriteLine(test(13));
Console.WriteLine(test(222));
}
// Method to check if an integer contains the digit '2'
public static bool test(int n)
{
while (n > 0) // Loop through each digit of the input integer 'n'
{
if (n % 10 == 2) return true; // Check if the last digit is equal to '2'
n /= 10; // Remove the last digit by dividing 'n' by 10
}
return false; // Return false if '2' is not found in 'n'
}
}
}
Sample Output:
True False True
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to create a new array from a given array of strings using all the strings whose length are matched with given string length.
Next: Write a C# Sharp program to create a new array of given length using the odd numbers from a given array of positive integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics