I have developed a program in c# which is doing "Insertion Sort", the code takes in a max value for the elements and the values of the elements and then one by one shows the steps of sorted values.
Code:
static void insertionSort(int[] ar)
{
for (int i = 1; i < ar.Length; i++)
{
int temp = ar[i];
int j = i - 1;
while (j >= 0 && ar[j] > temp)
{
ar[j + 1] = ar[j];
foreach (int val in ar)
Console.Write(val + " ");
Console.WriteLine();
j--;
}
}
}
static void Main(String[] args)
{
int ar_size;
ar_size = Convert.ToInt32(Console.ReadLine());
int[] ar = new int[ar_size];
for (int i = 0; i < ar_size; i++)
{
ar[i] = Convert.ToInt32(Console.Read());
}
insertionSort(ar);
Console.ReadKey();
}
The Sample Input That I Give:
5
2 4 6 8 3
The Output That Comes:
Can anyone explain me why is this happening!
Any help would be greatly appreciated! :)
Apart from the problems with your sort itself, the reason for the strange numbers in your result is that you use Console.Read very wrong. It returns the ASCII value of the character entered by the user. Furthermore, it will return the ASCII values for all entered characters, not only for the numbers.
So, the first call to Console.Read() will return 50 (ASCII value of '2').
The second call will return 32 (ASCII value of a space).
The third call will return 52 (ASCII value of '4').
etc.
To fix this, initialize ar like this:
var numbers = Console.ReadLine().Split(' ');
for (int i = 0; i < ar_size; i++)
ar[i] = Convert.ToInt32(numbers[i]);
Please note that this code lacks error handling. It will throw an exception in the followin circumstances:
The user entered anything besides spaces and numbers
The user entered less numbers than he specified in the first line
Related
This question already has answers here:
Read numbers from the console given in a single line, separated by a space
(7 answers)
Closed 2 years ago.
I'm new to C# programming. I was wondering how do you take multiple inputs in one line. My code:
using System;
namespace ArrayExercise01
{
class Program
{
static void Main(string[] args)
{
int arraySize = int.Parse(Console.ReadLine());
int[] ar = new int[arraySize];
int i;
for(i=0; i<arraySize; i++)
{
Console.Write("");
ar[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int arrayElement in ar)
{
sum += arrayElement;
}
Console.WriteLine(sum);
}
}
}
I get this output after running this:
3
2
3
4
9
But I wanted to do something like this (Multiple Input in single line):
3
2 3 4
9
Instead of:
ar[i] = int.Parse(Console.ReadLine());
You could:
foreach(string s in Console.ReadLine().Split()){
ar[i] = int.Parse(s);
i++;
}
Split without any arguments splits on whitespace, of which is one.. So the user is prompted for a string , and they could enter 1 or 1 2 3 4 5 or any combination (though there will be a problem if they enter more numbers than the remaining array can hold). The code splits them on the space, to become five strings of "1" "2" "3" "4" "5", and then the loop runs 5 times, and each one is parsed in turn and stored in an array index. The index i is incremented each time
As well as checking that i is still within the length of the array, it would be advisable to skip bad input too; take a look at int.TryParse, which returns a boolean false if the parsing did not succeed; if it returns false, don't add to the array/don't increment i
As per your requirement of "take multiple input on same line" you could do this as follow
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
but there is a problem while we take multiple input on same line as "we can't restrict user to enter only given size of numbers". To avoid this we can give informative message(or we can say validation message) to user as follows
while (numbers.Any() && ((numbers.Count() < arraySize) || (numbers.Count() > arraySize)))
{
Console.WriteLine("You have enter the numbers might be less than or greater than given size");
Console.WriteLine("Please the numbers of given size");
numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
}
Finally, you can do sum as follows
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
//or you can use directly sum method as follows
//Console.WriteLine(numbers.Sum());
Program as follows
static void Main(string[] args)
{
int arraySize = int.Parse(Console.ReadLine());
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
while (numbers.Any() && ((numbers.Count() < arraySize) || (numbers.Count() > arraySize)))
{
Console.WriteLine("You have enter the numbers might be less than or greater than given size");
Console.WriteLine("Please the numbers of given size");
numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
}
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
//or you can use directly sum method as follws
//Console.WriteLine(numbers.Sum());
Console.WriteLine(sum);
Console.Read();
}
Results:
3
1 2
You have enter the numbers might be less than or greater than given size
Please the numbers of given size
1 2 3 4
You have enter the numbers might be less than or greater than given size
Please the numbers of given size
1 2 3
6
Try this, but be careful, inputting too many numbers will cause IndexOutOfRangeException.
for (int i = 0; i < arraySize; )
{
// first catch the input
string input = Console.ReadLine();
// split it by space
string[] everyNumber = input.Split(' ');
for (int j = 0; j < everyNumber.Length; j++)
{
// parse each number in string array
ar[i] = int.Parse(everyNumber[j]);
i++;
}
}
I want to create an algorithm that would identify if the user input is repeating or not. If it is repeating it will prompt the user a message if its not repeating it will continue the process.
public static class Program
{
public static void Main()
{
Console.WriteLine("input array of numbers: );
int[] array = new int[4];
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(array[i] == array[0])
{
Console.WriteLine("repeating inputs")
}
}
Console.WriteLine("Highest number is:" + array.MaxLenght);
Console.ReadLine();
}
}
Explanation: The user will be prompted by message "inter array of numbers:" then the user will now input the numbers. If the user inputs the same number or if the number was already inputted, the user will be prompted by a message something like "repeating inputs! Input another number". After the user input another number unique to the previously interred the program will continue and print out the largest number base on the inputs.
i'm not sure if I understood you correctly but this is what i can extrapolated from your post :
you want to get input from the user and check if it's repeating or not and then print the highest number (based on your Console.WriteLine("Highest number is:" + array.MaxLenght); )
this is how i'd approach it
Console.WriteLine("input array of numbers: ");
List<int> uniqueInts = new List<int>();
int[] array = new int[4];
for (int i = 0; i < 3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if (!uniqueInts.Contains(array[i]))
uniqueInts.Add(array[i]);
}
//getting the max number
//assuming the first number is the max
int max = uniqueInts[0];
for (int i = 1; i < uniqueInts.Count; i++)
{
if (max < uniqueInts[i])
max = uniqueInts[i];
}
Console.WriteLine("The highest number is : " + max);
There are a lot of assumptions that I'm making with this answer. I'm assuming you're struggling to get the value of the item prior to the current iteration considering you have if(array[i] == array[0]).
If that's the case, then simply change array[0] to array[i-1].
Wait! Before you do that, you need to add a check to make sure you aren't on the first iteration. If you don't, you'll get an exception thrown on the first iteration, because you'll be trying to grab array[-1], which isn't valid.
for(int i=0; i<3; i++)
{
array[i] = int.Parse(Console.ReadLine());
if(i > 0)
{
if (array[i] == array[i-1])
Console.WriteLine("repeating inputs")
}
}
Make these few changes, and I think you'll get what you're after.
I want to add up all numbers in a string, I am sure this can be done easy with a for loop.
I have:
int numbers = 1234512345;
for (int i = 0 ; i numbers.Length ; i++)
{
int total;
total = int [i];
}
But it won't work for a reason, I am puzzled a lot.
For one, the "string" you're trying to iterate over is an int. You probably meant something along the lines of
string numbers = "1234512345"
After that, there are several ways to do this, my favorite personally is iterating over each character of the string, using a TryParse on it (this eliminates any issues if the string happens to be alphanumeric) and totaling the result. See below:
static void Main(string[] args) {
string numbers = "1234512345";
int total = 0;
int num; // out result
for (int i = 0; i < numbers.Length; i++) {
int.TryParse(numbers[i].ToString(), out num);
total += num; // will equal 30
}
Console.WriteLine(total);
total = 0;
string alphanumeric = "1#23451!23cf47c";
for (int i = 0; i < alphanumeric.Length; i++) {
int.TryParse(alphanumeric[i].ToString(), out num);
total += num; // will equal 32, non-numeric characters are ignored
}
Console.WriteLine(total);
Console.ReadLine();
}
Like others have posted though, there are several ways to go about this, it's about personal preference most of all.
this should do what you want
int total = 0;
foreach(char numchar in numbers)
{
total += (int)char.GetNumericValue(numchar);
}
EDIT:
1 line solution:
int total = numbers.Sum(x=> (int)char.GetNumericValue(x));
PS: Why the downvotes?
I've the following code in c# visual basic 2010:
for (int i = 7; i > 0; i--)
{
Char star = '*';
string numbers = "765432" ;
//Console.WriteLine(star);
for (int a = 0; a < i; a++)
{
Console.Write(star);
}
for (int b = 0; b < i; b++)
{
numbers.TrimEnd(numbers[numbers.Length - 1]);
Console.Write(numbers);
}
Console.WriteLine();
}
Console.ReadLine();
I was expecting the outcome:
*765432
repeated on the screen 7 times, instead I get:
*****765432765432765432765432765432
****765432765432765432765432
***765432765432765432
**765432765432
*765432
(I can't display the full outcome because it doesn't come back properly on screen but it's basically the variables star and numbers displayed 7 times on line 1, 6 times on line 2 etc. until once in line 7)
My understanding is that the a and b variables declared in the for loops should dictate how many times the for loop is entered into, why are the star and numbers variables also being written 7 times then 6 times to match the number of times the loop is entered into? Especially when they are initialised as * and 765432?
This is the problem (I suspect, anyway - it's certainly a problem):
numbers.TrimEnd(numbers[numbers.Length - 1]);
Strings are immutable in .NET. TrimEnd doesn't change the existing string - it returns a reference to a new one. As highlighted in the documentation:
This method does not modify the value of the current instance. Instead, it returns a new string in which all trailing characters found in trimChars are removed from the current string.
You'd also be better off using Substring for simplicity to "remove" the last character:
numbers = numbers.Substring(0, numbers.Length - 1);
Or indeed Remove:
numbers = numbers.Remove(numbers.Length - 1);
... although this will actually fail on the 7th iteration as the string will be empty at this point. It's not really what you were trying to achieve, but I think you need to take a step back from it and think carefully about each step in the process.
TrimEnd returns a new string, it doesn't modify the original string. You have to assign it back to number. Strings are immutable.
number = numbers.TrimEnd(numbers[numbers.Length - 1]);
Check for string length before indexing its element. In your for loop you can add the condition like:
for (int b = 0; b < i && numbers.Length > 0; b++)
No. The 'a' for loop runs, outputting that many stars, and the 'b' for loop runs next, outputting that many strings. If you just want '*765432' to repeat 7 times, you need to change
for (int a = 0; a < i; a++)
{
Console.Write(star);
}
for (int b = 0; b < i; b++)
{
numbers.TrimEnd(numbers[numbers.Length - 1]);
Console.Write(numbers);
}
To
for (int a = 0; a < 7; a++)
{
Console.Write(star);
Console.Write(numbers);
}
And take out the parent loop; that's what is giving you the incrementingly shorter lines.
This produce the output you are expecting:
for (int i = 0; i < 7; i++)
{
Char star = '*';
string numbers = "765432" ;
Console.WriteLine(star);
Console.Write(numbers);
Console.WriteLine();
}
I was expecting the outcome: *765432 repeated on the screen 7 times
You never need to use TrimEnd() and multiple for loop in this situation.
public static void Main()
{
for (int i = 7; i > 0;i--)
{
char star = '*';
string numbers = "765432";
Console.WriteLine(star + numbers);
}
Console.ReadLine();
}
output:
*765432
*765432
*765432
*765432
*765432
*765432
*765432
int n;
int[] ar = new int[50];
Console.Write("Enter the size of array= ");
n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
ar[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
Console.WriteLine("AR["+i+"]="+ar[i]);
}
Console.Read();
As here you can see that when m entering the 09 or 08 its going to remove it and print the 9 and 8. And when same run on the c++ compiler then its print the 0 and 9 on different indices, why the compilers of both language doing behave like this? Why they do not reading it one digit?
The behavior of int.Parse(..) and other string to numeric parsing functions is to strip out any leading characters (zeros in this case) which are irrelevant to the numeric value.
If you wish to keep the leading zero then change the data type of your array to string.
Now that you've posted some code, here's a few suggestions (comments inline)
int n;
bool validNumber;
do {
validNumber = true;
Console.Write("Enter the size of array:");
if(!int.TryParse(Console.ReadLine(), out n)) // use TryParse instead of Parse to avoid formatting exceptions
{
Console.WriteLine("Not a number, please try again");
validNumber = false;
}
} while(!validNumber); // re-prompt if an invalid number has been entered
int[] ar = new int[n]; // declare the array after the size is entered - your code will break if the user enters a number greater than 50
// change to "string[] ar = new string[n];" if you want to keep the full value entered
for (int i = 0; i < n; i++)
{
bool valid;
do {
valid = true;
int num;
string value = Console.ReadLine();
if(int.TryParse(value, out num)) // again - use tryparse.
ar[i] = num; // change to "ar[i] = value;" if you're using a string array.
else {
Console.WriteLine("Please enter that again - not a number");
valid = false;
}
} while(!valid);
}
for (int i = 0; i < n; i++)
{
Console.WriteLine("AR["+i+"]="+ar[i]);
}
Console.Read();
Your array is storing integers, and since 01 and 1 have the same number value, we don't distinguish them.
You'll want to save them as strings, if you need to keep the prefix zeros.
An integer is an integer, not a string.
So 09 is the same as 9, is the same as 000000009.
They are all internally represented by the bit pattern 00000101 00000000 00000000 00000000 (at least on x86).
i think its better if you convert your array to string array and then perfrom the operation. Since when it comes to integer 09 and 9 has no difference the numeric values is what that matters. but when its a string its different so use string array to do the operation and if u have to just want to display it then string is better anyways. if u want integer then convert it into int, there are API available.
Console.Read*Line*() is different from cin>> .
so