Ask 10 numbers then add the together - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int tulos = 0;
for (int i = 0; i < 10; i++)
{
Console.Write("Anna kokonaisluku: ");
String Luku = Console.ReadLine();
int annettu = int.Parse(Luku);
tulos = laske_pluslasku(annettu);
}
Console.WriteLine("Lukujen summa on " + tulos);
Console.ReadKey();
}
static int laske_pluslasku(int luku)
{
int lasku = 0;
lasku += luku;
return lasku;
}
}
}
The program should ask 10 numbers in a loop and then add them together in "static it". When return the sum and print it.
I should get a print like this
My problem is that it won't add all the 10 numbers together. It only displays the last given number. I think that is because of "int lasku = 0;".

The problem is that your adding a number to 0 then setting your final variable to the number you just sum.
Change your code to (If you really need to sum it on a method):
static void Main(string[] args)
{
int tulos = 0;
for (int i = 0; i < 10; i++)
{
Console.Write("Anna kokonaisluku: ");
string luku = Console.ReadLine();
int annettu = int.Parse(luku);
tulos = laske_pluslasku(tulos, annettu);
}
Console.WriteLine("Lukujen summa on " + tulos);
Console.ReadKey();
}
static int laske_pluslasku(int tulos , int annettu)
{
return tulos + annettu;
}
Or a simplier way
static void Main(string[] args)
{
int tulos = 0;
for (int i = 0; i < 10; i++)
{
Console.Write("Anna kokonaisluku: ");
string luku = Console.ReadLine();
int annettu = int.Parse(luku);
tulos += annettu;
}
Console.WriteLine("Lukujen summa on " + tulos);
Console.ReadKey();
}

List<int> sumList = new List<int>();
for (int i = 0; i < 10; i++)
{
Console.Write("Anna kokonaisluku: ");
String Luku = Console.ReadLine();
int annettu = int.Parse(Luku);
sumList.Add(annettu);
}
int result = sumList.Sum();

Related

Why can't get matrix what I passed to Thread?

I want to do some basic stuff: get a matrix, and iterate on it with multiple threads. For example, if I have a 20x20 sized matrix, and I have 4 threads, then the first Thread have to iterate on the 5x20 sized matrix, the second one has to iterate on the same size, but from the 6th row to the 10th one, and so on. But, my program gets only the first part, the second, and third, fourth threads can't see their submatrixes. Why? Can anyone help me with this?
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace multi_thred_test
{
class thredData
{
public int my_simulation_size;
public int[,] my_simulation;
public string my_path;
public int my_nrOfAvailableThreads;
public int my_oneThreeadSubsimulationSize;
public thredData(ref int simsize, ref int[,] simu, ref string path, ref int availabelthrd, ref int subsimsize )
{
my_simulation_size = simsize;
my_simulation = new int[simsize, simsize];
for (int i = 0; i < simsize; i++)
{
for (int j = 0; j < simsize; j++)
{
my_simulation[i, j] = simu[i, j];
}
}
my_path = path;
my_nrOfAvailableThreads = availabelthrd;
my_oneThreeadSubsimulationSize = subsimsize;
}
}
class Program
{
public static int simulation_size = 20;
public static int[,] simulation = new int[20, 20];
public static string path = Directory.GetCurrentDirectory();
public static int nrOfAvailableThreads = Environment.ProcessorCount;
public static int oneThreeadSubsimulationSize = simulation_size / nrOfAvailableThreads;
public static thredData tmp;
public static void Main(string[] args)
{
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
simulation[idx, jdx] = idx * 100 + jdx;
}
}
StreamWriter sw = new StreamWriter(path + "_matrix.txt");
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
sw.Write(simulation[idx, jdx]+" ");
}
sw.WriteLine(" ");
}
sw.Close();
tmp = new thredData(ref simulation_size, ref simulation, ref path, ref nrOfAvailableThreads, ref oneThreeadSubsimulationSize);
//generate threads
for (int thrdnr = 0; thrdnr < nrOfAvailableThreads; thrdnr++)
{
Thread newThread = new Thread(ThreadMethod);
newThread.Name = Convert.ToString(thrdnr);
newThread.Start();
}
Console.ReadKey();
}
private static void ThreadMethod()
{
Thread thr = Thread.CurrentThread;
int simulationSize = Convert.ToInt32(thr.Name);
int thrd_simulation_size;
int[,] thrd_simulation;
string thrd_path;
int thrd_nrOfAvailableThreads;
int thrd_oneThreeadSubsimulationSize;
lock (tmp)
{
thrd_simulation_size = tmp.my_simulation_size;
thrd_simulation = new int[thrd_simulation_size, thrd_simulation_size];
for (int i = 0; i < tmp.my_simulation_size; i++)
{
for (int j = 0; j < tmp.my_simulation_size; j++)
{
thrd_simulation[i, j] = tmp.my_simulation[i, j];
}
}
thrd_path = tmp.my_path;
thrd_nrOfAvailableThreads = tmp.my_nrOfAvailableThreads;
thrd_oneThreeadSubsimulationSize = tmp.my_oneThreeadSubsimulationSize;
}
for (int i = thrd_simulation_size * simulationSize; i < thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name +":"+ thrd_simulation[i,j] + " ");
}
Console.Write("\n");
}
}
}
}
Problem solved, the log part was wrong:
for (int i = thrd_oneThreeadSubsimulationSize * simulationSize; i < (thrd_oneThreeadSubsimulationSize * simulationSize) +thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name + ":" + thrd_simulation[i, j] + " ");
}
Console.Write("\n");
}

