Console.WriteLine("Please enter your number of the Names : ?");
int x = Convert.ToInt32(Console.ReadLine());
string[] names = new string[x];
for (int i = 0; i < x; i++)
{
Console.Write("Enter Name no.{0} : ", i + 1);
names[i] = Console.ReadLine();
}
Console.WriteLine("the items are {0}", names);
Console.ReadKey();
Now when I want to type down the names, it just prints the first Name entered!
Like if I have 5 names, in the last line in the
Console.WriteLine("the items are {0}", names);
it just prints out the 1st name!
You'll want to do a loop at the end as well
Either a for loop or a foreach, the current way you are using Console.WriteLine() is using the string.Format() overload
foreach (string name in names)
{
// Write out here
Console.WriteLine(name);
}
Join the strings together with the separator you want, before passing them to writeline.
Use string.Join to do so.
Passing an array to WriteLine makes out think you are passing an array with values to format.
You have to do a loop.
Console.Write("the items are");
for (int i = 0; i < names.Length; ++i)
{
Console.Write(" ");
Console.Write(names[i]);
}
Console.WriteLine();
//Console.WriteLine("the items are {0}.", String.Join(", ", names));
string argsFormat = ( 1 < x) ?
String.Join(", ", Enumerable.Range(0, x).Select(n => "{" + n + "}").ToArray())
.Replace(", {" + (x-1) + "}", " and {" + (x-1) + "}") + "."
:
argsFormat = "{0}.";
Console.WriteLine("the items are " + argsFormat , names);
Related
I am a beginner in C# programming and trying to code a method that ask the user to give a start and an end integer number, then sum up all numbers from the start to the end and in case the given start number is greater than the end number, swap the values so that the start number becomes the end number and the end number gets the value of the start number.
This what I have done so far but I'm not getting the right answer when running the app:
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
startNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nplease enter an end number: ");
endNumber = Convert.ToInt32(Console.ReadLine());
int result = 0;
for (int i=0; i<=startNumber; i=i+1)
{
result = result + i;
Console.WriteLine(i);
}
Console.ReadLine();
Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString());
Console.ReadLine();
}
I'm getting this result: The sum of Numbers between 12 and 23 is: 78 when the result actually need to 210.
for (int i=0;i<=startNumber;i=i+1)
You are iterating from 0 to startNumber, when really you want to iterate like startNumber to endNumber.
Try
for (int i = startNumber; i <= endNumber; i = i+1)
Below is the working example.
I also added some logic to handle the checking of the input (whether it is correct or no) so the application doesn't break. This way the user experience is much better.
Here is the live working example: code
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
do
{
var input1 = Console.ReadLine();
if (Regex.IsMatch(input1, #"^\d+$"))
{
startNumber = Convert.ToInt32(input1); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
Console.WriteLine("\nplease enter an end number: ");
do
{
var input2 = Console.ReadLine();
if (Regex.IsMatch(input2, #"^\d+$"))
{
endNumber = Convert.ToInt32(input2); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
int min = Math.Min(startNumber, endNumber);
int max = Math.Max(startNumber, endNumber);
int result = 0;
for (int i = min; i <= max; i++)
{
result = result + i;
Console.WriteLine(i);
}
Console.WriteLine("The sum of Numbers between " + min + " and " + max + " is: " + result.ToString());
Console.ReadLine();
}
The problem I have is that when I enter an element from the array, the user input resets to the start of the loop, for example when i user input the third element from the array, the user input question two more times to continue to the next user input question, how can I fix this? everybody know what I can adjust here.
worked loop image with 1st element entered
looping error
while (true)
{
String[] bgtype = { "cheeseburger","tlc", "bbq" };
int[] bgtypeprice = { 15, 25, 10 };
int max = bgtype.Length;
String[] product = new string[max];
String[] type = new string[max];
int[] qty = new int[max];
int[] disc = new int[max];
Console.WriteLine("");
for (int i = 0; i < max; i++)
{
Console.Write("What PRODUCT would you like to buy ?: "); ;
product[i] = Console.ReadLine();
if (product[i].Equals("burger", StringComparison.CurrentCultureIgnoreCase))
{
{
Console.Write("What TYPE of product would you like to buy?: ");
type[i] = Console.ReadLine();
if (bgtype[i].Contains(type[i]))
{
Console.Write("Enter your discount % (5% for adults & 7% for minors): ");
disc[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("How many will you buy? ");
qty[i] = Convert.ToInt32(Console.ReadLine());
float total = bgtypeprice[i]; total *= qty[i];
Console.WriteLine("Total cost of " + type[i] + " " + product[i] + " is: " + qty[i] + " pieces x P" + bgtypeprice[i] + "= P" + total);
float totaldisc = 0; totaldisc = (total * disc[i]) / 100;
Console.WriteLine("Total amount of discount: P " + totaldisc);
float totalamt = 0; totalamt = total - totaldisc;
Console.WriteLine("Total cost of order: P " + totalamt);
Console.WriteLine("-------------------ORDER CONFIRMATION-------------------");
}}}}}
if (bgtype[i].Contains(type[i])) should be changed to if (bgtype.Contains(type[i]))
Array.Contains, verifies if an item is contained within an Array, not an Array value. By asking if bgtype[i] contains type[i], you are asking if cheesburger contains tlc, which it doesn't, hence why it starts from the beginning. By verifying if bgtype contains type[i], you are asking if ["cheesburger", "tlc", "bbq"] contains tlc, which it does. I hope this was clear enough.
I'm new to programming and I've got confused on how to display the index number of a value in an array. I want to be able to type a random number and if the number I have entered is in the array, then it should tell me what the position (index) of the number is within the array.
For example if I enter the number 6, and 6 is in my array and it's index is 4, then the output should be "That number exists, it is positioned at 4 in the array". I've tried to do this but my code is the reverse of this, for example if I type in 6, then it looks for index 6 and outputs the number corresponding to index 6.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace searcharray
{
class Program
{
static void Main(string[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
for (int i = 1; i <= n; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.ReadLine();
Console.WriteLine("Enter a number: ");
int b = Convert.ToInt32(Console.ReadLine());
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + a[b]);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
Console.WriteLine();
Console.ReadLine();
}
}
}
You can use Array.IndexOf(gives you the index of given value in Array) instead of a[b] like this:
if (a.Contains(b))
{
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
You need to use Array.IndexOf() like below:
Console.WriteLine("That number exists and the position of the number is: " + Array.IndexOf(a, b));
Array.IndexOf returns -1 if the item dont exists in the array
var itemIndex = Array.IndexOf(a, b);
if (itemIndex != -1)
{
Console.WriteLine("That number exists and the position of the number is: " + itemIndex);
}
else
{
Console.WriteLine("The number doesn't exist in the array");
}
IN C# i am trying to solve a problem :
Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
The only thing left is:
On the second line you will receive N numbers separated by a whitespace.
I am unable to get this working. I have tried with Split but it keeps breaking. Can someone help?
Example:
Input
5
2 1 1 6 3
Output
yes 6
static void Main(string[] args)
{
long N = long.Parse(Console.ReadLine());
long[] array = new long[N];
long ODD = 1;
long EVEN = 1;
for (int i = 0; i < N; i++)
{
array[i] = int.Parse(Console.ReadLine());
if ((i + 1) % 2 == 0)
{
EVEN *= array[i];
}
else
{
ODD *= array[i];
}
}
if (EVEN == ODD)
{
Console.WriteLine("yes" + " " +
ODD);
}
else
{
Console.WriteLine("no" + " " + ODD + " " + EVEN);
}
}
Read from console input and keep it to an string array, Then convert each array element to long and apply the Odd Even logic like below:
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputArray = input.Split(' ');
long element;
long odd = 1;
long even = 1;
foreach (var i in inputArray)
{
element = long.Parse(i);
if (element % 2 == 0)
{
even *= element;
}
else
{
odd *= element;
}
}
Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);
if (odd == even)
{
Console.WriteLine("ODD == EVEN \n");
Console.WriteLine("Yes" + " " + odd);
}
else
{
Console.WriteLine("ODD != EVEN \n");
Console.WriteLine("No" + " " + odd + " " + even);
}
Console.ReadKey();
}
long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values
foreach(long x in nums.Where(a => a%2 == 1))
oddProduct *= x; // multiply odd ones
foreach(long x in nums.Where(a => a%2 == 0))
evenProduct *= x; // multiply even ones
A few weeks ago I began studying a c# beginners course, I got stuck on Arrays.
I do not want the complete answer for my problem, I want the tools or links to figure it out of myself
I´am trying to make a console Application that acts like a "Weather Station".
The program should take user input as an array on how many measurements have been made (Done). After that the user will enter the degrees in an loop (Done)
The program should write out all the measurements and the average measurement.
I can calculate the average but don't know how to print the results
I've come this far...
Console.WriteLine("How many measurements have you done");
string str = Console.ReadLine();
int size = Convert.ToInt32(str);
int[] temperatur = new int[size];
for (int i = 0; i < temperatur.Length; i++)
{
Console.WriteLine("Enter temperature " + i + ": ");
str = Console.ReadLine();
int element = Convert.ToInt32(str);
temperatur[i] = element;
}
Console.WriteLine("");
int sum = 0;
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " +
sum / temperatur.Length);
Seeing as you state that the only problem you are having is 'print out all the measurements', all you have to do is add an additional Console.WriteLine() to the existing for loop you already have. You will also to have to add braces. As such:
int sum = 0;
for (int i = 0; i < temperatur.Length; i++){
sum = sum + temperatur[i];
Console.WriteLine("Measurement {0} is {1}", i+1, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
You might not recognise that Console.WriteLine(), but it's basically a neat way of formatting your output using placeholders. The {0} will be replaced with the first value provided, the {1} with the second.
EDIT: MSDN documentation on Console.WriteLine() and also String.Format
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Change this to :
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0} is {1}", i, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
If you want to do it in the same for:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0}", temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
In another statement:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
}
temperatur.ForEach(x => Console.WriteLine("Temperature {0}", x));
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
...
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Console.ReadLine();
In the end type Console.ReadLine();