How are strings terminated in C#? - c#

This program throws ArrayIndexOutOfBoundException.
string name = "Naveen";
int c = 0;
while( name[ c ] != '\0' ) {
c++;
}
Console.WriteLine("Length of string " + name + " is: " + c);
Why is it so?
If strings are not null-terminated. How strings are getting handled in C#?
How can I get the length without using string.Length property?
I'm confused here.!

C# does not use NUL terminated strings as C and C++ does. You must use the Length property of the string.
Console.WriteLine("Length of string " + name + " is: " + name.Length.ToString());
or by using formatters
Console.WriteLine("Length of string '{0}' is {1}.", name, name.Length);

public static void Main()
{
unsafe
{
var s = "Naveen";
fixed (char* cp = s)
{
for (int i = 0; cp[i] != '\0'; i++)
{
Console.Write(cp[i]);
}
}
}
}
// prints Naveen

In C/C++ string is stored in is a char array AFAIR without intelligence and behaviour. Therefore, to indicate that such array ends somewhere, one must have added \0 at the end.
On the other hand, in C#, string is a container (a class with properties and methods); as a side note you can assign null to its instantiated object. You don't need to add anything to it to indicate where it ends. The container controlls everything for you. As such, it also has iterator (or enumerator in C# i think). That means you can use foreach and LINQ expressions to iterate over it.
Having said that, you could use a simple counter in a code similar to this to get a length of a string:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LengthOfString
{
class Program
{
static void Main(string[] args)
{
string s = "abcde\0\0\0";
Console.WriteLine(s);
Console.WriteLine("s.Length = " + s.Length);
Console.WriteLine();
// Here I count the number of characters in s
// using LINQ
int counter = 0;
s.ToList()
.ForEach(ch => {
Console.Write(string.Format("{0} ", (int)ch));
counter++;
});
Console.WriteLine(); Console.WriteLine("LINQ: Length = " + counter);
Console.WriteLine(); Console.WriteLine();
//Or you could just use foreach for this
counter = 0;
foreach (int ch in s)
{
Console.Write(string.Format("{0} ", (int)ch));
counter++;
}
Console.WriteLine(); Console.WriteLine("foreach: Length = " + counter);
Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine();
Console.WriteLine("Press ENTER");
Console.ReadKey();
}
}
}

You are trying to access a character at an index which is not available according to name length. You may solve it this way:
string name = "Naveen";
int c = 0;
while (c < name.Length)
{
c++;
}
However there is no need to count the length of a string in c# this
way. You can try simply name.Length
EDIT: based on what #NaveenKumarV provide in comments if you want to check for \0 characters then as others said you may try ToCharArray method. Here is the code:
var result = name.ToCharArray().TakeWhile(i => i != '\0').ToList();

Related

Trying to sort a List with dynamic List Size, having Unhandled Exceptions

