-2

I'm kinda new to c# and I'm doing some projects on my own. In this project I need to find the values of the arithmetic a + (a + b) + (a + 2b) and so on. Then I need to add all the answers together. I have the first part done but I'm unsure how to add all the values I get from the loop.

class Program
{
    static void Main(string[] args)
    {
        int a = 22;
        int b = 8;
        int answer;

        Console.WriteLine(a);

        for (int i = 1; i <= 43; i++)
        {
            answer = a + b * i;
            Console.WriteLine(answer);                
        }
    }
}
  • https://stackoverflow.com/questions/2817848/find-pythagorean-triplet-for-which-a-b-c-1000 – nikunjM Apr 03 '18 at 22:09
  • 1
    be careful of how you are adding and multiplying those numbers. a + b * i is the same as a + (b * i). You may come up with a different answer than expected – Kevbo Apr 03 '18 at 22:27

3 Answers3

1

You need to accumulate the answer is some way. You can do that be defining another variable to hold the summation. If the loop is many iterations you may have to worry about overflow.

int total; 
for (int i = 1; i <= 43; i++)
{
        answer = a + b * i;
        total += answer;
        Console.WriteLine(answer);                
}
rerun
  • 25,014
  • 6
  • 48
  • 78
  • You have to give `total` an initial value, e.g. 0. Otherwise, the compiler will complain about you using an unassign local variable. – Ian H. Apr 03 '18 at 22:11
  • I forgot about +=. I was trying to put all the values in an array then find the sum of an array and it was just getting overly complicated XD thank you so much – Badger Hart Apr 03 '18 at 22:16
0
  1. Start with i=0
  2. Use += operator for answer.
  3. Consider Sum extension method from System.Linq
Gena Verdel
  • 588
  • 5
  • 21
0

Using Linq you can use the Enumerable.Range() method to get a list of integers, then you can sum them.

var total = Enumerable.Range(1, 43).Sum();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150