Ask user to print out the amount of number they want c# - c#

I am having a bit issue with how I have to logically think for my code.
What I want to do is have the user type in how many numbers they want and then ask them where they want that sequence of numbers to start. Then I would print out the numbers. So if the user typed in 7 and then 4 the result would be 4 5 6 7 8 9 10.
Here is my code so far
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
for(int counts = userIntStart; userIntStart <= userInInt; userIntStart++)
{
Console.WriteLine(userIntStart);
}
I realized after doing this for loop that it would just be incrementing the starting number up until the userInInt which is not what I want. I've been spending a while trying figure out what else I need.
Thank you

The name you give to variables is important for the understanding of the code and makes it easier to think about it. userInInt does not reflect the purpose of the variable.
Console.Write("How many integers do you want to print? ");
int count = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
int start = Int32.Parse(Console.ReadLine());
Often i is used as loop variable, because in math it is used as index. You have different choices as how you can formulate the loop. The most typical is
for (int i = 0; i < count; i++)
{
Console.WriteLine(start + i);
}
But you can also add start to the loop variable start value and to the count.
for (int i = start; i < count + start; i++)
{
Console.WriteLine(i);
}
You can even increment more than one variable:
for (int i = 0; i < count; i++, start++)
{
Console.WriteLine(start);
}

Change your for loop as below
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
for(int counts = userIntStart; counts < userIntStart + userInInt; counts++)
{
Console.WriteLine(counts);
}
The problem to your initial code is that your for loop is wrong, first you should assign to counts the initial value, then you should provide correct exit condition in the second arg and third arg is increment step which is 1, have a look at for loop syntax here.

In your code first you need to use the correct variable name in increment step(++). Secondly please note, you need to use a separate variable to keep track of number of integers. In my case, I am using variable 'i' for that. Hopefully it will help.
int userInInt, userIntStart;
Console.Write("How many integers do you want to print? ");
userInInt = Int32.Parse(Console.ReadLine());
Console.Write("What is the first integer you want printed? ");
userIntStart = Int32.Parse(Console.ReadLine());
int i = 0;
for (int counts = userIntStart; i<userInInt; counts++,i++)
{
Console.WriteLine(counts);
}
Console.ReadLine();

Related

Why doen't the smallest number from user input gets added to the list?

There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )

Problems with loop