I'm trying to creat an algorithm who receive a list of user-defined size (dynamic list) but i keep having unhandled exceptions when trying to implement the algorithm.
The cleanest i found was this
using System.Linq;
using System.Collections.Generic;
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size;
List<string?> wordList = new() {};
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
I want the program to receive all the unsorted names written by the user and then reposition then in the List in a alphabetically sorted way.
First of all, if you want to declare an empty list, you can do it with:
List<string?> wordList = new List<string?>();
Then, A namespace cannot directly contain members such as fields or methods. Thats why you need to wrap the function by a class:
public class AnyClassName
{
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size - 1;
List<string?> wordList = new List<string?>();
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
}
Then, you need to call the function in main function:
using System;
using System.Linq;
using System.Collections.Generic;
public class AnyClassName
{
static void Sorter()
{
Console.WriteLine("Write the number of words the dictionary will have");
int Size = Convert.ToInt32(Console.ReadLine());
int ListEnd = Size - 1;
List<string?> wordList = new List<string?>();
while (Size>0)
{
Console.WriteLine("Write a term A");
string? item1 = "" ?? "1";
item1 = Console.ReadLine();
wordList.Add(item1);
Size--;
}
Console.WriteLine($"{wordList.Count()} terms");
Console.WriteLine(string.Join(" ", wordList));
string? last = wordList[ListEnd];
wordList.Sort();
Console.WriteLine(string.Join(" ", wordList));
}
public static void Main(string[] args)
{
Sorter();
}
}
A couple pointers, as pointed out in the comments of your original post (pun not intended):
Try to include any errors when stating that you are seeing errors.
Try to specify what you are actually looking for. Are you looking for a cleaner implementation? Are you looking for a fix to an error (if so, refer to the previous pointer)?
As for the direct answer to your question, I am assuming that you are looking for a cleaner implementation that doesn't result in errors during compilation. Here we go:
using static System.Int32;
List<string> ReadStringsFromConsole()
{
int numWords = 0;
string word = string.Empty;
List<string> words = new();
// Keep on reading until we get a valid number
while (numWords < 1)
{
Console.Clear();
Console.Write("How many words would you like to enter? ");
bool unused = TryParse(Console.ReadLine(), out numWords); // TryParse to make sure we don't get an exception
}
// Keep on reading until we get a valid word, at which point it is added to the list
// numWords is only decremented if we were able to successfully add the word to the list
do
{
Console.Clear();
Console.Write("Enter a word: ");
word = Console.ReadLine() ?? string.Empty;
if (word == string.Empty) continue;
words.Add(word);
numWords--;
} while (numWords > 0 && word != string.Empty);
words.Sort();
return words;
}
List<string> words = ReadStringsFromConsole();
Console.WriteLine(string.Join(" ", words));
Console.ReadKey();

How do I search an int array vs a string array by comparing it to user input

How do I check if user input matches a number in an array?
I've learned to compare user input or search using a string array, however doing the same with an int array is not working for me.
zipCode[i] = 0;
int userZip = 0;
do
{
Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
Console.WriteLine( );
Console.WriteLine( "Enter a 0 to exit the program" );
userZip = 0;
if ( userZip == zipCode[i] )
{
found = true;
if ( found )
{
Console.WriteLine( "We support zip code {0}", userZip ); ;
}
else
{
Console.WriteLine( "We do not support", userZip );
}
}
} while ( userZip != 0 );
Console.ReadLine( );
How do I check if user input matches a number in an array?
using System;
using System.Collections.Generic;
public class Program
{
static List<string> _zipCodes;
static Program()
{
_zipCodes = new List<string>() { "80205", "80225", "80210" };
}
static void Main(string[] args)
{
string userZip = string.Empty;
do
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area.");
Console.WriteLine();
Console.WriteLine("Enter a -1 to exit the program");
userZip = Console.ReadLine();
if (_zipCodes.Contains(userZip))//<---------------THAT WAY
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support zip code {0}", userZip);
}
} while (userZip != "-1");
}
}
How do I check if user input matches a number in an array?
I will answer this question, though I can't post an example using your sample code since it's incomplete and it's not exactly clear what it's supposed to do.
First, let's create a method that gets an integer from the user. This method will continually loop until the user enters a valid integer:
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Now, we can use that method to get the zip code from the user:
int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");
Now I'm assuming you have an array of zip codes that are supported. Perhaps something like:
private static int[] GetSeattleZipCodes()
{
return new []
{
98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
};
}
So, now we have an int user input, and an int[] of valid zip codes, so to see if the array of valid zip codes contains the user zip code, we can just use the Contains method:
int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);
TheFastCat beat me, but:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };
static void Main(string[] args)
{
Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
do {
// Read next line
string userZip = Console.ReadLine().Trim();
// Exit program?
if (userZip == "0")
break;
// Validate input
if (userZip.Length != 5)
{
Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
continue;
}
int n;
bool isNumeric = int.TryParse(userZip, out n);
if (!isNumeric)
{
Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
continue;
}
// Finally, see if our zip code matches a zip code in the list
bool found = zipCodes.Contains(userZip);
if (found)
{
Console.WriteLine("We support zip code {0}", userZip); ;
}
else
{
Console.WriteLine("We do not support " + userZip);
}
} while (true);
Console.WriteLine("Done: exiting program");
}
}
}
Note:
Initializing the list
Validating the input
Using IEnumerable.Contains() ... without necessarily messing with LINQ.
Use of "break" and "continue" to control the loop, without necessarily needing an extraneous variable.
An int array is Enumerable<int>, so you could just use Contains(): https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2
TheFastCat and Rufus L done great job.
I just want to add an example. Using 'var' datatypes makes things easy and durable as well in C#
This example demonstrates both 'int' and 'string' using var datatypes in both cases. Good luck haberjin.
static void Main(string[] args)
{
//var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List
//var userZip = "";
var userZip = 0;
do
{
Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");
//userZip = Console.ReadLine(); // Enable to receive userZip as a string
userZip = int.Parse(Console.ReadLine()); // receive userZip as an int
if (ZipCodes.Contains(userZip))
{
Console.WriteLine("We support zip code {0}", userZip);
}
else
{
Console.WriteLine("We do not support", userZip);
}
//} while (userZip != "0");
} while (userZip != 0);
}

