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.
Related
I am a beginner in C# and I am struck with this problem. To question is as follows
You are given an array of size n that contains integers. Here, n is an even number. You are required to perform the following operations:
1. Divide the array of numbers in two equal halves
Note: Here, two equal parts of a test case are created by dividing the array into two equal parts.
2. Take the first digit of the numbers that are available in the first half of the array (first 50% of
the test case)
3. Take the last digit of the numbers that are available in the second half of the array (second 50% of
the test case)
4. Generate a number by using the digits that have been selected in the above steps
Your task is to determine whether the newly-generated number is divisible by 11.
And this is my code-
using System;
namespace IsDivisible
{
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int div = 0, digit;
string str = " ";
string[] numArray = Console.ReadLine().Split(' ');
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = Convert.ToInt32(str[i]);
if (i <= n / 2)
{
while (arr[i] >= 10)
{
div = arr[i] / 10;
}
str += div;
}
else
{
digit = arr[i] % 10;
str += digit;
}
}
long newNumber = Convert.ToInt64(str);
if (newNumber % 11 == 0)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
Console.Read();
}
}
}```
It has no errors during compile time in visual studio. The code is not printing anything after I input the array and I am unable to figure out what's wrong. Please help.
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");
}
}
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();
}
}
}
I am beginning to learn C# and am writing a program that will first ask a user to enter a list of numbers. When the user finishes entering the input, I would like to square every number the user provided in the input. An example of user input is 2 3 5.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Third
{
public static void Main()
{
Console.WriteLine("Enter how much numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
int sum = 0;
for (int i = 0; i < num.Length; i++ )
{
sum = num[i] * num[i]; // this is what i did but it does not work?
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
Specifically, I would first like the user input to be captured in the numbers array. And then I would like to square each number in the num array that was created. What's wrong with my program?
First, you need to get input from user and fill the array:
for (int i = 0; i < num.Length; i++)
{
//TODO: Look into int.TryParse method to validate user input
num[i] = int.Parse(Console.ReadLine());
}
And instead of overwriting sum use sum += num[i] * num[i] in your second loop. Or if you are looking for the multiplication of all numbers just use sum = sum * num[i]; and start sum from 1.
Your code does not initialize the array - I added
Console.WriteLine("Enter number " + (i + 1));
num[i] = int.Parse(Console.ReadLine());
for that.
Also corrected the summarisation: sum += ...
for (int i = 0; i < num.Length; i++ )
{
Console.WriteLine("Enter number " + (i + 1));
num[i] = int.Parse(Console.ReadLine());
sum += (num[i] * num[i]);
}
This might be a LITTLE better, although there is still quite a bit of tidying up to do!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Third
{
public static void Main()
{
Console.WriteLine("Enter how many numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
int sum = 1;
for(int i=0;i<num.Length;i++) //allows you to fill the array
{
Console.WriteLine("Please enter an integer");
sum *= int.Parse(Console.ReadLine()); // this will now multiply the value to sum, as your comment suggests
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
EDIT
sum *= num[i];
should do what you want!
Take a look at the math that you are doing in the loop.
sum = num[i] * num[i];
Each time through, you're setting sum equal to the square of the indexed integer.
Taking your example of 2, 3, 5, the first time through the loop, you will set sum = 2 * 2 (or 4), the second time through, you'll set sum = 3 * 3 (or 9) and the last time it will be sum = 5 * 5 (or 25). What you really want is 2 * 3 * 5, right?
All you would need to do is to initialize int sum = 1, and change the statement in your loop to be:
sum = sum * num[i];
This will yield sum = 1 * 2 the first time through, sum = 2 * 3 the second time through, and sum = 4 * 5 the third time through.
I've assumed that the sum that you want to do (if the input is 2,3,5) is 2*3*5. If this is the case, then naming your variable sum is a little misleading as that would tend to imply 2+3+5.
The for loop where you multiply the numbers had the line
sum = num[i]*num[i];
Which, following with the example, when i == 0, would do sum = 2*2, and then overwrite it as you increment the loop, so sum would end at being 25 (5*5), and discount all other values.
If you did want to sum the squares of the numbers, initializing sum to 0 and then using the line
sum += num[i] * num[i];
would work. Having said that, unless you specifically need to store it for any reason, processing the values when they are read would be better, as the program would have 1 fewer for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Third
{
public static void Main()
{
Console.WriteLine("Enter how much numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
for(int i = 0; i < howMuch; ++i)
{
//This is assuming that the user will enter an int value.
//Ideally, verify this using int.TryParse or something similar.
num[i] = int.Parse(Console.ReadLine());
}
int sum = 1; //Set to 1 so that the PRODUCT is not always zero
for (int i = 0; i < num.Length; i++ )
{
sum *= num[i]; //Multiply the value
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
If the input is 2, 3, 5, the value in sum will be 30
replace the code in Main() with this :-
Console.WriteLine("Enter how much numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
Console.WriteLine("Enter numbers");
int sum = 0;
for (int i = 0; i < num.Length; i++ )
{
num[i] = int.Parse(Console.ReadLine());
sum += num[i] * num[i]; // this is what i did but it does not work?
}
Console.WriteLine(sum);
Console.ReadLine();
I am new to C#. I have been working on this program and researching but am not getting anywhere. The goal is to have the user enter numbers (how many is up to the user). when they enter a 0, it will stop the program and display the minimum number entered, the maximum number entered, and the average of all numbers entered. I am not getting any errors and I am getting. If someone can please point me in the right direction.
The WriteLines are returning:
Lowest number is 0
Highest number is 0
Average is: 0
Count: 5
Here is my code:
int LOWEST =0;
int HIGHEST=0;
const int STOP = 0;
double average = 0;
int input;
int count = 0;
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
while (input != STOP)
{
for (int i=0; input != STOP; i++)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
count++;
var Out = new int[] { input };
LOWEST = Out.Min();
HIGHEST = Out.Max();
average = Out.Average();
if ((input > LOWEST) || (input < HIGHEST))
{
LOWEST = Out.Min();
}
if (input > HIGHEST)
{
HIGHEST = Out.Max();
}
}
}
Console.WriteLine("Lowest number is {0}", LOWEST);
Console.WriteLine("Highest number is {0}", HIGHEST);
Console.WriteLine("Average is {0}", average);
Console.WriteLine("Count: {0}", count);
Console.ReadLine();
On each run you are constructing a new array of integers:
var Out = new int[] { input };
After this line, Out contains one item: the last input. Calling Min, Max and Average on it will return the last value. Which is zero if you ended the program.
instead of creating a new array each time, you want to create a List<int> at the beginning of your program and then add each input to it. You can then use the whole list of values to calculate Min, Max and Average.
Eventually you can change your code into something like this:
const int STOP = 0;
int input = -1;
List<int> Out = new List<int>();
while (input != STOP)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
if (input == STOP) break;
Out.Add(input);
}
Console.WriteLine("Lowest number is {0}", Out.Min());
Console.WriteLine("Highest number is {0}", Out.Max());
Console.WriteLine("Average is {0}", Out.Average());
Console.WriteLine("Count: {0}", Out.Count);
Console.ReadLine();
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(20);
numbers.Add(0);
numbers.Max();
numbers.Min();
numbers.Average();
returns 30, 0 and 15.
Before your loop, you should probably make Out an extensible data structure analogous to an array, the List.
List<int> Out = new List<int>();
then each loop, you can
Out.Add(input);
Since this sounds like an exercise for the reader, you can then traverse your list and compute the average from all data values.
Alternately, before the loop, you could declare
int n = 0;
int total = 0;
and each loop, do
n += 1;
total += input;
From these, you should be easily able to compute the average.