Showing posts with label NET World. Show all posts
Showing posts with label NET World. Show all posts

CSharp (C#) finding the count of factors and factors of a given number using out parameter

Find the number of factors (count of factors) and the actual factors of a given number

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {           
            int numoffact = 0;
            FindingFactors ff = new FindingFactors();                       
         Console.Write("Enter the number to which factors are needed : ");
            int num = Convert.ToInt32(Console.ReadLine());
            if (num <= 0)
            {
                Console.WriteLine("The number should be 1 or above. Exiting...");
                Console.ReadLine();
                return;
            }
            int[] allfactors = ff.factors(num, out numoffact);
            Console.WriteLine("The number of factors are : " + numoffact);
            Console.Write("The factors are : ");
            for (int i = 0; i < numoffact; i++)
            {
                Console.Write(allfactors[i] + " ");
            }
            Console.ReadLine();
        }
    }
   
    class FindingFactors
    {
        public int[] factors(int number, out int numberoffactors)
        {
            numberoffactors = 0;
            int[] fact = new int[100];
            int j = 0; //This is for array count in fact
            for (int i = 1; i <= number; i++)
            {
                if (number % i == 0)
                {
                    fact[j] = i;
                    j = j + 1;
                    numberoffactors++;
                }
            }
           
            return fact;
        }
    }
   

}

Output :

CSharp (C#) params example for finding minimum number out of a given list

CSharp Params sample program for finding a minimum number out of a given list

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            paramsexample p = new paramsexample();
            int y = p.findmin(-1, 2, 3);
            Console.WriteLine(y);
            Console.ReadLine();
        }
    }
    class paramsexample
    {
        public int findmin(params int[] numbers)
        {
            int x = numbers[0];
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i] < x)
                    x = numbers[i];
            } 
            return x;
        }
    }

}