1

I'm trying to modify the code below so each first number in column is based on the row number.

int i, sum = 0;

for (int row = 0; row < 7;  row++)
{
    for (i = 1; i < 6; i++)
    {
        sum = sum + i;
        Console.Write("{0} ", i);
    }

    Console.WriteLine(sum);
    sum = 0;                
}

Console.Read();

presents this in console:

1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15
1 2 3 4 5 15

But I'm trying get like this:

1 2 3 4 5 sum
2 3 4 5 6 sum
3 4 5 6 7 sum
4 5 6 7 8 sum
and so on..
......
....

Any idea on how to solve this?

1
  • 2
    Hint: you're starting each row, in your inner loop, with i = 1. Maybe that's something you can change? Commented Apr 5, 2018 at 19:31

3 Answers 3

7

Change the inner loop to be

for (int i = row + 1; i < row + 6; i++)
Sign up to request clarification or add additional context in comments.

Comments

1

Replace

sum = sum + i;
Console.Write("{0} ", i);

enter code here

with

number = number + row
sum = sum + number;
Console.Write("{0} ", number);

This way you use the variable row to keep track of the starting number for the row.

Comments

0

If you don't need the console statements and just the sum, you can just use no inner loop and:

sum = Enumerable.Sum(Enumerable.Range(row+1, 5));

It's LINQ

or, if you need the console statement:

Enumerable.Range(row+1, 5).ToList().ForEach(c => sum += c; Console.Write(c));

4 Comments

Suggesting LINQ and lambdas to a brand new programmer? They're still trying to grok for-loops.
i think the point should be considered that most of us began programming in an environment where those concepts didnt exist...there might be a time where someone considers these concepts synonymous instead of a step up @DavidMakogon
Point being, they had the start point of the loop incorrect. Your solution was a complete departure from their code, dove into enumerables, linq, lambda. This in no way corrects their code. It's a rewrite. Might be an obvious solution for a seasoned developer. But the answer is not in line with their question and level of competence in c#. It's great that you can provide such a succinct answer; just that it's out of context for this question.
An old school mentality like that will definitely mean you select an rb at 2...go iggles

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.