I am taking a class teaching C# and we just learned about methods. I am very, very new at this. As an assignment, it says the following:
"Write a method ‘SumNum’ that accepts an integer parameter and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if you pass 20 as an argument, the method will return the sum of 1, 2, 3, 4,…20 which is 210."
I’ve been trying to come up with something but I can’t figure it out and I keep getting error messages. I know how to create a method but I don’t know how to do mathematical operations with a changing amount of integers.
This is all I’ve been able to come up with:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab6
{
internal class Program
{
static int SumNum(int num)
{
for (int i = 0; i <= num; i++)
{
return i;
}
}
static void Main(string[] args)
{
int Sum1 = SumNum(20);
Console.WriteLine(Sum1);
}
}
}
The error says "Not all code paths return a value."
>Solution :
You wrote "in SumNum method, return i inside the for loop".
This means that it won’t return the sum of integers from 1 up to your input parameter num because you never do the actual sum.
The error says:
Not all code paths return a value.
When the input parameter is less than zero in your code, program won’t go inside for-loop and won’t execute the return i; line. That error is shown because of that possible case.
You can try the code below:
static int SumNum(int num)
{
int sum = 0;
for (int i = 1; i <= num; i++)
{
sum += i;
}
return sum;
}