Reputation: 25
I am having an issue with trying to write a loop that requires me to multiply. What I am trying to do is write a loop that outputs:
i*3 for i = 10 t i = 4000
I tried using a counter method but it seems I am doing something wrong so i tried to fix it an did this
int i = 10;
for (i = 10; i < 4000; )
{
int r = i * 3;
Console.WriteLine(r);
but the number 30 goes into an infinite loop. Any help is appreciated, I am trying to do this for fun so I am self learning. Thanks again!
Upvotes: 2
Views: 5199
Reputation: 129
Try This.
E.g. Array : { 3, 30, 7, 8 }) Top 3 elements of this array is : 30 , 8 ,7 Output : 30 * 8 * 7 = 1680
Array : { 3, 30, 7, 8, -10, -20 }) Top 3 elements of this array is : 30 , 8 ,7 Output : 30 * 8 * 7 = 1680
static void Main(string[] args)
{
Console.WriteLine(MaxProduct(new int[] { 7,8,9,10,11,12,13}, 5));
Console.ReadKey();
}
static int MaxProduct(int[] arr, int no)
{
int prev = 0;
int count = 1;
// if (no >= 1)
{
Array.Sort(arr);
Array.Reverse(arr);
for (int i = 0; i < no-1 ; i++)
{
if (i == 0)
{
prev = arr[i] * arr[i + 1];
}
else
{
prev = prev * arr[count];
}
count++;
}
}
return prev;
}
Upvotes: 0
Reputation: 1
class Program
{
static void Main(string[] args)
{
for (int i = 10; i < 4000; i = i*3 )
{
Console.WriteLine(i);
}
}
}
Upvotes: 0
Reputation: 44288
You need an i++
for (i = 10; i < 4000; i++)
currently you have a for loop, but i
never changes
if you want your new requirement :-
var r = 10;
while(r < 4000)
{
r = r * 3;
Console.Writeline(r);
}
or
for (var r = 30; r < 4000; r = r * 3)
{
Console.WriteLine(r);
}
Upvotes: 6
Reputation: 6356
You're almost there (based on your comments)
int i = 10;
while (i < 4000)
{
int r = i * 3;
Console.WriteLine(r);
i = r;
}
If it has to be a for
loop:
for (int i = 10; i < 4000; )
{
int r = i * 3;
Console.WriteLine(r);
i = r;
}
Upvotes: 1
Reputation: 3294
is result of loop sum of you multiplication? you have two problems
you're not incrimenting i for (i = 10; i < 4000; i++)
you're not adding to r, declare it outside of loop, then r += i * 3;
Upvotes: 0