vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool current = false;
int j;
Console.WriteLine("Enter any integer");
int num = Int32.Parse(Console.ReadLine());
for (int i = 2; i <= num; i++)//2 is the first prime number.
//I set i to 2 beacuse it has to print 2 firstly...
{
for (j = 2; j < i; j++)
{
if (i % j == 0)//Controls i is prime number or not...
{
current = true;
break;//breaks for not controlling anymore...
}
}
if (current == false)
Console.Write("{0} ", j);//if i is prime number, print it...
else
current = false;
}
Console.ReadLine();
}
}
}
FoX_
Junior Poster in Training
53 posts since Mar 2007
Reputation Points: 10
Solved Threads: 7
Rhohitman
Junior Poster in Training
86 posts since Dec 2007
Reputation Points: 10
Solved Threads: 5
Any time you are having troubles with iterations like this (especially nested) your first step should be to run through it step by step and track each variable at each stage:
num = 9:
i j i%j output
3 2 1 3
3 3 0
3 4 3 3
4 2 0
4 3 1 4
4 4 0
5 2 1 5
5 3 2 5
5 4 1 5
6 2 0
6 3 0
6 4 2 6
This allows you to see exactly whats going on and why the results arent what you expect. I wont tell you how to rewrite your algorythm as there are plenty of examples already here, just thought i'd chip in with some advice on solving similar issues in the future.Give a man a solution, and his problem is solved for today; give him the tools to trouble shoot his work, and his problems are solved for a lifetime ;)
Ryshad
Nearly a Posting Virtuoso
1,307 posts since Aug 2009
Reputation Points: 512
Solved Threads: 246
@Ryshad
Yes, I do this also when confronted wih this kind of "problems".
Although these days I prefer the wonderfull debugger that comes with VS!
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
Welcome iajm,
I'm glad you found it useful. Have you noticed that the current thread is two years old? Please do not resurrect old/solved threads. If you want to ask question, start your own thread.
Read before posting- http://www.daniweb.com/forums/thread78223.html
__avd
Posting Genius (adatapost)
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241