How do I find the lowest and highest value of an array as well as the array squared and the array reversed?

I'm trying to write a code that will give me the highest and lowest number in an array as well as the array squared and the reversed array. I keep getting 0's when I run the program but no other problem, so something is set equal to wrong but I can't figure out what's wrong because there's no error messages. Here's the code:
using System;
namespace ArrayMethods
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an array size: ");
int someArray = Convert.ToInt32(Console.ReadLine());
int[] Array = new int[someArray];
String input = Console.ReadLine();
int[] arrayPart3 = new int[10];
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
Console.WriteLine("Largest is:" + ArrayMax(arrayPart3));
Console.WriteLine("Smallest is:" + ArrayMin(arrayPart3));
SquaredArray(arrayPart3);
for (int index = 0; index<arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
Console.WriteLine();
ReversedArray(arrayPart3);
for (int index = 0; index < arrayPart3.Length; index++)
{
Console.Write(arrayPart3[index] + "| ");
}
}
public static int ArrayMax(int[] someArray)
{
int highest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] > highest)
highest = someArray[index];
}
return highest;
}
public static int ArrayMin(int[] someArray)
{
int lowest = someArray[0];
for (int index = 0; index < someArray.Length; index++)
{
if (someArray[index] < lowest)
lowest = someArray[index];
}
return lowest;
}
public static void SquaredArray(int[]someArray)
{
for (int index = 0; index < someArray.Length; index++)
{
someArray[index] = someArray[index] * someArray[index];
}
}
public static void ReversedArray(int[] someArray)
{
for (int index = 0; index<someArray.Length; index++)
{
int temp = someArray[index];
someArray[index] = someArray[someArray.Length - 1 - index];
someArray[someArray.Length - 1 -index] = temp;
}
}
}
}
the code of parsing the input is missing
here is a compact linq based code:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var input = Console.ReadLine();
// or use a fixed input: var input = "1 2 3 4";
int[] arrayPart3 = input.Split(' ',',', ';').Select(s => int.Parse(s)).ToArray();
Console.WriteLine("Reversed: " + string.Join("| ", arrayPart3.Reverse()));
Console.WriteLine();
Console.WriteLine("Largest is:" + arrayPart3.Max());
Console.WriteLine("Smallest is:" + arrayPart3.Min());
Console.WriteLine("Squared: " + string.Join("| ", arrayPart3.Select(i => i*i)));
Console.WriteLine("Reversed Squared: " + string.Join("| ", arrayPart3.Reverse().Select(i => i*i)));
}
}
As mentioned by #user287107 System.Linq provides most of these functions out of the box, for the squaring you can use a simple Select extension method Func.
Here is an ArrayUtils class I quickly wrote to provide the functionality you are looking for:
using System.Linq;
namespace StackOverflow
{
public class ArrayUtils
{
public int GetMax(int[] arr)
{
return arr.Max();
}
public int GetMin(int[] arr)
{
return arr.Min();
}
public int[] GetReverse(int[] arr)
{
return arr.Reverse().ToArray();
}
public int[] SquareValues(int[] arr)
{
return arr.Select(x => x * x).ToArray();
}
}
}

