Trouble suming totals [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Have trouble adding a summary for columns number, square and cube for totals. Any pointers where I should be looking at? Below is copy of my code.
static void Main(string[] args)
{
int number;
int total = 0;
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int i = 0; i <= 20; i += 2)
{
number = i;
int k = 0;
do
{
Console.Write(number + "\t");
number *= i;
total += number;
k++;
} while (k < 3);
Console.WriteLine("Total is",total);
Console.WriteLine();
}
Console.WriteLine("---------------------------------------");

If I understand what you want correctly, one way to do this is to keep track of the running totals for each power (1, 2, and 3) in an array, and then display those values at the end.
The array would have 3 indexes, and each time we increase the 'power' that we're raising our number to, we add that value to the corresponding index in the array.
For example:
static void Main(string[] args)
{
// This array will hold three items:
// - totals[0] = numberTotal
// - totals[1] = squareTotal
// - totals[2] = cubeTotal
var totals = new int[3];
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int number = 0; number <= 20; number += 2)
{
// Grab a copy of 'number' so we don't modify the loop variable
var thisNumber = number;
for(int powerIndex = 0; powerIndex < 3; powerIndex++)
{
// Write this number to screen
Console.Write($"{0:n0}\t", thisNumber);
// Add this number to the current number in 'power' index
totals[powerIndex] += thisNumber;
// Power up
thisNumber *= number;
}
Console.WriteLine();
}
Console.WriteLine("-----------------------------");
Console.WriteLine("{0:n0}\t{1:n0}\t{2:n0}\t", totals[0], totals[1], totals[2]);
// Alternatively, if you're using C#6.0, you could write:
Console.WriteLine($"{totals[0]:n0}\t{totals[1]:n0}\t{totals[2]:n0}\t");
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output:

There are two errors in your code:
First one is about Console.WriteLine. To get it working you should pass parameters as for example shown here (it's not the only way to do it but it's the simplest)
Console.WriteLine("Total is" + total);
Secon one is more about algorithm. Let's check when you are adding number to total. If you look closer you can see that you are not adding same number, which you displayed, but your adding number * i ! Thats big mistake but to fix it just swap that two lines like that:
Console.Write(number + "\t");
total += number;
number *= i;
k++;
I belive that fixes every issue, hope it helps :-)
Full code:
using System;
namespace Sum
{
public class Program
{
public static void Main(string[] args)
{
int number;
Console.WriteLine("number\t" + "square\t" + "cube");
Console.WriteLine("-----------------------------");
for (int i = 0; i <= 20; i += 2)
{
number = i;
int total = 0;
int k = 0;
do
{
Console.Write(number + "\t");
total += number;
number *= i;
k++;
} while (k < 3);
Console.WriteLine("Total is "+total);
Console.WriteLine();
}
Console.WriteLine("---------------------------------------");
}
}
}

Related

