Can I ask some questions about C# ? (Array)(Loop) [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 4 years ago.
Improve this question
I'm studying C# programming.
Nevertheless, I don't know how to solve these problems.
Like (Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program)
using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp36
{
class Program
{
static void Main(string[] args)
{
double a, b, c;
double avg = 0;
Console.Write("Input the first value : ");
a = Convert.ToDouble(Console.ReadLine());
Console.Write("Input the second value : ");
b = Convert.ToDouble(Console.ReadLine());
Console.Write("Input the third value : ");
c = Convert.ToDouble(Console.ReadLine());
avg = (a + b + c) / 3;
Console.WriteLine("Average of 3 different values is : {0}", avg);
}
}
}
and
(Write a MyFact function that gets one integer as an input and calculates the factorial of it. It returns factorial as the result of the function. Use the function in one simple program. Use the function in one simple program.)
using System;
/*4. Write a MyAvg method that gets 3 different double inputs and calculates the average of them. It should return the average as the output. Use the function in one simple program*/
namespace ConsoleApp39
{
class Program
{
static void Main(string[] args)
{
int i, f = 1, num;
Console.Write("Input the number : ");
num = Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
f = f * i;
Console.Write("The Factorial of {0} is: {1}\n", num, f);
}
}
}
Can you guys help me?

You should be more clear with your questions and show us that you actually tried to write some code. Anyways, here MyAvg and MyFact is just abbreviations for "MyAvarage" and "MyFactorial".
As you should know, average avarage in mathematics is simply summing n numbers, and then dividing the sum with n. So you should implement it in your function MyAvg. Here is how you should take the avarage of three double numbers;
double average = (a + b + c) / 3;
Also, for the function MyFact, you should be taking an int parameter, and then simply be implying the factorial algorithm. Let's assume you've sent 5 as a parameter to MyFact(), then you should be multiplying the number 5 decreasingly in a for loop, such as 5*4*3*2*1, and it will give you the result. You can return this result, or simply print it directly in function.
For loop to calculate factorials

Related

How to fix this "Input string was not in a correct format" problem in the following code? [duplicate]

This question already has answers here:
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
Here is my code :
using System;
namespace CappedSum
{
class Program
{
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;
while (sum<sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
if (sum + number < sumLimit)
{
sum += number;
count++;
}
else if (sum + number > sumLimit)
{
Console.WriteLine(sum + " " + count);
}
}
}
}
}
I had to write a console application that reads from the keyboard a list of numbers until their sum reaches a certain limit also entered by the user.
The limit is given on the first line, and on the next lines will be the list of numbers which has to be added. The program will stop reading when the sum of the numbers entered so far exceeds the limit and will display the last amount that did not exceed the limit, as well as how many numbers were needed to calculate it.
for example : if I enter 10 (which is the limit) then I enter 2,3,2,6. The result will be 7 (which is the last amount that did not exceed the limit) and 3 (which represents how many numbers needed to calculate it).
Try out Int32.Parse instead of Convert.ToInt32. Also, a really basic I use sometimes to debug my same mistakes, is to write MessageBoxes after specific instructions, so if they do not work I never get to the message, viceversa if the message shows I know that works. I'd put two Messageboxes after the Int32.Parse(Console.Readline()) being like MessageBox.Show(sumlimit/number.ToString());. This way you know how far the code works.