C# Adding big numbers using only strings?

I am trying to write a program that sums very big numbers (I am trying to solve a problem on projecteuler.net), so I cannot parse them into number types. So I was wondering if it is possible to sum such numbers using only strings or something like that?
Try using BigInteger instead. It effictively lets you use integers of arbitrary size.
kindly use BigInteger found in System.Numerics and use `
Add(BigInteger, BigInteger)
` please follow the below link for better understanding.
add two bigintegers
BigInteger Represents an arbitrarily large signed integer. microsoft documentation.
class Program
{
static void Main(string[] args)
{
string inputString = Console.ReadLine();
string[] linePart = inputString.Split(' ', ',', '\n'); // split as , and " " and new line
/* Console.WriteLine(linePart[1]);*/
string num0 = linePart[0];
string num1 = linePart[1];
int val0 = num0.Length;
int iv0 = val0;
int val1 = num1.Length;
int iv1 = val1;
/* Console.WriteLine(val0);
Console.WriteLine(val1)*/;
int arraySize;
if (val0 > val1)
{
arraySize = val0;
}
else { arraySize = val1; }
int[] arr0 = new int[arraySize];
int[] arr1 = new int[arraySize];
for (int i =0; i <iv0; i++)
{
arr0[i] = num0[val0-1]-48;
val0--;
}
for (int i = 0; i < iv1; i++)
{
arr1[i] = num1[val1-1]-48;
val1--;
}
/* for (int i = 0; i < arraySize; i++)
{
Console.Write(arr0[i]);
Console.Write(" ");
Console.Write(arr1[i]);
Console.WriteLine();
}*/
int tamp=0;
int rem=0;
int[] ans = new int[arraySize+1];
int ansloop = arraySize;
for(int i = 0; i <= arraySize; i++)
{
if (i != arraySize)
{
tamp = arr0[i] + arr1[i];
tamp = tamp + rem;
if (tamp >= 10)
{
tamp = tamp % 10;
rem = 1;
}
else { rem = 0; }
ans[ansloop] = tamp;
ansloop--;
}
else {
ans[ansloop] = rem;
}
}
for (int i = 0; i <= arraySize; i++)
{
Console.Write(ans[i]+" ");
}
}
}
}

calculating from each line of an array using c#