How can I calculate numbers (for example) from 1 - 10 with the next number. (1+2+3+4+ ...) [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 1 year ago.
Improve this question
Does it have a shorter way than doing something like this:
int[] Summe = new int[6];
Summe[0] = 1;
Summe[1] = 2;
Summe[2] = 3;
Summe[3] = 4;
Summe[4] = 5;
Summe[5] = 6;
Console.WriteLine(Summe[0] + Summe[1] + Summe[2] + Summe[3] + Summe[4] + Summe[5]);
Console.ReadKey();
Using the Enumerable.Sum() method which computes the sum of a sequence of numeric values and Enumerable.Take() which returns a specified number of contiguous elements from the start of a sequence.
Console.WriteLine(Summe.Take(10).Sum());
OR from high school
// sum of integers from 1 to n
int SumNaturalNumbers(int n)
{
return n * (n + 1) / 2;
}
Formula for the general algebraic series starting from a and difference between terms d (Arithmetic progression and series)
sum = n / 2 * (2 * a + (n - 1) * d)
I think using a foreach loop may be helpful here, since you're dealing with an array. Also, you can define your array on one line.
int[] Summe = { 1, 2, 3, 4, 5, 6 };
int total = 0;
foreach (int number in Summe)
{
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
You can simplify this process by simply putting this operation into a while loop.
int i = 0; // tell your program what 'i' should be upon first running the code
while (i < 10) // if 'i' is less than 10, run this block of code. You can change 10 to anything you want
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
This will print each number individually, but you want to calculate the sum of every number, so you could do something like this:
{
public static void Main()
{
int j, sum = 0;
Console.Write("\n\n");
Console.Write("Find the sum of first 10 natural numbers:\n");
Console.Write("----------------------------------------------");
Console.Write("\n\n");
Console.Write("The first 10 natural number are :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j; // add the previous number to the current one
Console.Write("{0} ",j);
}
Console.Write("\nThe Sum is : {0}\n", sum);
}
}
The above code prints the sum of the first 10 natural numbers. I added some additional lines simply to make the program more legible. Again, you can change the number 10 to whatever number you want.

'Summation of primes' takes too long [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I don't know why this takes forever for big numbers I'm trying to solve Problem 10 in Project Euler (https://projecteuler.net/problem=10). Can someone help me please?
It finds the first prime number and crosses all its factors, Then moves on to the next prime number and so on.
long sum=0;
int howmanyChecked = 1;
int target = 1000000;
int index = -1;
List<int> numbers = new List<int>(target);
List<bool> Isprime = new List<bool>(target);
for(int i=2;i<=target;i++)
{
numbers.Add(i);
Isprime.Add(true);
}
while (1 > 0)
{
index = Isprime.IndexOf(true, index + 1);
int Selected = numbers[index];
howmanyChecked++;
sum += Selected;
//Console.WriteLine($"selected prime number is {Selected}");
//int startfrom =numbers.IndexOf(Selected * Selected);
if (Selected >= target / 2)
{
Console.WriteLine("ss");
for(int i=index+1;i<target-1;i++)
{
if(Isprime[i]==true)
{
Console.WriteLine(numbers[i].ToString());
sum += numbers[i];
}
}
Console.WriteLine($"the sum of all prime nubers below {target} is {sum} tap to continue");
Console.ReadLine();
break;
}
else
{
for (int i = Selected; i * Selected <= target; i++)
{
int k = numbers.IndexOf(i * Selected);
if (k == -1)
break;
if (Isprime[k] == true)
{
Isprime[numbers.IndexOf(i * Selected)] = false;
howmanyChecked++;
//Console.WriteLine($"Checked number is {Selected * i} and we have counted {howmanyChecked} numbers");
}
}
}
if (howmanyChecked == target || index==target)
break;
}
Console.ReadLine();
Apply some straightforward optimizations:
list numbers should not be used because each number can be calculated based on an index
simplified initialization of Isprime.
For 1'000'000 got:
the sum of all prime numbers below 1000000 is 37548466742 tap to continue
long sum = 0;
int howmanyChecked = 1;
int target = 1000000;
int index = -1;
var Isprime = Enumerable.Repeat(true, target).ToArray();
while (1 > 0)
{
index = Array.IndexOf(Isprime, true, index + 1);
int Selected = index + 2;
howmanyChecked++;
sum += Selected;
//Console.WriteLine($"selected prime number is {Selected}");
//int startfrom =numbers.IndexOf(Selected * Selected);
if (Selected >= target / 2)
{
Console.WriteLine("ss");
for (int i = index + 1; i < target - 1; i++)
{
if (Isprime[i] == true)
{
Console.WriteLine(i + 2);
sum += i + 2;
}
}
Console.WriteLine($"the sum of all prime nubers below {target} is {sum} tap to continue");
Console.ReadLine();
break;
}
else
{
for (int i = Selected; i * Selected <= target; i++)
{
int k = i * Selected - 2;
if (k < 0)
break;
if (Isprime[k] == true)
{
Isprime[k] = false;
howmanyChecked++;
//Console.WriteLine($"Checked number is {Selected * i} and we have counted {howmanyChecked} numbers");
}
}
}
if (howmanyChecked == target || index == target)
break;
}
Console.ReadLine();
Do SoE (Sieve of Eratosthenes) up to n=2000000 in case you want to be memory efficient 2000000/16 = 62500 Bytes as you need just one bit per odd number). You can do the sum while filling SoE.
Your description is a SoE but you got too much code for a SoE ... my simple SoE solution for this is just 11 lines of formatted C++ code where half of it is variables declaration:
const DWORD N=2000000; // ~ 36 ms
const DWORD M=N>>1; // store only odd values from 3,5,7,...
char p[M]; // p[i] -> is 1+i+i prime? (factors map)
DWORD i,j,k,ss=0,n=0x10000000-N;
uint<2> s=2;
p[0]=0; for (i=1;i<M;i++) p[i]=1;
for(i=3,j=i>>1;i<N;i+=2,j++)
{
if (p[j]==1) { ss+=i; if (ss>=n) { s+=DWORD(ss); ss=0; }}
for(k=i+j;k<M;k+=i) p[k]=0;
} s+=DWORD(ss);
// s holds the answer 142913828922
where DWORD is unsigned 32bit int and uint<2> is 64bit unsigned int (as I am still on 32bit compiler that is why I do the sum so weirdly). As you can see you got maybe 3 times more code than necessary.
Using IsPrime without memoization is too slow but even with memoization can never beat SoE. see:
Prime numbers by Eratosthenes quicker sequential than concurrently?
btw. I got my Euler projects in single app where I do SoE up to 10^7 which creates a list of all primes up to 10^7 this takes 130 ms on my pretty old PC and that is then used for all the Euler problems related to primes (which speeds them up so the first 40 problems is finished below 1sec) which for this case (different solution code) takes 0.7 ms.
To avoid overflows sum on 64 bit arithmetics.
Also using dynamic lists without pre-allocation is slow. You do not need them anyway.
Try with this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
int main()
{
int n,i,i1,imax;
long sumprime;
bool *prime5mod6,*prime1mod6;
n=2000000;
imax=(n-n%6)/6+1;
prime5mod6 = (bool *) calloc(imax+1,sizeof(bool));
prime1mod6 = (bool *) calloc(imax+1,sizeof(bool));
sumprime=5;
for(i=1;(6*i-1)*(6*i-1)<=n;i++){
if(prime5mod6[i]==false){
sumprime=sumprime+6*i-1;
for(i1=6*i*i;i1 <= imax+2*i;i1+=(6*i-1)){
if(i1<=imax)
prime5mod6[i1]=true;
prime1mod6[i1-2*i]=true;
}
}
if(prime1mod6[i]==false){
sumprime=sumprime+6*i+1;
for(i1 = 6*i*i;i1<=imax;i1+=(6*i+1)){
prime5mod6[i1]=true;
if(i1<=imax-2*i)
prime1mod6[i1+2*i]=true;
}
}
}
for(i1=i;i1<=imax-1;i1++){
if(prime5mod6[i1]==false)
sumprime=sumprime+6*i1-1;
if(prime1mod6[i1]==false)
sumprime=sumprime+6*i1+1;
}
if(prime5mod6[imax]==false && n%6==5)
sumprime=sumprime+6*imax-1;
if(prime1mod6[imax-1]==false && n%6==0)
sumprime=sumprime-(6*(imax-1)+1);
printf("\nPrime sum: %ld",sumprime);
free(prime5mod6);
free(prime1mod6);
return 0;
}

Issues with looping code and do-while loops (c#)

static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
Hello. I am a beginner at coding, so I apologize if this is a poor attempt.
I am trying to make an app that records the amount donated by an individual, calculates a transaction fee, and outputs the results for each person. At the end, I am creating a final row of output that will state the total donations and the total transaction fees.
I am currently unsure how to properly implement the array into my loop, and am unsure if the loop is optimized in general.
Again, I am a beginner. I apologize for such code, but I'd love some clarification on these things.
Thank you!
First, your array declaration syntax is wrong. See this link.
So it should be int[] count = new int[donations+1];
Second, you need to declare and instantiate your amount and transfee variables outside of your loop.
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
This should be enough information to get you going again. Since you're learning, I don't think anyone would really unfold an answer for you that does the job you're trying to figure out :)
Your code :
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
You are actually increase i two times, then get values from count[i] assign to ct variable
See this sample :
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
It will cause IndexOutOfRangeException
Explain :
First Loop :
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
Second loop:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count[3] cause IndexOutOfRangeException
Something like count[i += 1] will make your code more difficult to maintain, in my opinion, you should avoid it if possible, try to write it explicity as you can

c # Exception index out of range [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
public class Word
{
private string _inputWord;
public Word()
{
Console.WriteLine("Enter a word");
_inputWord = Console.ReadLine();
}
public void sortandcount()
{
char[] test = _inputWord.ToCharArray();
char temp;
int count = 0, tcount = 0;
Array.Sort(test);
int length = test.Length;
temp = test[0];
while (length > 0)
{
for (int i = 0; i < test.Length; i++)
{
if (temp == test[i])
{
count++;
}
}
Console.WriteLine(temp + " " + count);
tcount = tcount + count;
temp = test[tcount]; //this line
length = length - count;
count = 0;
}
}
}
class Program
{
public static void Main() //this line
{
Word obj = new Word();
obj.sortandcount();
}
}
i get exception at two lines i have indicated as a comment(as // this line in the program) on that line,, can u people help me to clear abt this. M idea abt the program is to count the number of characters(same) in a given word.
Eg Apple
a-1
p-2
l-1
e-1
When you've counted all letters then tcount == test.length which means that test[tcount]will index one element to0 far.
Given any array arr then arr[arr.length] will always be out of bounds because the arr is zero indexed. Before temp = test[tcount] you need to ensure that tcount < test.length however you also have an error in your logic
try with the word obo it will print o 2 o 2
a simple implementation of counting the charaters in a word (if the order does not have to be as they appear in the word) would be
var result = test.Aggregate(new Dictionary<char,int>(), (state,c)=>{
if(!state.ContainsKey(c)) { state.Add(c,0); }
state[c] += 1;
return state;
});
foreach(var pair in result) { Console.WriteLine(pair.Key + " " + key.Value); }
EDIT if you need them to be sorted in the same order as they appear in the word then change the foreach to this
foreach(var pair in result.OrderBy(p=>test.IndexOf(p.Key))) {
Console.WriteLine(pair.Key + " " + key.Value);
}
If you want to output the count of letters in a word, try this code:
var testString = "APPLE";
testString.ToCharArray()
.OrderBy(i => i).ToLookup(i => i)
.Select(i => new { letter = i.Key, count = i.Count() }).ToList()
.ForEach(i => Console.WriteLine("letter {0}, count {1}", i.letter, i.count));
This is a bit cleaner and less error prone.
The code contains a bug
int length = test.Length; // This is not zero based
and count is zero based, your loop will do one additional iteration causing
temp = test[tcount]
to fail because tcount now became bigger than the length of test by 1 character.
The best thing to do is
int length = test.Length -1;
Please let me know if this helps :) have a nice day
A little bit more "programmatic" version:
public class Word
{
private string _inputWord;
public Word()
{
Console.WriteLine("Enter a word");
_inputWord = Console.ReadLine();
}
public void SortAndCount()
{
// sort
char[] array = _inputWord.ToCharArray();
Array.Sort(array);
// for all characters
for(int i = 0; i < array.Length; i++)
{
// duplicate check
if(i > 0 && array[i] == array[i - 1])
continue;
// count
int count = 0;
for(int j = 0; j < array.Length; j++)
if(array[i] == array[j])
count++;
Console.WriteLine(array[i] + " " + count);
}
}
}
class Program
{
public static void Main()
{
Word obj = new Word();
obj.SortAndCount();
}
}

Ask user for starting and stopping point within the array?

In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();

Categories

Resources