Reputation: 19
This is Code I reached. What I don't understand is how do I put a condition to display the first 20 numbers where I wrote the condition for i
to be less than 20. I know that my code is completely wrong.
for(int i=1; i<=20; i++)
{
if(i%7==0)
{
Console.WriteLine(i);
}
}
Upvotes: 0
Views: 1311
Reputation: 76
You can try bellow code that will give you first 20 numbers that will covered the condition i%7==0 ........
public static void Main(string[] args)
{
int i=0, count = 0;
while(count < 20)
{
if (i % 7 == 0)
{
Console.WriteLine("Position {0} number is = {1}", count+1, i,"\n");
count++;
}
i++;
}
Console.ReadKey();
}
Upvotes: 0
Reputation: 56453
You're close. use a counter variable:
int counter = 0; // counter variable
for(int i=1; ; i++) // removed condition
{
if (counter > 20) break; // time to stop the iteration
if(i%7==0)
{
counter++;
Console.WriteLine(i);
}
}
This can be improved to:
for(int i = 7, counter = 0; counter <= 20; i += 7)
{
Console.WriteLine(i);
counter++;
}
Upvotes: 2
Reputation: 10350
Can’t you just go up in sevens?
for (int multiple = 7, int count = 0; count < 20; multiple += 7, count++)
{
Console.WriteLine(multiple);
}
Upvotes: 1
Reputation: 26501
The first 20 integers that are divisible by 7 are easily written as 7,2*7,3*7,4*7,...,20*7
. This in your loop you can do:
for(int i = 1; i<=20; i++) {
Console.WriteLine(7*i);
}
Upvotes: 1