I'm very new to c# and programming in general. I'm having some issues trying to get this program to work.
I've to input 5 names from a text file, add 5 scores to each name, remove the max and min score for each name, and then display the winner. What I have done so far only seems to be adding up all the scores. Could anyone point me in the right direction?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diving_Championship
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
string DiverScore;
int score = 0;
int max = 0;
int min = 10;
int Totalscore = 0;
int[] Finalscore = new int[5];
int max1 = 0;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)
{
DiverScore = divers[i];
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", DiverScore);
score = Convert.ToInt16(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Score Is Invalid, Please Re-Enter a score between 0 and 10");
score = Convert.ToInt16(Console.ReadLine());
}
if (score > max)
{
max = score;
}
if (score < min)
{
min = score;
}
Totalscore += score;
}
}
for (int i = 0; i < 5; i++)
{
Finalscore[i] = Totalscore - max - min;
if (Finalscore[0] > max1)
{
max1 = Finalscore[0];
}
if (Finalscore[1] > max1)
{
max1 = Finalscore[1];
}
if (Finalscore[2] > max1)
{
max1 = Finalscore[2];
}
if (Finalscore[3] > max1)
{
max1 = Finalscore[3];
}
if (Finalscore[4] > max1)
{
max1 = Finalscore[4];
}
}
Console.WriteLine("the max score is {0}", max1);
}
}
}
Looks like i was completely barking up the wrong tree, i have finally got my code to work, but thanks for all your input. It's not the prettiest code but it works :P
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DivingChampionship_Coursework
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
int score1 = 0;
int score2 = 0;
int score3 = 0;
int score4 = 0;
int score5 = 0;
Diver1(ref divers, ref score1);
Diver2(ref divers, ref score2);
Diver3(ref divers, ref score3);
Diver4(ref divers, ref score4);
Diver5(ref divers, ref score5);
FindWinner(ref divers, ref score1, ref score2, ref score3, ref score4, ref score5);
}
static void Diver1(ref string[] divers, ref int score1)
{
int[] diver1 = new int[5];
int max1 = 0;
int min1 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[0]);
diver1[i] = Convert.ToInt16(Console.ReadLine());
while (diver1[i] < 0 || diver1[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver1[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver1[i] < min1)
{
min1 = diver1[i];
}
if (diver1[i] > max1)
{
max1 = diver1[i];
}
}
score1 = diver1[0] + diver1[1] + diver1[2] + diver1[3] + diver1[4] - max1 - min1;
Console.WriteLine("Total score is {0} from {1}", score1, divers[0]);
Console.WriteLine();
}
static void Diver2(ref string[] divers, ref int score2)
{
int[] diver2 = new int[5];
int max2 = 0;
int min2 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[1]);
diver2[i] = Convert.ToInt16(Console.ReadLine());
while (diver2[i] < 0 || diver2[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver2[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver2[i] < min2)
{
min2 = diver2[i];
}
if (diver2[i] > max2)
{
max2 = diver2[i];
}
}
score2 = diver2[0] + diver2[1] + diver2[2] + diver2[3] + diver2[4] - max2 - min2;
Console.WriteLine("Total score is {0} from {1}", score2, divers[1]);
Console.WriteLine();
}
static void Diver3(ref string[] divers, ref int score3)
{
int[] diver3 = new int[5];
int max3 = 0;
int min3 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[2]);
diver3[i] = Convert.ToInt16(Console.ReadLine());
while (diver3[i] < 0 || diver3[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver3[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver3[i] < min3)
{
min3 = diver3[i];
}
if (diver3[i] > max3)
{
max3 = diver3[i];
}
}
score3 = diver3[0] + diver3[1] + diver3[2] + diver3[3] + diver3[4] - max3 - min3;
Console.WriteLine("Total score is {0} from {1}", score3, divers[2]);
Console.WriteLine();
}
static void Diver4(ref string[] divers, ref int score4)
{
int[] diver4 = new int[5];
int max4 = 0;
int min4 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[3]);
diver4[i] = Convert.ToInt16(Console.ReadLine());
while (diver4[i] < 0 || diver4[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver4[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver4[i] < min4)
{
min4 = diver4[i];
}
if (diver4[i] > max4)
{
max4 = diver4[i];
}
}
score4 = diver4[0] + diver4[1] + diver4[2] + diver4[3] + diver4[4] - max4 - min4;
Console.WriteLine("Total score is {0} from {1}", score4, divers[3]);
Console.WriteLine();
}
static void Diver5(ref string[] divers, ref int score5)
{
int[] diver5 = new int[5];
int max5 = 0;
int min5 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[4]);
diver5[i] = Convert.ToInt16(Console.ReadLine());
while (diver5[i] < 0 || diver5[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver5[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver5[i] < min5)
{
min5 = diver5[i];
}
if (diver5[i] > max5)
{
max5 = diver5[i];
}
}
score5 = diver5[0] + diver5[1] + diver5[2] + diver5[3] + diver5[4] - max5 - min5;
Console.WriteLine("Total score is {0} from {1}", score5, divers[4]);
Console.WriteLine();
}
static void FindWinner(ref string[] divers, ref int score1, ref int score2, ref int score3, ref int score4, ref int score5)
{
int MaximumScore = 0;
int x = 0;
if (score1 > MaximumScore)
{
MaximumScore = score1;
}
if (score2 > MaximumScore)
{
MaximumScore = score2;
x = 1;
}
if (score3 > MaximumScore)
{
MaximumScore = score3;
x = 2;
}
if (score4 > MaximumScore)
{
MaximumScore = score4;
x = 3;
}
if (score5 > MaximumScore)
{
MaximumScore = score5;
x = 4;
}
Console.WriteLine("Max score is {0} from {1}", MaximumScore, divers[x]);
}
}
}
Appreciate you've already solved your problem, but thought I'd post this short example solution:
Console.WriteLine("The max score is " +
File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt")
.Select(driver =>
{
int score;
do Console.WriteLine("Please Enter a Score between 0 and 10 for " + driver);
while (!int.TryParse(Console.ReadLine(), out score) || score < 0 || score > 10);
return score;
}).Max());
It's not completely clear from the code what do you really aim. At least, the code differs from the task description you provided. Anyway, I'd suggest such a wild guess, for example:
Update - I fixed the code to fit your needs, according to the working code you provided.
using System.IO;
using System.Linq;
namespace Diving_Championship
{
class Program
{
private class Diver
{
internal Diver(string name)
{
Name = name;
}
internal readonly string Name;
internal readonly int[] Scores = new int[5];
internal int TotalScore
{
get { return Scores.OrderBy(sc => sc).Skip(1).Take(3).Sum(); }
}
}
static void Main(string[] args)
{
string[] diverNames = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
List<Diver> divers = new List<Diver>();
for (int j = 0; j < 5; j++)
{
var diver = new Diver(diverNames[j]);
for (int i = 0; i < 5; i++)
{
int score;
do
{
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", diver.Name);
score = Convert.ToInt32(Console.ReadLine());
} while (score < 0 || score > 10);
diver.Scores[i] = score;
divers.Add(diver);
}
}
var MaxScore = divers.Max(d => d.TotalScore);
var Winner = divers.First(d => d.TotalScore == MaxScore);
Console.WriteLine("The winner is {0} with score {1}", Winner.Name, MaxScore); }
}
}
}

