0
For loop help
Hi again...another question I’m stumped on. 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 Hint: Counter should start at 1 // question already has this typed out Int N= Convert.ToInt32(Console.ReadLine()); Int sum = 0; /* then further down it is typed Console.WriteLine(sum); */ // what I have typed For (sum = 0; sum > N; sum ++) { Console.WriteLine(sum); } Any help would be greatly appreciated. Thank you
4 Respuestas
+ 3
without for loop:
int N= Convert.ToInt32(Console.ReadLine());
Console.WriteLine(N(N+1)/2);
with for loop:
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;
for(int i = 0; i <= N; i++)
{
sum += i;
}
Console.WriteLine(sum);
}
}
}
+ 2
int sum = 0;
for(int i = 0; i <= N; i++)
{
sum += i;
}
the for loop will run until i <= N is true and each time we are adding i to sum and incrementing i by 1.
for example if N = 4
i = 0
sum = sum + i
= 0 + 0
= 0
i++
i = 1
sum = sum + i
= 0 + 1
= 1
i++
i = 2
sum = sum + i
= 1 + 2
= 3
i++
i = 3
sum = sum + i
= 3 + 3
= 6
i++
i = 4
sum = sum + i
= 6 + 4
= 10
i++
i=5 which makes our i<=N(5<=4) condition false and therefore the for loop stops executing
so our final sum value is 10.
+ 1
RKK thank you!!!!!! :)
0
RKK thank you for the help ! it’s much appreciated,would you mind explaining how that for loop worked?