Hi need some help with the summing of this simple problem. Seems that it doesn't save on the arrays.
Here is the code:
using System;
namespace test
{
class Program
{
static void Main()
{
Program p = new Program();
p.sum(1000);
Console.ReadLine();
}
public void sum (int tal)
{
for (int i = 1; i < tal; i++)
{
int[] array= new int[1000];
if (i % 3 == 0 || i % 5 == 0)
{
array[i] += i;
Console.WriteLine(array[i]);
}
}
}
}
}
Can someone give me the guidance to complete this one!?
Best regards,
Loading
Datta KharadPosted Dec 7, 2011, 8:12 AM
Declare array outside the for loop and get another variable total for sum...
You can display each number which is meet your condition i,e multiple of 3 or 5 and Lastly display Sum of these numbers. Use this code:-
using System;
namespace test
{
class Program
{
static void Main()
{
Program p = new Program();
p.sum(1000);
Console.ReadLine();
}
public void sum (int tal)
{
long total = 0;
int[] array= new int[1000]; //It does save in Array..(Here your problem get solved)
for (int i = 1; i < tal; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
array[i] += i;
total = total + i;
Console.WriteLine(array[i]);
}
}
Console.WriteLine("Sum of multiple 3 or 5 below 1000= "+total);
}
}
}
Datta KharadPosted Dec 8, 2011, 12:56 AM
If your query resolved then mark as Correct Answer.
Zu Sung ParkPosted Dec 7, 2011, 10:37 AM
Zu Sung ParkPosted Dec 7, 2011, 10:37 AM
Armando PintoPosted Dec 7, 2011, 8:04 AM
Looking at your code I'm not sure of what you want to do...
If you want to get the total sum, you should maybe do something like this:
namespace test
{
class Program
{
static void Main(string[] args)
{
long totalSum = Sum(1000);
Console.WriteLine(string.Format("Total sum: {0}", totalSum));
Console.ReadLine();
}
public static long Sum(int tal)
{
long total = 0;
for (int i = 1; i < tal; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
}
}
return total;
}
}