Sum of ONLY negative numbers - c#

C# Loops.
I need help with this question:
Write a program that reads 10 data from the keyboard and add only those that are negative.
I just started class in January an we're in C# loops. I haven't been in school for over 3 weeks now because of the coronavirus. So i'm kinda lost now and we just started online class so big rips to me:(
double sum = 0.0d;
double n = 0.0d;
for (int i = 1; i <= 10; i++)
{
Console.Write($"Enter a number {i}: ");
n = double.Parse(Console.ReadLine());
}
if (n < 0)
sum = n + n;
Console.WriteLine($"{sum}");
Here is my code (I'm probably 100% wrong but it's 2am rn and i'm trying);
Thanks! :)
Thank ya'll so much for the help!

Actually, you're closer than you think. You should adjust the sum inside the loop, and it should be adjusted by adding n to the current sum rather than setting it to n + n.
By adjusting after the loop is finished, you only take the last number in to account. And, by setting sum to n + n, the sum you end up with will just be twice the last number entered if it was negative, and zero if not.
In other words, something like:
double sum = 0.0d;
double n = 0.0d;
for (int i = 1; i <= 10; i++)
{
Console.Write($"Enter a number {i}: ");
n = double.Parse(Console.ReadLine());
if (n < 0)
sum = sum + n;
}
Console.WriteLine($"{sum}");

you are adding to sum outside of your loop ...
move that if into the loop after the assignment of n, add n to sum and not to n and you are good

One possibility to filter for negative numbers is Math.Min(Int,Int) which returns the Minimum of 2 numbers. In this case positive numbers are set to 0.
After each iteration your would do this:
sum = sum + Math.Min(0, InputNumber)
Or you can simply use an if clause:
if (InputNumber < 0) { sum = sum + InputNumber }
Note: Your need to add your numbers inside your loop, otherwise it would only be executed once.

Related

Sum range using loop, calculate sum of odd and even numbers

Hi I am sick of searching I could not find the exact code for my question.
I need to code the sum of the odd numbers from 1 to 100
and sum of the even numbers from 2 to 100.
This is what i have so far.
Thank you so much
// 1) using for statement to Sum Up a Range of values using Interactive
Console.WriteLine(" Sum Up a Range of values entered by User ");
Console.WriteLine();
// 2) Declare the Variables to be used in the Project
string strFromNumber, strToNumber;
int fromNumber, toNumber;
int sum = 0;
int i, even = 0, odd = 0;
int[] array = new int[10];
// 3) Prompt the User to Enter the From Number to Sum From
Console.Write("Enter the From Number to Sum From: ");
strFromNumber = Console.ReadLine();
fromNumber = Convert.ToInt32(strFromNumber);
// 4) Prompt the User to Enter the To Number to Sum To
Console.Write("Enter the To Number to Sum To: ");
strToNumber = Console.ReadLine();
toNumber = Convert.ToInt32(strToNumber);
// 5) Use for statement to Sum up the Range of Numbers
for (i = fromNumber; i <= toNumber; ++i)
{
sum += i;
}
if //(array[i] % 2 == 0) //here if condition to check number
{ // is divided by 2 or not
even = even + array[i]; //here sum of even numbers will be stored in even
}
else
{
odd = odd + array[i]; //here sum of odd numbers will be stored in odd.
}
Console.WriteLine("The Sum of Values from {0} till {1} = {2}",
fromNumber, toNumber, sum);
Console.ReadLine();
There is no need to write the complex code which you have written.
Problem is to calculate the sum of arithmetic progression. The formula to find the sum of an arithmetic progression is Sn = n/2[2a + (n − 1) × d] where, a = first term of arithmetic progression, n = number of terms in the arithmetic progression and d = common difference.
So in case of odd numbers its a = 1, n = 50 and d = 2
and in case of even numbers its a = 2, n = 50 and d = 2
and if you try to normalize these above formulas, it will be more easy based on your problem.
the sum of the first n odd numbers is Sn= n^2
the sum of the first n even numbers is n(n+1).
and obviously, it's very simple to loop from ( 1 to 99 with an increment of 2 ) and ( 2 to 100 with an increment of 2 )
In the simplest case, you can try looping in fromNumber .. toNumber range while adding
number either to even or to odd sum:
// long : since sum of int's can be large (beyond int.MaxValue) let's use long
long evenSum = 0;
long oddSum = 0;
for (int number = fromNumber; number <= toNumber; ++number) {
if (number % 2 == 0)
evenSum += number;
else
oddSum += number;
}
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
Note, that you can compute both sums in one go with a help of arithmetics progression:
private static (long even, long odd) ComputeSums(long from, long to) {
if (to < from)
return (0, 0); // Or throw ArgumentOutOfRangeException
long total = (to + from) * (to - from + 1) / 2;
from = from / 2 * 2 + 1;
to = (to + 1) / 2 * 2 - 1;
long odd = (to + from) / 2 * ((to - from) / 2 + 1);
return (total - odd, odd);
}
Then
(long evenSum, long oddSum) = ComputeSums(fromNumber, toNumber);
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
From the code snippet you shared, it seems like the user gives the range on which the sum is calculated. Adding to #vivek-nuna's answer,
Let's say the sum of the first N odd numbers is given by, f(n) = n^2 and
the sum of the first N even numbers is given by, g(n) = n(n + 1).
So the sum of odd numbers from (l, r) = f(r) - f(l - 1).
Similarly, the sum of even numbers from (l, r) = g(r) - g(l - 1).
Hope this helps.