How to run-length encode 'EEDDDNE' to '2E3DNE'?

Explanation: The task itself is that we have 13 strings (stored in the sor[] array) like the one in the title or 'EEENKDDDDKKKNNKDK'
and we have to shorten it in a way that if there's two or more of the same letter next to eachother then we have to write it in the form of 'NumberoflettersLetter'
So by this rule, 'EEENKDDDDKKKNNKDK' would become '3ENK4D3K2NKDK'
using System;
public class Program
{
public static void Main(string[] args)
{
string[] sor = new string[] { "EEENKDDDDKKKNNKDK", "'EEDDDNE'" };
char holder;
int counter = 0;
string temporary;
int indexholder;
for (int i = 0; i < sor.Length; i++)
{
for (int q = 0; q < sor[i].Length; q++)
{
holder = sor[i][q];
indexholder = q;
counter = 0;
while (sor[i][q] == holder)
{
q++;
counter++;
}
if (counter > 1)
{
temporary = Convert.ToString(counter) + holder;
sor[i].Replace(sor[i].Substring(indexholder, q), temporary); // EX here
}
}
}
Console.ReadLine();
}
}
Sorry I didn't make the error clear, it says that :
"The value of index and length has to represent a place inside the string (System.ArgumentOutOfRangeException) - name of parameter: length"
...but I have no clue what's wrong with it, maybe it's a tiny little mistake, maybe the whole thing is messed up, so this is why I'd like someone to help me with this D:
(Ps 'indexholder' is there because i need it for another exercise)
EDIT:
'sor' is the string array that holds these strings (there are 13 of them) like the one mentioned in the title or in the example
You can use regex for this:
Regex.Replace("EEENKDDDDKKKNNKDK", #"(.)\1+", m => $"{m.Length}{m.Groups[1].Value}")
Explanation:
(.) matches any character and puts it in group #1
\1+ matches group #1 as many times can it can
Shortening the same string inplace is more difficult then construction a new one while iterating the old one char by char. If you plan to iteratively add to a string it is better to use the StringBuilder - class instead of adding directly to a string (performance reasons).
You can streamline your approach by using IEnumerable.Aggregate function wich does the iteration on one string for you automatically:
using System;
using System.Linq;
using System.Text;
public class Program
{
public static string RunLengthEncode(string s)
{
if (string.IsNullOrEmpty(s)) // avoid null ref ex and do simple case
return "";
// we need a "state" between the differenc chars of s that we store here:
char curr_c = s[0]; // our current char, we start with the 1st one
int count = 0; // our char counter, we start with 0 as it will be
// incremented as soon as it is processed by Aggregate
// ( and then incremented to 1)
var agg = s.Aggregate(new StringBuilder(), (acc, c) => // StringBuilder
// performs better for multiple string-"additions" then string itself
{
if (c == curr_c)
count++; // same char, increment
else
{
// other char
if (count > 1) // store count if > 1
acc.AppendFormat("{0}", count);
acc.Append(curr_c); // store char
curr_c = c; // set current char to new one
count = 1; // startcount now is 1
}
return acc;
});
// add last things
if (count > 1) // store count if > 1
agg.AppendFormat("{0}", count);
agg.Append(curr_c); // store char
return agg.ToString(); // return the "simple" string
}
Test with
public static void Main(string[] args)
{
Console.WriteLine(RunLengthEncode("'EEENKDDDDKKKNNKDK' "));
Console.ReadLine();
}
}
Output for "'EEENKDDDDKKKNNKDK' ":
'3ENK4D3K2NKDK'
Your approach without using the same string is more like this:
var data = "'EEENKDDDDKKKNNKDK' ";
char curr_c = '\x0'; // avoid unasssinged warning
int count = 0; // counter for the curr_c occurences in row
string result = string.Empty; // resulting string
foreach (var c in data) // process every character of data in order
{
if (c != curr_c) // new character found
{
if (count > 1) // more then 1, add count as string and the char
result += Convert.ToString(count) + curr_c;
else if (count > 0) // avoid initial `\x0` being put into string
result += curr_c;
curr_c = c; // remember new character
count = 1; // so far we found this one
}
else
count++; // not new, increment counter
}
// add the last counted char as well
if (count > 1)
result += Convert.ToString(count) + curr_c;
else
result += curr_c;
// output
Console.WriteLine(data + " ==> " + result);
Output:
'EEENKDDDDKKKNNKDK' ==> '3ENK4D3K2NKDK'
Instead of using the indexing operator [] on your string and have to struggle with indexes all over I use foreach c in "sometext" ... which will proceed char-wise through the string - much less hassle.
If you need to run-length encode an array/list (your sor) of strings, simply apply the code to each one (preferably by using foreach s in yourStringList ....

Using a 'foreach' loop with stringArray in C#

I am writing a program which should display the items from an array in a foreach loop.
I wanted to change the elements of the array by adding a string "sad" to each element, but when run the program the array stays the same.
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string[] stringArray = {"hey", "Tom"};
for (int i = 0; i < stringArray.Length; i++ )
{
stringArray[i] += " dad";
Console.WriteLine(stringArray[i]);
}
Array.Resize(ref stringArray, stringArray.Length + 1);
// Add bob to the last element of the array
stringArray[stringArray.Length - 1] =" bob";
foreach (string s in stringArray)
{
string b = s + "sad";
Console.WriteLine(s);
//Console.WriteLine(stringArray);
}
}
}
}
foreach (string s in stringArray)
{
string b = s + "sad";
// ...
}
Here you are creating a new string, completely unrelated to the string in the string-array. You haven't changed the old string (you can't; strings are immutable). You then simply drop this new longer string on the floor - you aren't updating the array etc.
Try instead something like:
for(int i = 0 ; i < stringArray.Length ; i++)
{
stringArray[i] = stringArray[i] + "sad";
}
This replaces every item in the array with a new string. Note that you can't update a list/collection/array etc while iterating with foreach - that can break the iterator. Hence the for loop instead.
Apart from what Chris said, you could simply use LINQ to achieve what you want:
string[] newStringArray = stringArray
.Select(s => s + "sad")
.ToArray();
string b = s + "sad";
Console.WriteLine(s);
//Console.WriteLine(stringArray);
At no point in your code do you alter values in the array. You create a new string from each value in the array, concatenated with the string "sad".
Solution
You can not alter a for-each variable. You'll get a message like:
Cannot assign to 's' because it is a 'foreach iteration variable'.
Instead, settle for a simple for loop.
for(int x = 0; x < stringArray.length; x++)
{
stringArray[x] = stringArray[x] + "sad";
}
Look at this part of the code:
string b = s + "sad";
Console.WriteLine(s);
You are concatenating the string in s with the string "sad", and storing in the variable b. Then you display the content of the variable s. If you would display the content of the variable b isntead, there would be a sad at the end of each string.

reading two integers in one line using C#

i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.

Categories