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 7 years ago.
Improve this question
I need some help. I created a constant for a small company initialize to 5. I declared an array to hold unique salaries and declared a variable to hold a raise. However I am struggling with using loops to give each salary in the array the raise the user received and then use another loop to display the new salary amounts with the format specifier. Below is the code I am trying to put together.
public class Program
{
public static void Main(string[] args)
{
const int NumOfSalaries = 5;
int[] UniqueSalary = {30000,40000,50000,55000,60000};
decimal raise = 0.0M;
Console.WriteLine("Please enter a raise amount");
raise = int.Parse(Console.ReadLine());
foreach (int number in UniqueSalary)
raise += number;
foreach (int number in UniqueSalary)
Console.WriteLine(" {0}", UniqueSalary);
} // end Main
} // end class
Run a for loop and assign the raise to each element of the array as shown below.
decimal[] UniqueSalary = { 30000, 40000, 50000, 55000, 60000 };
decimal raise = 0.0M;
Console.WriteLine("Please enter a raise amount");
raise = int.Parse(Console.ReadLine());
for (int i = 0; i < UniqueSalary.Length; i++)
UniqueSalary[i] += raise;
for(int i = 0; i < UniqueSalary.Length; i++)
Console.WriteLine(" {0}", UniqueSalary[i]);
Console.ReadLine();
Note: I have changed the array type from an int to decimal. You could maintain an int array and do a conversion when adding the raise.
The problem is inside your for loop.
foreach (int number in UniqueSalary)
raise += number;
This is adding the variable number to the raise and storing it back in raise. You need to store it in the array instead.
Related
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 1 year ago.
Improve this question
I am new to c#, but have been coding in java before. I downloaded visual studio code and the c# extension, and it seems to be working when I do Console.WriteLine("Example"); yet when I have a for loop it seems to not run it. I have a really simple sum calculator, but it doesn't work:
static void Main(string[] args)
{
int sum = 0;
Console.Write("Started Program");
Console.WriteLine("...");
for (int i = 0; i < 10; i++)
{
Console.Write("Choose numbers you want to add: ");
int num = Console.Read();
sum = sum + num;
}
Console.WriteLine(sum);
}
Its probably passing the .read input as ASCII characters instead of the actual int ... try changing;
int num = Console.Read();
to
int num = Int32.Parse(Console.ReadLine());
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 1 year ago.
Improve this question
for(int i = 1; i != amount+1; i++)
{
Console.WriteLine("What is the name of the {0} person?", i);
people.Append(Console.ReadLine());
Console.WriteLine("What was their grade?");
grades.Append(Convert.ToDecimal(Console.ReadLine()));
}
(This section is what is affected)
It gets the inputs from the user (I.E. it gets the names and grades, though it doesn't add to the array. I am new to C#, coming from python. Do you guys have any idea how I could fix this issue? TIA
Are you looking for something like this?
using System.Collections.Generic;
int amount = 5;
List<string> people = new List<string>();
List<decimal> grades = new List<decimal>();
for (int i = 0; i < amount; i++)
{
Console.WriteLine("What is the name of the {0} person?", i);
people.Add(Console.ReadLine());
Console.WriteLine("What was their grade?");
grades.Add(Convert.ToDecimal(Console.ReadLine()));
}
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 4 years ago.
Improve this question
I am new to programming. C# is my first programming language.
I have an assignment where I have to create and test out a bubble sort algorithm and a selection sort algorithm using arrays. I think I understand those now.
The next part of the assignment I am having some trouble on.
I have to write a program that will ask the user for a number (n) and create 1000 arrays of n size.
So if the user enters 5 for the number, my program has to create and sort 1000 arrays that are of length 5.
I have to use the bubble sort and the selection sort methods I created.
After I do that, I have to initiate a variable called running_time to 0. I have to create a for loop that iterates 1000 times and in the body of the loop i have to create an array of n random integers.
Then I have to get the time and set this to the start time. My professor said to notice that the sort is started after each array is built, so I should time the sort process only.
Then I have to get the time and set it to end time. I have to subtract the start time from end time and add the result to the total time.
Once the program has run, note
1. the number of items sorted
2. the average running time for each array (total time/1000)
Then I have to repeat the process using 500, 2500, and 5000 as the size of the array.
This is my code for creating one array with n number of spaces and filled with random integers.
//Asks the user for number
Console.WriteLine("Enter a number: ");
n = Convert.ToInt32(Console.ReadLine());
//Creates an array of the length of the user entered number
int[] randArray = new int[n];
//Brings in the random class so we can use it.
Random r = new Random();
Console.WriteLine("This is the array: ");
//For loop that will put in a random number for each spot in the array.
for (int i = 0; i < randArray.Length; i++) {
randArray[i] = r.Next(n);
Console.Write(randArray[i] + " ");
}
Console.WriteLine();
THIS IS MY CODE FOR THE BUBBLE SORT ALGORITHM:
//Now performing bubble sort algorithm:
for (int j = 0; j <= randArray.Length - 2; j++) {
for (int x = 0; x <= randArray.Length - 2; x++) {
if (randArray[x] > randArray[x + 1]) {
temp = randArray[x + 1];
randArray[x + 1] = randArray[x];
randArray[x] = temp;
}
}
}
//For each loop that will print out the sorted array
foreach (int array in randArray) {
Console.Write(array + " ");
}
Console.WriteLine();
THIS IS MY CODE FOR THE SELECTION SORT ALGORITHM:
//Now performing selection sort algorithm
for (int a = 0; a < randArray1.Length - 1; a++) {
minkey = a;
for (int b = a + 1; b < randArray1.Length; b++) {
if (randArray1[b] < randArray1[minkey]) {
minkey = b;
}
}
tempSS = randArray1[minkey];
randArray1[minkey] = randArray1[a];
randArray1[a] = tempSS;
}
//For loop that will print the array after it is sorted.
Console.WriteLine("This is the array after the selection sort algorithm.");
for (int c = 0; c < randArray1.Length; c++) {
Console.Write(randArray1[c] + " ");
}
Console.WriteLine();
This is very overwhelming as I am new to this and I am still learning this language.
Can someone guide me on the beginning on how to create 1000 different arrays filled with random numbers and then the rest. I would appreciate it greatly. Thank you.
So you have a several questions that has overwhelmed you.
Let's look at each one
Take user input
Console.WriteLine("Enter a length");
while (!int.TryParse(Console.ReadLine(), out var length))
Console.WriteLine("omg! you had one job");
Calling a method with an out argument
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call. The following example is like the previous
example, except that it defines the number variable in the call to the
Int32.TryParse method.
Fill Array
private static Random _rand = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
...
public static string RandomString(int length)
{
var result = Enumerable.Range(0, length)
.Select(s => chars[_rand.Next(length)])
.ToArray();
return new string(result);
}
Create array of random chars
var arr = Enumerable.Range(0, size)
.Select(i => RandomString(length)).ToArray();
How to time something
var sw = Stopwatch.StartNew();
// something to time
var milliseconds = sw.ElapsedMilliseconds
Now map it all together, I'll leave these details up to you
Additional Resources
Enumerable.Range(Int32, Int32) Method
Generates a sequence of integral numbers within a specified range.
Enumerable.Select Method
Projects each element of a sequence into a new form.
Stopwatch Class
Provides a set of methods and properties that you can use to
accurately measure elapsed time.
Random Class
Represents a pseudo-random number generator, which is a device that
produces a sequence of numbers that meet certain statistical
requirements for randomness.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Just trying to make a simple array that takes grades (double variables) and assigns them to the array elements. Also the user determines how many grades they want to assign. It seems simple, yet every time I execute the code, it prints out way too many lines and doesn't stop based on the user input. Not sure what I am missing here.
static void Main(string[] args)
{
int num = 0;
Write("How many grades are you wanting to process...");
num = Read();
Double[] grades = new Double[num];
for (int i = 0; i < grades.Length; i++)
{
WriteLine("Enter grade:");
grades[i] = ToDouble(Read());
WriteLine();
}
It has been a while and feel silly, just came back from python.
Just few modification
static void Main(string[] args)
{
int num = 0;
Write("How many grades are you wanting to process...");
num = Convert.ToInt32(Console.ReadLine());
Double[] grades = new Double[num];
for (int i = 0; i < num; i++)
{
Console.Write("Enter grade:");
grades[i] = Convert.ToDouble(Console.ReadLine());
}
}
ReadKey (returns a character): reads only one single character from
the standard input stream. Usually used when you're giving options to
the user in the console to select from, such as select A, B or C.
Another prominent example, Press Y or n to continue.
ReadLine (returns a string): reads only single line from the standard input stream. As an example, it can be used to ask the user
enter their name or age.
Read (returns an int): reads only one single character from the standard input stream. Similar to ReadKey except that it returns an
integer.
This was clearly described with examples in the MSDN documentation
(links are included above).
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 7 years ago.
Improve this question
I'm trying to do a Prime Number finder but cant see why it's not working.
When i run the debug test nothing show in the console. Could someone check it and tell me what i do wrong?
List<int> primes = new List<int>();
primes.Add(2);
primes.Add(3);
int maxPrime = 11; //The maximum found Primes
int primeCount = primes.Count; //Current Number of Primes
int num = 4; //Current Number
int x = 0; //
int curPrime = primes[x];
while (primeCount < maxPrime)
{
if (x != primeCount)
{
if (num % primes[x] == 0)
{
num++;
x = 0;
}
else
{
x++;
}
}
else
{
primes.Add(num);
primeCount=primes.Count;
x = 0;
}
}
primes.ForEach(i => Console.Write("{0}\t", i));
You have an infinite loop.
Since you never modify primeCount or maxPrime, this will always be true:
while (primeCount < maxPrime)
In order to end that loop, you need to modify one of those two values in such a way that the condition will evaluate to false.
(Note: There appear to also be other bugs/problems in the code aside from this. For example, num = num++; doesn't do what you probably think it does.)