C# WinsForm, Frequency Distribution Table [Updated]

Update 01
Thanks to Caius, found the main problem, the logic on the "if" was wrong, now fixed and giving the correct results. The loop still create more positions than needed on the secondary List, an extra position for each number on the main List.
I've updated the code bellow for refence for the following question:
-001 I can figure out why it create positions that needed, the for loop should run only after the foreach finishes its loops correct?
-002 To kind of solving this issue, I've used a List.Remove() to remove all the 0's, so far no crashes, but, the fact that I'm creating the extra indexes, and than removing them, does means a big performance down if I have large list of numbers? Or is an acceptable solution?
Description
It supposed to read all numbers in a central List1 (numberList), and count how many numbers are inside a certain (0|-15 / 15|-20) range, for that I use another List, that each range is a position on the List2 (numberSubList), where each number on List2, tells how many numbers exists inside that range.
-The range changes as the numbers grows or decrease
Code:
void Frequency()
{
int minNumb = numberList.Min();
int maxNumb = numberList.Max();
int size = numberList.Count();
numberSubList.Clear();
dGrdVFrequency.Rows.Clear();
dGrdVFrequency.Refresh();
double k = (1 + 3.3 * Math.Log10(size));
double h = (maxNumb - minNumb) / k;
lblH.Text = $"H: {Math.Round(h, 2)} / Rounded = {Math.Round(h / 5) * 5}";
lblK.Text = $"K: {Math.Round(k, 4)}";
if (h <= 5) { h = 5; }
else { h = Math.Round(h / 5) * 5; }
int counter = 1;
for (int i = 0; i < size; i++)
{
numberSubList.Add(0); // 001 HERE, creating more positions than needed, each per number.
foreach (int number in numberList)
{
if (number >= (h * i) + minNumb && number < (h * (i + 1)) + minNumb)
{
numberSubList[i] = counter++;
}
}
numberSubList.Remove(0); // 002-This to remove all the extra 0's that are created.
counter = 1;
}
txtBoxSubNum.Clear();
foreach (int number in numberSubList)
{
txtBoxSubNum.AppendText($"{number.ToString()} , ");
}
lblSubTotalIndex.Text = $"Total in List: {numberSubList.Count()}";
lblSubSumIndex.Text = $"Sum of List: {numberSubList.Sum()}";
int inc = 0;
int sum = 0;
foreach (int number in numberSubList)
{
sum = sum + number;
int n = dGrdVFrequency.Rows.Add();
dGrdVFrequency.Rows[n].Cells[0].Value = $"{(h * inc) + minNumb} |- {(h * (1 + inc)) + minNumb}";
dGrdVFrequency.Rows[n].Cells[1].Value = $"{number}";
dGrdVFrequency.Rows[n].Cells[2].Value = $"{sum}";
dGrdVFrequency.Rows[n].Cells[3].Value = $"{(number * 100) / size} %";
dGrdVFrequency.Rows[n].Cells[4].Value = $"{(sum * 100) / size} %";
inc++;
}
}
Screen shot showing the updated version.
I think, if your aim is to only store eg 17 in the "15 to 25" slot, this is wonky:
if (number <= (h * i) + minNumb) // Check if number is smaller than the range limit
Because it's found inside a loop that will move on to the next range, "25 to 35" and it only asks if the number 17 is less than the upper limit (and 17 is less than 35) so 17 is accorded to the 25-35 range too
FWIW the range a number should be in can be derived from the number, with (number - min) / number_of_ranges - at the moment you create your eg 10 ranges and then you visit each number 10 times looking to put it in a range, so you do 9 times more operations than you really need to

How to divide number on separate digits to add values to each other

can you help me figure out how to calculate this way, for example I have some integer:
first I need condition
if (x < 10) to avoid asked calculation for single numbers
now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.
So question is how to separate numbers
try
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
This isn't C# in particular, but you can loop over your number then get it digit by digit.
// -- c
int num = 134;
int sum = 0;
while(num != 0) {
ones_digit = num % 10;
sum += ones_digit;
num = (num - ones_digit) / 10;
}
printf("sum: %d", sum);
On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.
// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);

