Simple Example on "For" loop and "If" condition

by Jagadish Pulakhandam on 10/18/2011 8:38:44 AM
Rated 0 from 0 votes
Brief: Demonstrates on finding prime numbers below 100 using a couple of "For" loops and "If" conditions
Posted to: Basics of .NET Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

The sample demonstrates the following:
  • How to use "For" loops in C#
  • How to use "If" conditions in C#
  • How to find Prime numbers below 100 using C#
Source Code:
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.namespace PrimeNumbers
07.{
08.    class Program
09.    {
10.        static void Main(string[] args)
11.        {
12.            //displays all primes below 100
13.            for (int i = 0; i <= 100; i++)
14.            {
15.                if (isPrime(i)) Console.WriteLine(i);
16.            }
17.            //wait for enter key
18.            Console.ReadLine();
19.        }
20. 
21.        static bool isPrime(int n)
22.        {
23.            bool b = true;
24.            //1 is always a factor for every number (we start with 2)
25.            //there can never be a factor of a number which is above the half of the number.
26.            //ex:for a number 200, the highest factor is 100 (which is just half of 200).
27.            for (int i = 2; i <= (n/2); i++)
28.            {
29.                //if a factor is found for 'n', it is no longer a prime
30.                if ((n % i) == 0)
31.                {
32.                    b = false;
33.                    break;
34.                }
35.            }
36.            return b;
37.        }
38.    }
39.}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following