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();
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`m quite new to the whole programming world.
And i started studying C#
i got the following exersice to do:
Write a program that upon the input of 2 numbers (a and b), u receive
an output of the sum of squares in between.
I.e. - The program receives a and b where b > a and calculates a^2
+ (a+1)^2 + (a+2)^2 + ... + (b-1)^2 + b^2.
E.g. - If a = 3 and b = 6, the output would be 86, since 3^2 +
4^2 + 5^2 + 6^2 = 9 + 16 + 25 + 36 = 86
But i don't have any idea where do i even begin.
I`m guessing i need some sort of loop within a loop maybe?
You need to use for loop for this. Please see below, if that helps-
int i, j, k;
int value=0;
Console.WriteLine("Enter the fist number ");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
j = Convert.ToInt32(Console.ReadLine());
if (i > j)
{
Console.WriteLine("Second number should be greater then First");
Console.ReadLine();
Environment.Exit(0);
}
for (k = i; k <= j; k++)
{
value += k * k;
}
Console.WriteLine(value);
Console.ReadLine();
Perhaps a method that takes in two integers and returns a double is a good place to start (returning a double allows you to specify a wider range of numbers without getting inaccurate results):
public static double GetSumOfSquaresBetween(int first, int second)
{
}
Then you could implement the body by creating a loop that goes from the lowest number to the highest number, adding the square of the current number to a result, and then returning that result at the end.
Here's a Linq example that would most likely not be acceptable for this assignment but gives you the idea:
public static double GetSumOfSquaresBetween(int first, int second)
{
return Enumerable
.Range(Math.Min(first, second), Math.Abs(first - second) + 1)
.Select(number => Math.Pow(number, 2))
.Sum();
}
Try this
int a, b, sum = 0;
Console.WriteLine("Enter the fist number ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
b = Convert.ToInt32(Console.ReadLine());
if (a<b){
for (int x = a+1; x < b; x++)
{
sum += x * x;
}
Console.WriteLine(sum);
}
else{
Console.WriteLine("Wrong input!");
}
Console.ReadLine();
}
}
A for loop should do it.
double nTotal = 0;
for (int a = 3; a <= 6; a++)
{
nTotal += Math.Pow(a, 2);
}
I'm currently creating a simple single layer perceptron algorithm. It should take in a .txt file and the algorithm runs over it. At the moment, I have the algorithm and just hard coded sample data values to test if it works (which it does), but I need it to feed off existing data values from a file. I have tried to make it work, but due to my inexperience in coding, I haven't succeeded. It would be awesome if someone could help me get this code working with external data as I've been pulling my hair out. The data is formatted like below (obviously without the bullet numbers).
0.651769
0.651604
0.651609
0.651679
0.651667
0.651699
Current Code:
using System;
using System.IO;
using System.Collections.Generic;
namespace Network
{
public class Network
{
static void Main()
{
// Load sample input patterns.
double[,] inputs = new double[,] {
{0.99, 0.99}, {0.99, 0.99}, {0.99, 0.99}, {0.99, 095}};
// Load sample output patterns.
int[] outputs = new int[] {0, 1, 0, 0 };
int patternCount = inputs.GetUpperBound(0) + 1;
// Randomise weights.
Random rdm = new Random();
// Setting randomly generated weights between -0.5 and +0.5
double[] weights = {rdm.NextDouble()-0.5, rdm.NextDouble()-0.5, rdm.NextDouble()};
// Set learning rate.
double learningRate = 1;
// Start iteration at 0
int iteration = 1;
double ErrorRate;
do
{
// Global error set to 0
ErrorRate = 0;
for (int j = 0; j < patternCount; j++)
{
// Calculate output.
int output = Output(weights, inputs[j, 0], inputs[j, 1]);
// Calculate error.
double localError = outputs[j] - output;
//if the localError is not equal to zero
if (localError != 0)
{
// Update weights.
for (int i = 0; i < 2; i++)
{
weights[i] += learningRate * localError * inputs[j, i] / 2;
}
}
// Convert error to absolute value.
ErrorRate += (localError);
}
Console.WriteLine("Iteration {0}\tError {1}", iteration, ErrorRate);
iteration++;
// If the Error is equal to zero then calculate
} while (ErrorRate != 0);
// Convergence
Console.WriteLine();
Console.WriteLine("[Input1] [Input2] [Output]");
// Input1 values
for (double input1 = 0; input1 <= 1; input1 += 1)
{
// Input2 values
for (double input2 = 0; input2 <= 1; input2 += 1)
{
// Calculate output with the inputs and the randomly generated weights
int output = Output(weights, input1, input2);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(" {0} {1} {2}", input1, input2, (output == 1) ? "1" : "0");
}
}
Console.Read();
}
private static int Output(double[] weights, double input1, double input2)
{
// Output = input1 * weight1 + input2 * weight2 + bias * weight3
double sum = input1 * weights[0] + input2 * weights[1] + 1 * weights[2];
// If the first condition is true, then it becomes the result. If not, the second condition becomes the result
return (sum >= 0) ? 1 : 0;
}
}
}
Are you looking for
using System.Globalization;
using System.IO;
using System.Linq
...
double[] data = File
.ReadLines(#"C:\MyFile.txt") //TODO: put actual file here
.Select(line => Double.Parse(line, CultureInfo.InvariantCulture))
.ToArray();
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 have printed some Fibonacci numbers. Now I want to see if a number / which I enter / is within that range and if it is, to show it's position.
This is what I have so far:
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
int first = 0;
int second = 1;
int third = 1;
for (int i = 0; i < 50; i++)
{
third = second;
second = first + second;
first = third;
Console.WriteLine(second);
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (number == second)
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
}
}
I can't understand why the If statement prints the else result if I enter a number that I SEE in the range?!
I think that after I manage to make the If statement to work, the position is the "i" in the for statement?
I suggest you to use either an array of integer or List of integer to solve this: as like the following:
int first = 0;
int second = 1;
int third = 1;
List<int> fibnoList= new List<int>();
for (int i = 0; i < 50; i++)
{
fibnoList.Add(second);
Console.WriteLine(second); //To print the series
third = second;
second = first + second;
first = third;
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (fibnoList.Contains(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
Aside from using looping, maybe you can consider this
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (IsFibonacci(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
static bool IsFibonacci(int number)
{
//Uses a closed form solution for the fibonacci number calculation.
//http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence
int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)
return actualFibonacciNumber == number;
}
}
}