Project Euler #23 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm currently trying to solve the project euler problem number 23 :
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
However my code is not giving correct result while it seems to be completely fine. Am I calculating more than the enough numbers ?
private static void Main()
{
List<int> AbudantNumbers = new List<int>();
long sum = 0;
for (int i = 12; i <= 28123; i++)
{
int abudantNumber = GetProperDivisor(i);
if (abudantNumber > i)
{
AbudantNumbers.Add(i);
}
}
for (int k = 1; k <= 28123; k++)
{
int count = 0;
for (int i = 0; i < AbudantNumbers.Count; i++)
{
count = 0;
if (AbudantNumbers[i] > k)
{
break;
}
for (int j = i; j < AbudantNumbers.Count; j++)
{
if (AbudantNumbers[j] > k)
{
break;
}
if (AbudantNumbers[i] + AbudantNumbers[j] == k)
{
count++;
break;
}
}
}
if (count == 0)
{
sum += k;
}
}
Console.WriteLine(sum);
Console.ReadKey();
}
private static int GetProperDivisor(int input)
{
int sum = 1;
for (int i = 2; i <= input / 2; i++)
{
if (input%i == 0)
{
sum += i;
}
}
return sum;
}
My result is : 297632990
Correct result is : 4179871
Quite big difference when there are no obvious mistakes in my code.
My second approach :
for (int k = 1; k <= 28123; k++)
{
var k1 = k;
int count =
(from t1 in AbudantNumbers.TakeWhile(t1 => t1 <= k1) let a = t1 select t1).Count(
t1 => AbudantNumbers.TakeWhile(t => t <= k).Any(t => t1 + t == k));
if (count == 0)
{
sum += k;
}
}
My idea is to get all the abundant numbers lesser than 28123 than check all the integers lesser than 28123 (everything above have a sum of 2 abundant numbers) than rotate all the abundant numbers and lastly check if abundantNumber1 + abundantNumber2 == currentNumber if so we break out of the loop because we need only the ones that don't have a sum of 2 abundant numbers.
When you find that the current number k is the sum of two abundant numbers a[i] + a[j], you set the count and then break out of the loop – out of the inner loop over j, that is.
That means that you still consider all remaining is, for which you reset the count. Effectively, you consider only the last abundant number that is smaller or equal to k. It is not likely that the sum of the two numbers involves this number, so your condition for adding the numbers, count == 0 will be wrong in most cases.
You must break out of the two innermost loops when you find out that k == a[i] + a[j]. C# doesn't seem to have labelled loops, so it is probably best to refactor the the inner loops into a function that takes the list of abundant numbers and k as arguments; you can then simply return true when your condition is met.
As a quick but ugly fix, you can add
if (count) break;
after the loop over j.
Your approach is very ineffective, though. It might be better to write only two nested loops over all abundant numbers and then add their sums to a set when they are smaller than 28124. Then add all numbers from 1 to 28124 that are not in the set.

When arrays go awry?

I'm trying to learn C# by solving mathematical problems. For example, I'm working on finding the sum of factors of 3 or 5 in the first 1000 positive numbers. I have the basic shell of the code laid out, but it isn't behaving how I'm expecting it to.
Right now, instead of getting a single output of 23, I am instead getting 1,1,3,3,5,5,7,7,9,9. I imagine I messed up the truncate function somehow. Its a bloody mess, but its the only way I can think of checking for factors. Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
using System;
namespace Problem1
{
class Problem1
{
public static void Main()
{
//create a 1000 number array
int[] numberPool = new int[10];
//use for loop to assign the first 1000 positive numbers to the array
for (int i = 0; i < numberPool.Length; i++)
{
numberPool[i] = i + 1;
}
//check for factors of 3 or 5 using if/then statment
foreach (int i in numberPool)
if ((i / 3) == Math.Truncate((((decimal)(i / 3)))) || ((i / 5) == Math.Truncate(((decimal)(i / 5)))))
{
numberPool[i] = i;
}
else
{
numberPool[i] = 0;
}
//throw the 0s and factors together and get the sum!
int sum = 0;
for (int x = 0;x < numberPool.Length;x++)
{
sum = sum + numberPool[x];
}
Console.WriteLine(sum);
Console.ReadLine();
//uncomment above if running in vbs
}
}
}
The foreach loop has a few errors.
If you want to modify the array you are looping through use a for loop. Also, use modulus when checking remainders.
for (int i = 0; i < numberPool.Length; i++)
{
if (numberPool[i] % 3 == 0 || numberPool[i] % 5 == 0)
{
// Do nothing
}
else
{
numberPool[i] = 0;
}
}
Modulus (%) will give the remainder when dividing two integers.
Another useful shortcut, variable = variable + x can be replaced with variable += x
Please note that there are more concise ways of doing this but since you are learning the language I will leave that for you to find.
#kailanjian gave some great advice for you but here is another way your initial logic can be simplified for understanding:
//the sum of factors
int sum = 0;
//the maximum number we will test for
int maxNum = 1000;
//iterate from 1 to our max number
for (int i = 1; i <= maxNum; i++)
{
//the number is a factor of 3 or 5
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
//output our sum
Console.WriteLine(sum);
You also stated:
Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
Your program logic will execute in the order that you list it and won't move on to the next given command until it is complete with the last. So your sum output will only be printed once it has completed our for loop iteration.

Categories