Searching for a "magic digit" among the integers elements of array and summing of all integers that contain the "magic digit".
For example :
1, 2, 3, 4, 5, 55
and magic Digit is 5
1, 2, 3, 4, 5, 55
The sum of numbers that contain the magic digit "5" is: 60
(thank you in advance for your help)
so far I have :
int[] arrayOfUserInput = new int[10];
int i;
//------------------------------- Array and variable declaration
Console.WriteLine("Please enter 10 integers : ");
for (i = 0; i < 10; i++)
{
Console.Write("array element = {0} : ", i);
arrayOfUserInput[i] = Convert.ToInt32(Console.ReadLine());
}
//-------------------------------- User input of 10 integers
Console.Write("Please enter your magic number : ");
int magicNumberInput = Convert.ToInt32(Console.ReadLine());
if (magicNumberInput >= 0 && magicNumberInput <= 9)
{
Console.WriteLine($"Your magic number is : {magicNumberInput}");
}
else
{
Console.WriteLine("Sorry, but please enter single digit number!");
}
//-------------------------------- User input & displaying of magic number
Console.WriteLine("Your integers are : ");
for (i = 0; i < 10; i++)
{
Console.Write("{0} ", arrayOfUserInput[i]);
}
Console.WriteLine("");
//--------------------------------- Displaying user input of 10 integers
You can use Linq .Where() and .Sum() to calculate total of all numbers containing magic numbers.
using System;
using System.Linq;
using System.Collections.Generic;
...
var arrayOfUserInput = new int[] {1, 2, 3, 4, 5, 55};
var magicNumberInput = 5;
var sumOfNumbers = arrayOfUserInput
.Where(x => x.ToString().Contains(magicNumberInput.ToString())) //Filter by Magic numbers
.Sum(); //Calculate sum of filtered numbers.
.Net Fiddle
If you don't want to use Linq then you can do it using foreach or for loop with string.Contains() function.
...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
if(input.ToString().Contains(magicNumberInput.ToString()))
sumOfNumbers += input;
}
Console.WriteLine(sumOfNumbers);
I would strongly suggest you to read more about LINQ and basics of C#.
Code refactoring note:
If you store input data in string format, then you need not to convert it again into string. At the time of addition convert it into int and add it to sumOfNumbers. Like,
Using Linq,
var sumOfNumbers = arrayOfUserInput
.Select(x => x.Contains(magicNumberInput) && int.TryParse(x, out int number) ? number : 0)
.Sum();
using for loop,
...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
if(input.Contains(magicNumberInput) && int.TryParse(input, out int number))
sumOfNumbers += number;
}
Related
I need some help with the for-loop. I'm trying to sum up every fifth number that I type in, instead it sums them all up. What do I have to change?
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
for (count = 0; count <= 0; count += 5)
{
total = total + input;
}
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Assuming that you enter a list of numbers, and the 1st number and every five afterwards is added (so 1st, 6th, 11th, etc.):
int count = 0;
double total = 0;
Console.Write("Enter your number: ");
int input = int.Parse(Console.ReadLine());
while (input != 0)
{
count++;
if (count % 5 == 1)
total = total + input;
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
This works by using the modulo operator (%). The modulo operator returns the remainder of a division operation involving the number you specify.
In the code if (count % 5 == 1), the question is:
Is the remainder of count divided by 5 equal to 1?
If so, it adds the number. If not, it is skipped
The reason the remainder is one is because we want results 1, 6, 11, etc:
1 / 5 = remainder 1
6 / 5 = remainder 1
11 / 5 = remainder 1
If you change the modulo value to 0 it will return the results at position 5, 10, 15, etc.
You could just store the numbers in a list and calculate it at the end:
var numbers = new List<int>();
Console.Write("Enter your number: ");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
numbers.Add(input);
input = int.Parse(Console.ReadLine());
}
var total = numbers.Where((x, i) => (i + 1) % 5 == 0).Sum(); // i + 1 since indexes are 0-based.
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
You can try this:
double total = 0;
int passover = 4;
int input = 0;
do
{
passover++;
Console.Write("Enter your number: ");
int.TryParse(Console.ReadLine(), out input);
if ( passover != 5 ) continue;
passover = 1;
total = total + input;
}
while ( input != 0 );
Console.WriteLine("The sum of every fifth numbers is: {0}", total);
Console.ReadKey();
I think the best way is to recover all the values before making the sum, this code works:
double total = 0;
int input = -1;
List<int> allInput = new List<int>();
while (input != 0)
{
Console.Write("Enter your number: ");
input = int.Parse(Console.ReadLine());
allInput.Add(input);
}
for (int i = 0; i < allInput.Count()-1; i += 5)
{
total = total + allInput[i];
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
Your sample would go forever, because there is no break point in your loop. You should always put a break point in your loop, otherwise it'll loop indefinitely.
Here is what you need :
int total = 0;
int count = 0;
Console.Write("Enter your number: ");
while (true)
{
int input = 0;
bool isNumber = int.TryParse(Console.ReadLine(), out input);
if (isNumber)
{
count++;
if (count % 5 == 0)
total += input;
}
else
{
break;
}
Console.Write("Add another number or press enter to get the sum : ");
}
Console.WriteLine("The sum of every +5 numbers is: {0}", total);
Console.ReadKey();
So, you'll need first to put the user input inside a loop, and keep asking the user for adding another number until hits the condition where you close this loop. In the example, I decided to break the loop if the user typed anything not a number. but I told the user to press enter to get the some, to end the loop. For you, you'll need to translate that to your application breakpoint, how would you want the user to get the sum ?. Then, change the condition to your logic, so it breaks the loop and gets the sum.
another point is that int.TryParse. When you want to convert strings to numbers (int, long, decimal ..etc). You should always use `TryParse, this will verify the number, if the conversion failed, it'll return false. This way you can maintain the conversion and do something about it.
how can I make the code below work?
If a number is a multiple of 3, write to the console: "Hi" plus the number e,g IT3
Console.WriteLine("Enter number that is a multiple of 3");
int[] numero = new int[5];
numero[0] = 3;
numero[1] = 6;
numero[2] = 9;
numero[3] = 12;
numero = Console.ReadLine();
if (numero = "3, 6, 9, 12, 15")
{
Console.WriteLine("IT" + "{0}");
}
Take a look at the % Operator.
The remainder operator % computes the remainder after dividing its
first operand by its second operand.
if (Convert.ToInt32(numero) % 3 == 0)
{
// do stuff
}
So there's a few things going on with your code.
You're using = (should be == to compare as a single equality sign is assigning a value) on a string type ("") quotations define string types.
What you want to do is test each index of the array using integer comparison, or if you're going to read them as strings use the string comparator .Equals().
Console.WriteLine("Enter number that is a multiple of 3");
int[] numero = new int[5];
numero[0] = 3;
numero[1] = 6;
numero[2] = 9;
numero[3] = 12;
numero = Console.ReadLine();
if (numero = "3, 6, 9, 12, 15")
{
Console.WriteLine("IT" + "{0}");
}
The above code should be translated to something like this:
Console.WriteLine("Enter number that is a multiple of 3");
int[] arrCheck = new int[5];
arrCheck[0] = 3;
arrCheck[1] = 6;
arrCheck[2] = 9;
arrCheck[3] = 12;
int number = 0;
number = Convert.ToInt32(Console.ReadLine());
//if the number is a multiple of the value stored in arrCheck[0] (e.g 3)
if (number % arrCheck[0] == 0)
{
Console.WriteLine("Hi" + number);
}
The modulo operator is useful for checking remainders and in this case if the remainder is 0 post division with 3 then you know it's a multiple.
Console.WriteLine("Enter number that is a multiple of 3");
var numero = Console.ReadLine();
if (Convert.ToInt32(numero) % 3 == 0)
{
Console.WriteLine($"HI IT{numero}");
}
I am trying to work out how to count how many numbers in an array fall between the values of, 1.5 - 35. I am struggling to work out which method I should use to achieve this. I was thinking maybe a for-each embedded loop but then the more I think about it the more I question that method. Any help would be appreciated on how I may achieve this, I will post my current code below as I have already worked out how to calculate the average and minimum price for the equation.
class Program
{
static void Main(string[] args)
{
read_stock_price();
}
static void read_stock_price()
{
Console.Write("Enter how many stocks to enter price for: ");
int numStocks = Convert.ToInt32(Console.ReadLine());
double[] arrayinput = new double[numStocks];
for (int i = 0; i < numStocks; ++i)
{
Console.Write("Enter price for stock number: ");
arrayinput[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = arrayinput.Sum();
double average = sum / numStocks;
Console.WriteLine("Average price: {0} out of {1} stocks", average, numStocks);
Console.WriteLine("Minimum price: {0}", arrayinput.Min());
}
}
You can use LINQ instead of a for-each. First filter the array then count the elements.
var count = arrayinput
.Where(x => 1.5 <= x && x <= 35.0)
.Count();
Shortest way is Enumerable.Count
var count = arrayinput.Count(x => 1.5 < x && x < 35.0);
if we assumed arrayinput is your filled array you can use this:
double[] arrayinput = new double[numStocks];
double[] filteredArray = arrayinput.Where(p => p > 1.5 && p < 3.5).ToArray();
int count = filteredArray.Count();
this code filter your array with value between 1.5 & 3.5.
We are working on the Project Euler problems and there is one part of the code I cannot get to work.
I have displayed and calculated the sum for multiples of 3 and 5 under 10, and I have calculated the sum for the same numbers under 1000 but I cannot initially display the numbers used for the calculation within a textbox or equivalent field.
Here's a link to the code.
http://pastebin.com/MZAA88UP
I think, it's a good task for Linq:
int n = 1000;
var numbers = Enumerable
.Range(1, n - 1)
.Where(item => item % 3 == 0 || item % 5 == 0);
Having numbers as a source you can easily play with it. If you want to sum up:
// 233168
var sum = numbers.Sum();
If you want to print out the numbers:
// 3, 5, 6, 9, 10, 12, ..., 996, 999
string report = string.Join(", ", numbers);
If you want to use loops instead of Linq:
private void BtnDisplay1000_Click(object sender, RoutedEventArgs e)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
stringBuilder.Append(i);
stringBuilder.Append(", ");
}
}
TxtDisplay1000.Text = (stringBuilder.ToString());
}
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();