HI WELCOME TO SIRIS
Showing posts with label c# interview programs. Show all posts
Showing posts with label c# interview programs. Show all posts

How to get the total number of decimal places using c#

Leave a Comment
For example, please refer to the sample input and output below. 
InputOutput
10
1.00
1.11
1.122
1.1233
1.11002
1.0102
1.001100 4              


using System;namespace SampleProgram{    class MainProgram    {        public static void Main(string[] args)        {            // Create the decimal array for sample test data            decimal[] decimalNumbers = { 1, 1.0M, 1.1M, 1.12M, 1.123M, 1.1100M,                                                                  1.010M, 1.001100M };
            // Loop thru each decimal number            foreach (decimal decimalNumber in decimalNumbers)            {                // Print the original number and total decimal places                Console.WriteLine("Original Decimal Number = {0}, Total Decimal Places = {1}",                    decimalNumber, GetDecimalPartCount(decimalNumber));            }        }        // Function that return the total decimal places        private static int GetDecimalPartCount(decimal decimalNumber)        {            // Dividing decimal number with 1 gives the decimal part            decimal decimalPlaces = decimalNumber % 1;            if (decimalPlaces != 0)            {                // Get the index of dot from the decimal part                int indexOfDot = decimalPlaces.ToString().IndexOf('.');                // Use the 0.######## format string to rip off trailing zeros, and get the count                int numberOfDecimals =                decimalPlaces.ToString("0.##########").Substring(indexOfDot).Length - 1;
                return numberOfDecimals;            }            // Finally convert decimal to int and return            return (int)decimalPlaces;        }    }}

C# Program to compute factorial of a number

Leave a Comment
In mathematics, 5 factorial is computed as 5X4X3X2X1, which is equal to 120. 5 factorial is denoted as 5 and an exclamation mark as shown below.
5 Factorial = 5! = 5X4X3X2X1 = 120 
4 Factorial = 4! = 4X3X2X1 = 24
3 Factorial = 3! = 3X2X1 = 6

Factorial of Zero is 1.

C# Program below shows how to compute factorial for a given number.

using System;
namespace SamplePrograms
{
    class Factorial
    {
        public static void Main()
        {
            // Prompt the user to enter their target number to calculate factorial
            Console.WriteLine("Please enter the number for which you want to compute factorial");


            try
            {
                // Read the input from console and convert to integer data type
                int iTargetNumber = Convert.ToInt32(Console.ReadLine());


                // Factorial of Zero is 1
                if (iTargetNumber == 0)
                {
                    Console.WriteLine("Factorial of Zero = 1");
                }
                // Compute factorial only for non negative numbers
                else if (iTargetNumber < 0)
                {
                    Console.WriteLine("Please enter a positive number greater than 1");
                }
                // If the number is non zero and non negative
                else
                {
                    // Declare a variable to hold the factorial result.
                    double dFactorialResult = 1;


                    // Use for loop to calcualte factorial of the target number
                    for (int i = iTargetNumber; i >= 1; i--)
                    {
                        dFactorialResult = dFactorialResult * i;
                    }


                    // Output the result to the console
                    Console.WriteLine("Factorial of {0} = {1}", iTargetNumber, dFactorialResult);
                }
            }
            catch (FormatException)
            {
                // We get format exception if user enters a word instead of number
                Console.WriteLine("Please enter a valid number"Int32.MaxValue);
            }
            catch (OverflowException)
            {
                // We get overflow exception if user enters a very big number, 
                // which a variable of type Int32 cannot hold
                Console.WriteLine("Please enter a number between 1 and {0}"Int32.MaxValue);
            }
            catch (Exception)
            {
                // Any other unforeseen error
                Console.WriteLine("There is a problem! Please try later");
            }
        }
    }
}

Find smallest and largest number in an integer array

Leave a Comment
I want a c# program that can find and print, the smallest and largest number in a given integer array.

using System;using System.Linq;

namespace SamplePrograms{    class LargestSmallest    {        public static void Main()        {            // Declare and initialize the integer array            int[] NumbersArray = { 102, 34, 89, 12, 187, 29, 111};                        // Sort the array, first element in the array will be            // smallest and the last element will be largest            Array.Sort(NumbersArray);

            // Print the smallest number in the array            Console.WriteLine("Samllest Number = {0}", NumbersArray[0]);

            // Print the largest number in the array.            Console.WriteLine("Largest Number = {0}", NumbersArray[NumbersArray.Length -1]);

            // Linq makes this much easier, as we have Min() and Max() extension methods            // Console.WriteLine("Samllest Number = {0}", NumbersArray.Min());            // Console.WriteLine("Largest Number = {0}", NumbersArray.Max());

        }    }}

Exception handling at its best

Leave a Comment
Write a c# program to add two numbers. This may sound very simple, but the catch, is - The program should not break, and always should give meaningful error messages when exception conditions occur. For example, the following error conditions should be handled in your program. Also, the program should run as long as the user wants it to run.
1. If the user enters "Ten" instead of 10, the program should let the user know only numbers can be added.
2. If the user, enters a very large number, the program should let the user know about the range allowed.

using System;


namespace SamplePrograms
{
    class ExceptionHandlingAtItsBest
    {
        public static void Main()
        {
            string strUserChoice = String.Empty;
            do
            {
                try
                {
                    Console.WriteLine("Please enter first number");
                    int FN = Convert.ToInt32(Console.ReadLine());


                    Console.WriteLine("Please enter second number");
                    int SN = Convert.ToInt32(Console.ReadLine());


                    int Total = FN + SN;


                    Console.WriteLine("Total = {0}", Total);
                }
                catch (FormatException)
                {
                    Console.WriteLine("Invalid Input. Only numbers please.");
                }
                catch (OverflowException)
                {
                    Console.WriteLine("Only numbers between {0} and {1} are allowed"
                        Int32.MinValue, Int32.MaxValue);
                }
                catch (Exception)
                {
                    Console.WriteLine("Unknown problem, please contact administrator");
                }


                do
                {
                    Console.WriteLine("Do you want to continue - Yes or No");
                    strUserChoice = Console.ReadLine();
                } 
                while (strUserChoice.ToUpper() != "YES" && strUserChoice.ToUpper() != "NO");
            } 
            while (strUserChoice.ToUpper() != "NO");
        }
    }
}

Insert space before every upper case letter in a string

Leave a Comment
Write a c# program that inserts a single space before every upper case letter. For example, if I have string like "ProductUnitPrice", the program should convert it to "Product Unit Price". Usually database column names will not have spaces, but when you display them to the user, it makes sense to have spaces.



using System;
using System.Text;


namespace SamplePrograms
{
    class SpaceBeforeUpperCaseLetter
    {
        public static void Main()
        {
            // Prompt the user for input
            Console.WriteLine("Please enter your string");
            
            // Read the input from the console
            string UserInput = Console.ReadLine();


            // Convert the input string into character array
            char[] arrUserInput = UserInput.ToCharArray();


            // Initialize a string builder object for the output
            StringBuilder sbOutPut = new StringBuilder();


            // Loop thru each character in the string array
            foreach (char character in arrUserInput)
            {
                // If the character is in uppercase
                if (char.IsUpper(character))
                {
                    // Append space
                    sbOutPut.Append(" ");
                }
                // Append every charcter to reform the output
                sbOutPut.Append(character);
            }
            // Remove the space at the begining of the string
            sbOutPut.Remove(0, 1);


            // Print the output
            Console.WriteLine(sbOutPut.ToString());


            Console.ReadLine();
        }
    }
}

C# program to remove duplicates

Leave a Comment
Write a c# program to print unique names, by removing the duplicate entries. For example, in the Input String below, Rob and Able names are repeated twice. The c# program that you write should remove the duplicates and return the string as shown in Output String. The output string contains each name only once, eliminating duplicates.


Input String    = "Rob;Mike;Able;Sara;Rob;Peter;Able;"
Output String = "Rob;Mike;Able;Sara;Peter;"

using System;
using System.Linq;
using System.Text;


namespace SamplePrograms
{
    class PrintUniqueNames
    {
        public static void Main()
        {
            // Prompt the user to enter the list of user names
            Console.WriteLine("Please enter list of names seperated by semi colon");


            // Read the user name list from the console
            string strUserNames = Console.ReadLine();


            // Sampe list of user names that can be used as an input
            // strUserNames = "Rob;Mike;Able;Sara;Rob;Peter;Able";


            // Split the string into a string array based on semi colon
            string[] arrUsersNames = strUserNames.Split(';');


            // Use the Distinct() LINQ function to remove duplicates
            string[] arrUniqueNames = arrUsersNames.Distinct().ToArray();


            // Using StringBuilder to concatenate strings is more efficient
            // than using immutable string objects for better performance
            StringBuilder sbUniqueUsernames = new StringBuilder();


            // Build the string from unique names appending semi colon
            foreach (string strName in arrUniqueNames)
            {
                sbUniqueUsernames.Append(strName + ";");
            }


            // Remove the extra semi colon in the end
            sbUniqueUsernames.Remove(sbUniqueUsernames.ToString().LastIndexOf(';'), 1);


            // Finally print the unique names
            Console.WriteLine();
            Console.WriteLine("Printing names without duplicates");
            Console.WriteLine(sbUniqueUsernames.ToString());
        }
    }
}

C# program to sort names in ascending and descending order

Leave a Comment
I have a string of user names seperated by semi colon. I want a c# program that can sort these names in both ascending and descending order.


string strUserNames = "Rob;Mike;Able;Sara;Peter;John;Tom;Ben";


using System;

namespace SamplePrograms{    class SortNamesInAscendingAndDescendingOrder    {        public static void Main()        {            // Prompt the user to enter the list of user names            Console.WriteLine("Please enter list of names seperated by semi colon");                        // Read the user name list from the console            string strUserNames = Console.ReadLine();

            // Sampe list of user names that can be used as an input            // strUserNames = "Rob;Mike;Able;Sara;Peter;John;Tom;Ben";

            // Split the string into a string array based on semi colon            string[] arrUsersNames = strUserNames.Split(';');

            // Print the names before sorting using foreach loop            Console.WriteLine("Names before sorting");            foreach (string UserName in arrUsersNames)            {                Console.WriteLine(UserName);            }

            // Sort the elements in the array in ascending order            Array.Sort(arrUsersNames);

            // Print the elements of the array after sorting            Console.WriteLine("Names after sorting in ascending order");            foreach (string UserName in arrUsersNames)            {                Console.WriteLine(UserName);            }

            // Reverse the elements in the sorted array to get            // the elements in descending order            Array.Reverse(arrUsersNames);                        // Finally print the elements            Console.WriteLine("Names after sorting in descending order");            foreach (string UserName in arrUsersNames)            {                Console.WriteLine(UserName);            }

            Console.ReadLine();        }    }}