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
Related
The code is shown below. I would like to make it so a number less than 0 cannot be entered.
double[] Fastest = new double[GymRunners];
for (int i = 0; i < GymRunners; i++)
{
Console.WriteLine("Please enter the lane time for lane number {0}: ", i + 1);
Fastest[i] = Convert.ToDouble(Console.ReadLine());
}
Double.TryParse will help validate if the input is of type double.
This function will assign the input to the out variable if the input is parse-able to double.
the condition in do while will check that the input is positive.
So, try the following:
double[] Fastest = new double[GymRunners];
for (int i = 0; i < GymRunners; i++)
{
do
{
Console.WriteLine("Please enter the lane time for lane number {0}: ", i + 1);
Double.TryParse(Console.ReadLine(), out Fastest[i]);
} while (Fastest[i] <= 0);
}
Refer to this article for more about TryParse from Microsoft documentation
My end goal is to take a number like 29, pull it apart and then add the two integers that result. So, if the number is 29, for example, the answer would be 2 + 9 = 11.
When I'm debugging, I can see that those values are being held, but it appears that other values are also being incorrect in this case 50, 57. So, my answer is 107. I have no idea where these values are coming from and I don't know where to begin to fix it.
My code is:
class Program
{
static void Main(string[] args)
{
int a = 29;
int answer = addTwoDigits(a);
Console.ReadLine();
}
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + a[i];
}
return total;
}
}
As mentioned the issue with your code is that characters have a ASCII code value when you cast to int which doesn't match with the various numerical digits. Instead of messing with strings and characters just use good old math instead.
public static int AddDigits(int n)
{
int total = 0;
while(n>0)
{
total += n % 10;
n /= 10;
}
return total;
}
Modulo by 10 will result in the least significant digit and because integer division truncates n /= 10 will truncate the least significant digit and eventually become 0 when you run out of digits.
Your code is actually additioning the decimal value of the char.
Take a look at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
Decimal value of 2 and 9 are 50 and 57 respectively. You need to convert the char into a int before doing your addition.
int val = (int)Char.GetNumericValue(a[i]);
Try this:
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + (int)Char.GetNumericValue(a[i]);
}
return total;
}
Converted number to char always returns ASCII code.. So you can use GetNumericValue() method for getting value instead of ASCII code
Just for fun, I thought I'd see if I could do it in one line using LINQ and here it is:
public static int AddWithLinq(int n)
{
return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}
I don't think it would be particularly "clean" code, but it may be educational at best!
You should you int.TryParse
int num;
if (int.TryParse(a[i].ToString(), out num))
{
total += num;
}
Your problem is that you're adding char values. Remember that the char is an integer value that represents a character in ASCII. When you are adding a[i] to total value, you're adding the int value that represents that char, the compiler automatic cast it.
The problem is in this code line:
total = total + a[i];
The code above is equal to this code line:
total += (int)a[i];
// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.
To solve your problem, you must change that line by this:
total = (int)Char.GetNumericValue(a[i]);
// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.
You can see this answer to see how to convert a numeric value
from char to int.
At this page you can see the ASCII table of values.
public static int addTwoDigits(int n)
{
string number = n.ToString()
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total += Convert.ToInt32(number[i].ToString());
}
return total;
}
You don't need to convert the number to a string to find the digits. #juharr already explained how you can calculate the digits and the total in a loop. The following is a recursive version :
int addDigit(int total,int n)
{
return (n<10) ? total + n
: addDigit(total += n % 10,n /= 10);
}
Which can be called with addDigit(0,234233433)and returns 27. If n is less than 10, we are counting the last digit. Otherwise extract the digit and add it to the total then divide by 10 and repeat.
One could get clever and use currying to get rid of the initial total :
int addDigits(int i)=>addDigit(0,i);
addDigits(234233433) also returns 27;
If the number is already a string, one could take advantage of the fact that a string can be treated as a Char array, and chars can be converted to ints implicitly :
var total = "234233433".Sum(c=>c-'0');
This can handle arbitrarily large strings, as long as the total doesn't exceed int.MaxValue, eg:
"99999999999999999999".Sum(x=>x-'0'); // 20 9s returns 180
Unless the number is already in string form though, this isn't efficient nor does it verify that the contents are an actual number.
I am trying to do string manipulation. Here's my C# code :
static void Main(string[] args)
{
string input;
string output;
int length;
Console.WriteLine("input = ");
input = Console.ReadLine();
length = input.Length;
if ((input != "") || (length != 0))
{
Random randem = new Random();
int i = -1; //because I do not want the first number to be replaced by the random number
char[] characters = input.ToCharArray();
while (i < length)
{
int num = randem.Next(0, 9);
char num1 = Convert.ToChar(num);
i = i + 2; //so that every next character will be replaced by random number.. :D
characters[i] = num1; //*error* here
}
output = new string(characters);
Console.WriteLine(output);
}
For example:
User input : "i_love_to_eat_fish"
Desired output : "i2l4v1_9o5e8t7f8s2"
notice that the only unchanged character in
the char[] characters is : "i l v _ o e t f s". (desired output from the program)
I've already tried using this code, but still,
keep getting error at characters[i] = num1;
Am I on the right track?
I'm guessing the error you get is IndexOutOfRangeException this is because of the i = i + 2;. The while makes sure that i is less than length, but then adding 2 could result in it being more. Just add a check that it isn't beyond the length.
i = i + 2;
if(i < length)
characters[i] = num1;
Or just change to a for loop.
Random randem = new Random();
char[] characters = input.ToCharArray();
for(int i = 1; i < length; i += 2)
{
int num = randem.Next(1, 10); // max value is exclusive
char num1 = num.ToString()[0];
characters[i] = num1;
}
output = new string(characters);
Console.WriteLine(output);
Also as Shar1er80 points out you're currently converting the digit to the char that has the same ASCII value, and not the the actual characters that represent the digit. The digits 0-9 are represented by the the values 48-57. You can change the call to Random.Next to be:
int num = randem.Next(48, 58); // The upper bound is exclusive, not inclusive
char num1 = (char)num;
Or as Shar1er80 does it
int num = randem.Next(0,10) // Assumming you want digits 0-9
char num1 = num.ToString[0];
Also note that the max value for Random.Next is exclusive, so if you want to include the possibility of using a 9 you have to use an upper bound that is 1 greater than the greatest value you want.
Whenever you reach i = 17 you add 2 to i . That makes i = 19 with length of input equal to 18 that causes out of range exception.
The error you are getting is IndexOutOfTheRangeException, which explains everthing in itself.
It means that index you are feeding to array in the loop is going beyond its length-1 (as arrays have 0-based indexing)
So when you do i+2, you need to check if i+2 is not exceeding i.length-1 at any point of time; which does in your loop.
In general just check if you are supplying indexes between 0 and Array.Length-1
its because you start at index -1, and characters doesn't contain an index of -1.
EDIT: Sorry no the corrct answer is it must be while(i < length - 2)
Change this line
char num1 = Convert.ToChar(num);
To
char num1 = num.ToString()[0];
Then... Put
characters[i] = num1;
In an if block
if (i < length)
characters[i] = num1;
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I check if a number is a palindrome?
Hello All i want to make program to check whether palindrome number or not when user input the number. But my work does not work at all... Can you guys help me...
class Program
{
static void Main(string[] args)
{
int i = 0, j = 0 ;
int numbers =Convert.ToInt32( Console.ReadLine());
i = numbers % 10;
do
{
j = numbers / 10;
}
while (j < 10);
if (i == j)
{
Console.WriteLine(" this is palindrome number");
}
else
{
Console.WriteLine("not a palindrome");
}
The quickest way is to reverse the string and compare it to the original. You don't really need the integer conversion.
You may want to filter or correct the user's input by stripping leading zeroes (i.e. in 010). For example : string number = Convert.ToInt32(Console.ReadLine()).ToString();
You don't have to convert it to integer.
You can check it from the string.
Take the first character and the last character compare those .
Iterate the first pointer +1 and the last pointer -1 then compare.
Continue this process upto you are in middle of the string.
First of all by converting the digits to an Int32, the number of digits a user can enter are limited.
By using the modulo operation, the i variable will contain the last digit of the entered number.
By dividing the number by 10, j should eventually contain the first digit entered. However you aren't dividing it "until j is smaller than 10", but you're dividing it "while j is smaller than 10", effectively making the contents of j depend on the number of digits entered.
Even if you would fix the while condition, this code will only check the first and last digit, making it function only for 1, 2 and 3 digit numbers.
You'll need something like this:
bool isPalindrome = true;
string s = "300212003";
for (int i = 0; i < (s.Length / 2); i++)
{
if (s[i] != s[s.Length - i - 1])
{
isPalindrome = false;
break;
}
}
Console.WriteLine(isPalindrome);
It's faster than reverting a string and comparing it, only need O(n/2) operations.
a disscussion
palindrome check
C# code to check palindrome
You can follow these links .
#include<stdio.h>
#include<math.h>
void main()
{
long int n, num, rev = 0, dig;
clrscr();
printf("\n\n\t ENTER A NUMBER...: ");
scanf("%ld", &num);
n = num;
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
if (n == rev)
printf("\n\t GIVEN NUMBER IS A PALINDROME");
else
printf("\n\t GIVEN NUMBER NOT A PALINDROME");
getch();
}
Something is palindrome when you can read it either way, so when the reverse is the same as the original.
So just reverse your input string and compare it to the original.