Creating 1000 arrays and sorting them using the bubble and selection sort (C#) [closed]

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.

how to solve application disappearing after console readline a negative number? [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 6 years ago.
Improve this question
So I wrote a short code in c#, and it's function is like this:
First you choose how many times you want to put in a number, then you pick a number to sum
static void number()
{
Console.WriteLine("how many numbers, max is 999");
int n = int.Parse(Console.ReadLine());
if (n > 999)
{
return;
}
Console.WriteLine("enter number here:");
int d = int.Parse(Console.ReadLine());
if (d < -99999 || d > 99999)
{
return;
}
Console.WriteLine(n + " " + d + "which number has to be counted up");
for (int i = 0; i < n; i++)
{
int e = int.Parse(Console.ReadLine());
int c;
c = e + d;
Console.WriteLine(e + " " + c);
Console.WriteLine("press enter to input a new number");
Console.ReadKey();
i++;
}
}
If I put positive numbers, it works correctly. But if I put in negative numbers, It asks "enter number here" and after I put in a number, it shows the which number to count up writeline very quickly and then the application stops for no reason.
Any thoughts why this happens?
If you put a negative number into n, then i will never be less than n in your for loop (which you've set to run while i < n). This means the the for loop will never run and the as this is the last bit of code in you application, the program will end.
Here's what I get:
how many numbers, max is 999
-2
enter number here:
3
-2 3which number has to be counted up
When I enter the -2 it gets stored in the variable n. Later, in the for loop, the variable i starts out at zero, which means the i < n, so the loop quits without executing anything in the loop body.

how do you repeat the total entered? [closed]

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 8 years ago.
Improve this question
I am very new to c# and I don't get it very quickly. If you can explain how and why like your talking to a 3yr old that would be great!!!
how do you make (enter the amount (-1 to stop)) repeat and end up with a total of all amounts entered?
Luckily, my 3-year old is sitting right here, so I had him write it out :)
var total = 0; // This will hold the sum of all entries
var result = 0; // This will hold the current entry
// This condition will loop until the user enters -1
while (result != -1)
{
// Write the prompt out to the console window
Console.Write("Enter the amount (-1 to stop): ");
// Capture the user input (which is a string)
var input = Console.ReadLine();
// Try to parse the input into an integer (if TryParse succeeds,
// then 'result' will contain the integer they entered)
if (int.TryParse(input, out result))
{
// If the user didn't enter -1, add the result to the total
if (result != -1) total += result;
}
else
{
// If we get in here, then TryParse failed, so let the user know.
Console.WriteLine("{0} is not a valid amount.", input);
}
}
// If we get here, it means the user entered -1 and we exited the while loop
Console.WriteLine("The total of your entries is: {0}", total);
We are calling it loops, little boy :P
UPDATE I dont know if i understood you, but now the code writes sum each time, and if you enter for example -5 it will be sum = sum - 5
class Program
{
static void Main(string[] args)
{
// thoose are variables, and they are storing data
int input = 0; // input integer number
int sum = 0; // sum of all numbers
while (true) //Infinite loop (executes undereneath code until true=true)
{
input = int.Parse(Console.ReadLine()); // read the line from user, parse to int, save to input variable
if (input == -1) break; // if integer input is -1, it stops looping (the loop breaks) and GOES (two lines down)
sum = sum+ input; // summing all input (short version -> s+=input)
Console.WriteLine("Actual Sum: "+sum); // HERE IS THE UPDATE
}
//HERE
Console.WriteLine("Your final sum is: " + s);
}
}

SPOJ small factorials problem

Here is the exact question
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
I have coded the SPOJ small factorials problem no 24, but the judge is saying as wrong answer. Please have a look at my code and help me.
class Program
{
static void Main(string[] args)
{
long numOfTestCases=0;
string factForAll = "";
numOfTestCases = Convert.ToInt32(Console.ReadLine());
long[] numArray = new long[numOfTestCases];
for (long i = 0; i < numArray.Length; i++)
{
numArray[i]= Convert.ToInt64(Console.ReadLine());
}
foreach (var item in numArray)
{
long factResult = findFact(item);
factForAll += factResult+"\n";
}
Console.WriteLine();
Console.WriteLine(factForAll);
}
public static long findFact(long number)
{
long factorial = 1;
if (number<=1)
{
factorial = 1;
}
for (long i = 1; i <=number; i++)
{
factorial *= i;
}
return factorial;
}
}
After looking at the first comment you need to write each answer on a single line, in c3 that is "\r\n", not "\n".
The problem specifies that the numbers are in the range 1 <= n <= 100. You are calculating the factorial of these in long variables. The range of a long is –9223372036854775808 to 9223372036854775807. The result will easily overflow this range.
For example,
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
You will need to use something like BigInteger to manipulate numbers this large.
C# is not an optimal language choice on SPOJ.com because everything runs on Unix/Linux servers, and the version of C# used is actually Mono 2.. that is why a lot of stuff is not supported, and will not run as expected.
So i would recommend switching to C++ or Java :)

Categories

Resources