so I'm new to coding and I've decided to learn C# with the whole Covid-19 going on, and I've run into a small problem if anybody can assist me.
I'm just writing a basic C# program to allow the user to input 5 numbers into an array and then display the array, but for some reason, I only display the number 5, not the whole array.
Please find my code: ( if anyone can make it easier for me please help me lol (: )
int[] numbers = new int[5];
int num = 0;
int i = 0;
Console.WriteLine("This porgram allows the user to input 5 numbers into an array");
Console.Write("--------------------------------------------------------------");
Console.WriteLine("\n");
for ( i = 0; i < numbers.Length; i ++)
{
Console.WriteLine("Please input number");
num = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < numbers.Length; i++)
{
Console.ReadLine();
Console.WriteLine("Your array is: " , numbers );
}
Console.WriteLine();
// any help will be appreciated!
Two problems:
1) You haven't put the number coming in. After
num = Convert.ToInt32(Console.ReadLine());
put
numbers[i] = num;
Though in fact num is superfluous, so you could just have
numbers[i]= Convert.ToInt32(Console.ReadLine());
2) In the second loop you need to display the specific array element:
Console.WriteLine("Your array item is: " , numbers[i] );
Also, not sure what the ReadLine() in the second loop is for - just means the users has to hit return to see each number.
It's worth mentioning a few other issues in the code:
Variables should be declared as close as possible to where they are used. this i should be declared separately for each for loop - for(int i = 0; ... and num should be declared inside the loop (though as mentioned, it's redundant).
Be clear on the difference between Console.Write() and Console.WriteLine(). WriteLine() simply adds a \n to whatever is displayed. Thus it would be clearer (for the same output to have:
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine();
here is code:
it is the basic syntax of displaying an array.
public class Work
{
public static void Main()
{
int[] arr = new int[5];
int i;
Console.Write("\nRead & Print elements of an array:\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input 5 elements in the array :\n");
for(i=0; i<5; i++)
{
Console.Write("element - {0} : ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for(i=0; i<5; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
}
}
Related
I'm new to C# and I'm trying to calculate the average of 4 numbers from the user I've gotten this far but i'm having issues in the input stage. I wanted to use a for loop to iterate for every number printing "Enter number one:" > user puts 2, its accumulates... Then is asks for the next one "Enter number two" adds to sum and so on until all for numbers have been added. However instead of taking each number at a time. The output for this program is:
number 1number 2number 3number 4:
Question: Why isn't it stopping at each iteration to allow the user to input a number?
namespace Hello
{
class Program
{
static void Main(string[] args)
{
double sum;
for (int i = 1; i <= 4; i++)
Console.Write("Enter number {0}:", i);
sum = +Convert.ToDouble(Console.ReadLine());
}
}
}
Try this:
double sum;
for (int i = 1; i <= 4; i++) {
Console.Write("Enter number {0}:", i);
sum += Convert.ToDouble(Console.ReadLine());
}
You forgot to enclose your for loop in curly braces.
i need a way to store the random numbers generated in the parenthesis for a true/false or if statement but can't because it keeps regenerating new numbers after i input an answer. also if it generated a random of 44 and i answered 48 how do i call the random to display whether if it is correct or not?
Just a simple exercise to help myself with C# coding. Thank you for any answers given.
//There wasn't any problem with the coding at all. The problem was the Online compiler i was using, it kept refreshing every time i enter an input for answer so i thought it was giving me a new random set of numbers after it was already done with printing the entire set in the for loops. i apologize for the confusion! I don't have a visual studio so i was using an online compiler.
public static void Main()
{
Random rand = new Random();
int count, a, b, x, y;
Console.Write("Sequence: ");
count = int.Parse(Console.ReadLine());
Console.Write("Minima: ");
x = int.Parse(Console.ReadLine());
Console.Write("Maxima: ");
y = int.Parse(Console.ReadLine());
int[] roll = new int[count];
for(a = 0; a < count; a++){
roll[a] = rand.Next(x, y);
}
Console.Write("( ");
foreach(var nr in roll){
Console.Write(nr + " ");
}
Console.WriteLine(")");
Console.WriteLine("");
int[] answer = new int[count];
for(b = 0; b < count; b++){
Console.Write("{0}. Answer: ",b+1);
answer[b] =int.Parse(Console.ReadLine());
}
Console.ReadLine();
}
}
The solution is this
for(int i = 0; i < count; i++)
{
if(roll[i] == answer[i])
{
Console.WriteLine("Question " + i + " is correct");
}
}
I am solving the problem from this link: https://www.hackerrank.com/challenges/cut-the-sticks (I added the link for more details if my explanation wasn't enough or wasn't quite clear.)
The point here from the exercise that I in the first I give a (int) number of sticks that I will use in the operation. the second line I enter the sticks length. So I must find the smallest stick(k), then subtract it from the rest of the sticks, then make the program print the number of total sticks that I have cut. So if the stick was cut before or its original value is 0 I have to remove it and don't count it. Then this should repeat over to redefine the value of the k because the min array value will be changed because all the sticks are cutted.
Here is my code that I used:
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
for (int i = 0; i < n - 1; i++)
{
arr = arr.Where(s => s != '0').ToArray();
int k = arr.Min();
arr[i] -= k;
Console.WriteLine(arr.Length);
}
Console.ReadKey();
The problem is it keeps printing the n value, which is the array's original size, it doesn't modify after the removing of the 0. So how can I fix it to just print the number of cutted sticks and when the all sticks is 0 so break?
I'm sorry for my English and if my explanation is a bit hard, but I am just new to C#.
This is the working code as you expected and tested.
Note: I just reused all the variable names and naming conventions as you did which can be refactored further.
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
CutTheStick(arr);
Console.ReadKey();
}
private static void CutTheStick(int[] arr)
{
arr = arr.Where(s => s != 0).ToArray();
if (arr.Length > 0)
{
Console.WriteLine(arr.Length);
int k = arr.Min();
for (int i = 0; i < arr.Length; i++)
{
arr[i] -= k;
}
CutTheStick(arr);
}
}
}
If you had web/winForm based application, remove the static keyword accordingly.
There is an evident error in your code. The char '0' is not the integer 0. The automatic conversion between char and int allows this code to compile and run but you are not testing correctly your inputs
For example
int[] arr = new int[] {0,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will never print "Is Zero", while
int[] arr = new int[] {48,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will print "Is Zero" because the integer value of the char '0' is 48.
Now to give a solution to your problem I could post this code
int cutCount = 1;
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(userinput, Int32.Parse);
// Loop until we finish to empty the array
while (true)
{
// remove any zero present in the array
arr = arr.Where(s => s != 0).ToArray();
// If we don't have any more elements we have finished
if(arr.Length == 0)
break;
// find the lowest value
int k = arr.Min();
// Start a loop to subtract the lowest value to all elements
for (int i = 0; i < arr.Length; i++)
arr[i] -= k;
// Just some print to let us follow the evolution of the array elements
Console.WriteLine($"After cut {cutCount} the array length is {arr.Length}");
Console.Write("Array is composed of: ");
foreach(int x in arr)
Console.Write(x + " ");
Console.WriteLine();
}
Console.ReadLine();
But please study it carefully because otherwise my solution is no help for you in future programming tasks
I was asked to solve a problem in C# to get the sum of 'n' user inputs from console, which is separated by space, in a single line.
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
arr[i] = Convert.ToInt32(Console.ReadLine());
sum += arr[i];
}
Console.WriteLine("{0}",sum);
How can I modify this code to get the expected output from the space separated input?
Also the values need to be stored in array.
Input:
5
1 2 3 4 5
Output:
15
int result = Console.ReadLine().Split().Select(int.Parse).Sum();
You'll of course have to handle any bad user input as needed.
Per your added requirements:
int[] items = Console.ReadLine().Split().Select(int.Parse).ToArray();
int sum = items.Sum();
You could do something like this:
int result = input.Split(' ').Take(n).Select(int.Parse).Sum();
But it seems to me that you could avoid asking the user for the count, and just add together all the lines that they typed in:
string input = Console.ReadLine();
int result = input.Split(' ').Select(int.Parse).Sum();
Console.WriteLine(result);
(Note that this code does no error checking.)
EDIT: It seems that you want to have an array of ints. In that case, you can do it like this (again, with no error checking):
using System;
using System.Linq;
namespace Demo
{
internal class Program
{
private static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] arr = Console.ReadLine().Split(' ').Take(n).Select(int.Parse).ToArray();
int sum = arr.Sum();
Console.WriteLine("{0}", sum);
}
}
}
You need to use the split function in C#. When you read the line, you get the whole line. This means you're attempting to say "sum = 0 plus Convert.ToInt32('5 1 2 3 4 5')" which doesn't work.
You need an array of integers equal to
Console.ReadLine().Split(" ");
String.Split function:
https://msdn.microsoft.com/en-us/library/b873y76a.aspx
using arr[i] = Convert.ToInt32(Console.ReadLine()) inside the loop will cause the program to expect an input on a different line and not on a single line.
What you can do is to take the input as a string and then split based on space, which produces an array of the inputed values. You can then sum them
Considering the fact that Naveen seems a student, I think some more code can explain better and let him learn some more from this exercise:
I've made a sample that gets some numbers separated by space or an enter and when the user enters a T calculates the sum in a traditional way using a loop and using Linq. I'm sure there are plenty of better ways to do the same, but maybe something a little bit more structured can be better to begin understanding C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SumTheNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Insert the numbers separated by a space or [Enter]> key, when finished write T and press [Enter] and you will have the result");
List<int> values = new List<int>();
while (true)
{
string inputData = Console.ReadLine();
if (inputData.ToUpper().StartsWith("T")) break;
string[] svals = inputData.Split(' ');
for (int i = 0; i < svals.Length; i++)
{
int x = 0;
int.TryParse(svals[i], out x);
if (x != 0) values.Add(x);
}
}
//Traditional mode
int total = 0;
for (int i = 0; i < values.Count; i++)
{
total = total + values[i];
}
//Linq mode
int totalLinq = values.Sum();
Console.WriteLine("The sum is");
Console.Write("Total: ");
Console.WriteLine(total.ToString());
Console.Write("Total linq: ");
Console.WriteLine(totalLinq.ToString());
Console.WriteLine("Press a key to end...");
Console.ReadKey();
}
}
}
So i'm trying to make a console program that takes 10 numbers from the user and adds them then averages the sum. Within the do while loop the program is supposed to keep asking for the next number.
{
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare an array of strings
int[] aryNumbers;
int intSum = 0;
int intAverage = 0;
// initialize the array
aryNumbers = new int[10];
aryNumbers[0] = int.Parse(Console.ReadLine());
aryNumbers[1] = int.Parse(Console.ReadLine());
aryNumbers[2] = int.Parse(Console.ReadLine());
aryNumbers[3] = int.Parse(Console.ReadLine());
aryNumbers[4] = int.Parse(Console.ReadLine());
aryNumbers[5] = int.Parse(Console.ReadLine());
aryNumbers[6] = int.Parse(Console.ReadLine());
aryNumbers[7] = int.Parse(Console.ReadLine());
aryNumbers[8] = int.Parse(Console.ReadLine());
aryNumbers[9] = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[] = int.Parse(Console.ReadLine());
} while (intSum != 0);
int intNumbers = aryNumbers.Length;
//for loop to average sum of array elements
for (int i = 0; i < intNumbers; i++)
{
intSum += aryNumbers[i];
}
intAverage = intSum / intNumbers;
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();
}
}
I really have no clue what to do, i'm very new to this
Thanks
There are many problems with your code. I think you should read a whole chapter on arrays. Here's a tutorial on MSDN.
Here is my code:
using System.Linq;
.....
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare the array
int[] aryNumbers = new int[10];
for(int i =0; i<aryNumbers.Length;i++)
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[i] = int.Parse(Console.ReadLine());
}
int intAverage = (int)aryNumbers.Average();
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();