0
How to solve this exercise? And explanation
The program you are given takes a positive number N as input. Complete the program to calculate the sum of all numbers from 1 to N inclusive. Sample Input 4 Sample Output 10 IN C# https://www.sololearn.com/discuss/2669866/?ref=app
5 Respostas
+ 4
Carlos
This is so simple. Just start loop with index 1 and add index values.
int sum = 0;
for(int i = 1; i <= N; i++) {
sum += i;
}
+ 2
i is simple a new variable/counter for the for loop.
for (init; condition; increment)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int N = Convert.ToInt32(Console.ReadLine());
int sum = 0;
//your code goes here
for (int x = 1; x <= N; x++ )
{
sum = sum + x;
}
Console.WriteLine(sum);
}
}
}
0
thanks for the reply, just one question, its “i” and arbitrary name or when do you ise it?
0
Wow, how simple is that! I've been wondering too much on this...
0
I've managed to solve it too!
It was kinda rough though!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
int sum = 0;
//your code goes here
for(int x = 1; x <= N; x++)
{
sum += x;
}
Console.WriteLine(sum);
}
}
}