I'm still in the learning stages of C# and I need some help with my program.
My program is supposed to work like this, I have 6 salesmen, and in the console I will write information about them(name, sold items etc). How can I make it loop 6 times (one for each salesmen)?
for (int i = 0; i < 6; i++) (Couldn't come up with more than this)
{
salesmen[] seller = new salesmen[6];
//Salesmen name
Console.WriteLine("Enter name: ");
salesmen[0].namn = System.Console.ReadLine();
//Birth certificate
Console.WriteLine("Enter birth certificate: ");
salesmen[0].birthvertificate = Console.ReadLine();
//Enter district
Console.WriteLine("Enter district: ");
salesmen[0].district = Console.ReadLine();
//Enter solditems
Console.WriteLine("Enter solditems: ");
salesmen[0].solditems = int.Parse(Console.ReadLine());
//Calculates what level each salesmen has reached
if (salesmen[0].solditems < 50)
salesmen[0].level = 1;
if (salesmen[0].solditems >= 50 && salesmen[0].solitems < 99)
salesmen[0].level = 2;
if (salesmen[0].solitems >= 100 && salesmen[0].solditems < 199)
salesmen[0].level = 3;
if (salesmen[0].solditems > 199)
salesmen[0].level = 4;
Is the code you provided the full code you are using? After quickly glancing at it, I noticed that your array declaration is inside the for loop, initializing the array 6 times with an empty one.
And as #Drenguin stated, you should use an index (in this case i) to modify the right salesman.
I also noticed that you wrote
salesmen[0].namn
instead of
salesmen[0].name
and although your code works, the correct spelling might be more readable.
You are only changing the salesmen[0]. In order to use the loop replace all salesmen[0] with salesmen[i].

How to go about storing multiple values from a loop, and displaying asterisks based on input

This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );

C# program where size of array index and elements are from user input and then search for a specific element

I'm trying to create a program where the size of array index and its elements are from user input.
And then the program will prompt the user to search for a specific element and will display where it is.
I've already come up with a code:
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main(String [] args)
{
int a;
Console.WriteLine("Enter size of index:");
a= int.Parse(Console.ReadLine());
int [] index = new int [a];
for (int i=0; i<index.Length;i++)
{
Console.WriteLine("Enter number:");
index[i]=int.Parse(Console.ReadLine());
}
}
}
}
The problem with this is that I can't display the numbers entered and I don't have any idea how to search for an array element.
I'm thinking of using if statement.
Another thing, after entering the elements the program should display the numbers like Number 0 : 1
Is this correct: Console.WriteLine("Number"+index[a]+":"+index[i]);?
And where should I put the statement? after the for loop or within it?
You're on the right track. Look carefully at how you stuffed values into the array, and you might find a clue about "how to search for an array element" with specific value. This is a core introductory algorithm, so no shortcuts! You need to find the answer on your own :-).
What is the last line Console.WriteLine(index[i]);? It seems like you are using the loop variable outside the loop.
To display entered numbers (ie. if I understand well, the numbers in the array), you have just to walk through the array like this:
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
Since you want display numbers only after every number is entered, you may put this code only after finishing the loop where the user is entering the numbers:
// The user is entering the numbers (code copied from your question).
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("Enter number: ");
index[i] = int.Parse(Console.ReadLine());
}
// Now display the numbers entered.
for (int i = 0; i < index.length; i++)
{
Console.WriteLine(index[i]);
}
// Finally, search for the element and display where it is.
int elementToSearchFor;
if (int.TryParse(Console.ReadLine(), out elementToSearchFor))
{
// TODO: homework to do.
}
To search for a number, you can either walk through the array again and compare each element until finding a good one, or use Linq TakeWhile() method. (I suppose that your intent is not to use Linq, so I don't provide any further detail in this direction.)
You could use Array.IndexOf,
int a;
Console.WriteLine("Enter size of Array:-");
a = int.Parse(Console.ReadLine());
int[] array = new int[a];
Console.WriteLine("Enter the Elements of the Array:-");
for (int i = 0; i < array.Length; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe Elemets of the Array are:-");
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Just try to break down what you've done and what you still need to do
Create a program where:
1) size of its array elements comes from user input (check)
2) array elements come from user input (check)
3) Prompt the user to search for a specific element (TODO)
4) Display where it is (TODO)
From the code you've written so far I would think you have most of what you need to do #3 & #4
An if statement may come into play when finding the location of the element the user specifies.

How to Fill an array from user input C#?

What would be the best way to fill an array from user input?
Would a solution be showing a prompt message and then get the values from from the user?
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.
If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use
string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
if(Int32.TryParse(s, out oneNum))
nums.Add(oneNum);
}
Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.
It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...
1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.
2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.
3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
to this:
for (int counter = 0; counter < 6; counter++)
{
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}
It makes the block clearer, and means you don't accidentally write:
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("----"); // This isn't part of the for loop!
4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:
bool keepGoing = true;
while (keepGoing)
{
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
keepGoing = false;
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
keepGoing = false;
break;
default:
Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
break;
}
}
5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:
// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();
Again, this is fairly advanced - don't worry about it for now!
C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.
If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:
using Microsoft.VisualBasic;
You can do the following:
List<string> responses = new List<string>();
string response = "";
while(!(response = Interaction.InputBox("Please enter your information",
"Window Title",
"Default Text",
xPosition,
yPosition)).equals(""))
{
responses.Add(response);
}
responses.ToArray();
Try:
array[i] = Convert.ToDouble(Console.Readline());
You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.
I've done it finaly check it and if there is a better way tell me guys
static void Main()
{
double[] array = new double[6];
Console.WriteLine("Please Sir Enter 6 Floating numbers");
for (int i = 0; i < 6; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
double average = sum / 6;
Console.WriteLine("===============================================");
Console.WriteLine("The Values you've entered are");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("===============================================");
Console.WriteLine("The average is ;");
Console.WriteLine(average);
Console.WriteLine("===============================================");
Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
string answer = Console.ReadLine();
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
break;
}
}
Add the input values to a List and when you are done use List.ToArray() to get an array with the values.
of course....Console.ReadLine always return string....so you have to convert type string to double
array[i]=double.Parse(Console.ReadLine());
readline is for string..
just use read

Categories

Resources