Series problems forloop

i have a problem in my series number that will output the 1,2,4,7,11 and etc. i have my forloop that handle the 0,1,2,3,4,5 but im having trouble to progress the 1,2,4,7,11 output please help me this is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int v = 0; v <= 5; v++)
{
for (int x = 1; x <= 5; x++)
{
int c = v + x;
}
}
Console.ReadKey();
}
}
}
ok try this...
class Program
{
static void Main(string[] args)
{
int c = 1;
for (int v = 0; v <= 5; v++)
{
c = c + v;
Console.Write("{0} ", c);
}
Console.ReadKey();
}
}
I hope it will help you...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var iterations = 50;
var result = 0;
for (int i = 0; i < iterations; i++)
{
result += i;
}
Console.WriteLine(result);
Console.ReadKey();
}
}
}
You can try this to control number to calculate from console not by code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number to calculate: ");
int num = Convert.ToInt32(Console.ReadLine());
Fib(0, 1, 1, num);
}
public static void Fib(int i, int j, int count, int num)
{
Console.WriteLine(i);
if (count < num) Fib(j, i+j, count+1, num);
}
I got it.
int x = 1;
for (int v = 0; v <= 5; v++)
{
int c = x + v;
x = c;
Console.Write(c);
}
Console.ReadKey();
It seems something like this :
var f1 = 0;
var f2 = 1;
for (int i = 1; i < 7; i++)
{
Console.WriteLine(f1);
f1 = f2;
f2 = f2 + i;
}
Output :
0, 1, 2, 4, 7, 11
This should work.
int i=1;
int j=0;
while(i<50)
{
i+=j;
j+=1;
Console.Writeln(i)
}
I hope , it should be solve the problem
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace While_loop
{
class Program
{
static void Main(string[] args)
{
int i = 1;
Console.WriteLine(i);
while (i < 10)
{
for (int j = 1; j < 5; j++)
{
i = i + j;
Console.WriteLine(i);
}
i++;
}
Console.ReadKey();
}
}
}

Categories

Resources