For Loop C#-- Adding - c#

How to find a loop that will successfully add 5 numbers. Here is the homework question.
Add a loop that will take a number input by the user and add it to a running total (the ReadLine() method will get a string from the user).
You’ll notice in the above code there are two variables declared.
One is total of the double data type which will have the total of the 5 entered numbers.
The other is a temp string variable to take the user input, convert to double, and then add the converted value to the total.
Using what you have learned in case 2 about taking input and converting to an int32, take the input and convert ToDouble() instead of int32.
total = total + Convert.ToDouble(temp);
case "3":
double total = 0;
string temp = "0";
Console.WriteLine("Enter 5 numbers here for addition \n");
for (total = 0; total <= 6; total++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
break;
When I tried entering this in, the debugging program exited out and gave me a set number.
It keeps saying that string will not convert to integer when I tried entering string as an expressions instead.
Here is the result I am trying to get.
1
2
3
4
5
Total:15 This is the answer I am trying to get.

You set temp to be an empty string and then it never becomes a number, hence you can't cast it to a double....
Convert.ToDouble(input) won't do anything either as you need to store the value, i.e.
double result = Convert.ToDouble (input)
The loop is wrong because you only ever take one input - you need to put your Console.ReadLine in your loop and then append what the user inputs to your total.

you probably need to do:
int index=Convert.ToDouble(input);
and use in the for loop something like
for(int i=0;i<index;i++)
since as it stands you retrieve an input but don't use it, in for loop in fact you're trying to set it to zero -> for(input=0;....)
which can't be done since input is a string and not a number
in case 3 you're using total as an index and as the total variable in the calculation you can't do that
you need another variable to use as a index:
for (int i = 0; i<= 6; i++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}

Console.Write("Enter how many numbers you want to enter and sum up: ");
double n = double.Parse(Console.ReadLine());
double r;
double sum = 0;
for (int i = 0; i < n; i++)
{
Console.Write("{0} Enter number ", i);
r = double.Parse(Console.ReadLine());
sum += r;
Console.WriteLine(sum);
}

Related

How to take digits from two different numbers and form a new one

I have the following problem here:My input is several lines of 2 digit numbers and I need to make a new number using the second digit of the first number and the first of the next one.
Example:
int linesOfNumbers = Convert.ToInt32(Console.ReadLine());
for(int i = 0,i<linesOfNumbers,i++)
{
int numbers = Conver.ToInt32(Console.ReadLine());
//that's for reading the input
}
I know how to separate the numbers into digits.My question is how to merge them.
For example if your input is 12 and 21 the output should be 22.
I like oRole's answer, but I think they're missing a couple things with the example input that you provided in your comment. I'll also point out some of the errors in the code that you have.
First off, if you're only given the input 12,23,34,45, then you don't need to call Console.ReadLine within your for loop. You've already gotten the input, you don't need to get any more (from what you've described).
Secondly, unless you're doing mathematical operations, there is no need to store numerical data as ints, keep it as a string, especially in this case. (What I mean is that you don't store Zip Codes in a database as a number, you store it as a string.)
Now, onto the code. You had the right way to get your data:
var listOfNumbers = Console.ReadLine();
At that point, listOfNumbers is equal to "12,23,34,45". If you iterate on that variable as a string, you'll be taking each individual character, including the commas. To get each of the numbers to operate on, you'll need to use string.Split.
var numbers = listOfNumbers.Split(',');
This turns that list into four different two character numbers (in string form). Now, you can iterate over them, but you don't need to worry about converting them to numbers as you're operating on the characters in each string. Also, you'll need a results collection to put everything into.
var results = new List<string>();
// Instead of the regular "i < numbers.Length", we want to skip the last.
for (var i = 0; i < numbers.Length - 1; i++)
{
var first = numbers[i];
var second = numbers[i + 1]; // This is why we skip the last.
results.Add(first[1] + second[0]);
}
Now your results is a collection of the numbers "22", "33", and "44". To get those back into a single string, you can use the helper method string.Join.
Console.WriteLine(string.Join(",", results));
You could use the string-method .Substring(..) to achieve what you want.
If you want to keep int-conversion in combination with user input, you could do:
int numA = 23;
int numB = 34;
int resultAB = Convert.ToInt16(numA.ToString().Substring(1, 1) + numB.ToString().Substring(0, 1));
Another option would be to take the users input as string values and to convert them afterwards like that:
string numC = "12";
string numD = "21";
int resultCD = Convert.ToInt16(numC.Substring(1, 1) + numD.Substring(0, 1));
I hope this code snippet will help you combining your numbers. The modulo operator (%) means: 53 / 10 = 5 Rest 3
This example shows the computation of the numbers 34 and 12
int firstNumber = 34 - (34 % 10) // firstNumber = 30
int secondNumber = 12 % 10; // secondNumber = 2
int combined = firstNumber + secondNumber; // combined = 32
EDIT (added reading and ouput code):
boolean reading = true;
List<int> numbers = new ArrayList();
while(reading)
{
try
{
int number = Convert.ToInt32(Console.ReadLine());
if (number > 9 && number < 100) numbers.Add(number);
else reading = false; // leave reading process if no 2-digit-number
}
catch (Exception ex)
{
// leave reading process by typing a character instead of a number;
reading = false;
}
}
if (numbers.Count() > 1)
{
List<int> combined = new ArrayList();
for (int i = 1; i <= numbers.Count(); i++)
{
combined.Add((numbers[i-1] % 10) + (numbers[i] - (numbers[i] % 10)));
}
//Logging output:
foreach (int combination in combined) Console.WriteLine(combination);
}
As you mention, if you already have both numbers, and they are always valid two digit integers, following code should work for you.
var num1 = 12;
var num2 = 22;
var result = (num2 / 10)*10 + (num1 % 10);
num2/10 returns the first digit of second number, and num1 % 10 returns the second digit of the first number.
The % and / signs are your savior.
If you want the 'ones' digit of a number (lets call it X), simply do X%10 - the remainder will be whatever number is in the 'ones' digit. (23%10=3)
If, instead, the number is two digits and you want the 'tens' digit, divide it by ten. (19/10=1).
To merge them, multiply the number you want to be in the 'tens' digit by ten, and add the other number to it (2*10+2=22)
There are other solutions like substring, etc and many one have already given it above. I am giving the solution VIA LINQ, note that this isn't efficient and it's recommended only for learning purpose here
int numA = 12;
int numB = 21 ;
string secondPartofNumA = numA.ToString().Select(q => new string(q,1)).ToArray()[1]; // first digit
string firstPartofNumB = numB.ToString().Select(q => new string(q,1)).ToArray()[0]; // second digit
string resultAsString = secondPartofNumA + firstPartofNumB;
int resultAsInt = Convert.ToInt32(resultAsString);
Console.WriteLine(resultAsString);
Console.WriteLine(resultAsInt);

Do we need to subtract Convert.ToInt32(o) with 48 every time? When there is a need to minus and when its not?

int num = Convert.ToInt32(Console.ReadLine());
With above code I am getting the correct integer value and I am able to do operation on this number and getting the correct result.
But with this below code why Convert.ToInt32(o) method is not converting it to integer value. Why we need to minus with 48.
int[] numarr = number.ToString().Select(o => Convert.ToInt32(o)-48).ToArray();
If I am not subtracting with 48 I am not getting the correct integer value.
Please can anyone explain why this is? Is it required to do every time? Because somewhere else I calculated result without subtracting 48 and I got a correct result.
I am doing a program to print number of occurrences in a number.
Here is my code:
Console.WriteLine("Enter the number:");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number to search:");
int searchnumber = Convert.ToInt32(Console.ReadLine());
int cnt = 0;
int[] numarr = number.ToString().Select(o => Convert.ToInt32(o)-48).ToArray();
for (int i = 0; i < numarr.Length; i++)
{
Console.WriteLine(numarr[i]);
}
for (int i = 0; i < numarr.Length; i++)
{
if (numarr[i] == searchnumber)
{
cnt++;
}
}
Console.WriteLine("Number of occurence of given number is:{0}", cnt);
Because you are converting the number to a string, the integers you retrieve are actually Unicode code points of the characters in the string. According to the ASCII code table, the 0 character starts at position 48.
So you actually found a workaround to convert characters to their integer representation. If you just want to get the number in a less hacky way, you could use this answer, which uses the modulus operator. Or char.ToNumericValue on your original string, as Time Schmelter proposed in a comment.

How to get odd and even value from new int C#

Hello that is my homework from the course for begginers, and I have no idea how to take the first input i than the second, not the numbers typed but the simple i. e.g.
2
3
4
4
3
1
I want to separate them somehow. But with this code it only takes :
1
1
2
3
4
4etc..
And the source.
Console.Write("Enter number of the numbers: ");
int a = int.Parse(Console.ReadLine());
int[] numbers = new int[a];
int even = 1;
int odd = 1;
for (int i = 0; i < a; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
if (numbers[i] % 2 == 0)
{
even *= numbers[i];
}
else if (numbers[i] % 2 !=0)
{
odd *= numbers[i];
}
}
Console.WriteLine(odd);
Console.WriteLine(even);
The way your application is written, it expects a single number to be entered (followed by the Enter key) indicating how many numbers in total will be read.
Then, it loops that many times, expecting a single number (followed by the Enter key) to be input for each loop.
That should be fine and work well. However, if you want to enter all of the numbers at once, you will need to restructure things a bit.
You don't need numbers to be an array. You never reference the value after you store it. You can use just an integer.
You are multiplying your count rather than adding it, e.g.
even *= numbers[i];
should be
even++;
if you want to count the number of even numbers, or
even += numbers[i];
if you want to sum them.
Same for tracking the odd number count.

Error Reading User Input into Array

So I'm intentionally overcomplicating a homework assignment I was given because I was bored and wanted to learn more about c#. The original assignment is as follows:
"Compute the average of five exam scores ranging between 50 and 90. Declare and perform a compile-time initialization with the five values. Use a constant to define the number of scores. Display all scores and the average value formatted with no digits to the right of the decimal."
So I decided rather than just putting the 5 scores in, I'd allow the user to input them into an array and then calculate it from that.
Console.WriteLine("Enter 5 test scores between 50 and 90:");
int i = 0;
double total = 0;
double[] Scores;
Scores = new double[5];
while (i < 5)
{
Console.WriteLine("Input Score " + (i + 1) + ":");
String input = Console.ReadLine();
Scores[i] = double.Parse(input);
total += Scores[i];
i++;
}
Console.WriteLine("The average of the scores is: " + (total/5));
The issue is that the Scores[i] = double.Parse(input); is throwing an error saying that the input is in the wrong format. So the program won't even run to let me put IN an input, but it says the input format is incorrect.
Any suggestions? I'm probably missing something obvious.
EDIT: Ok, so what ended up working was changing the code to
Console.WriteLine("Input Score " + (i + 1) + ":");
Scores[i] = double.Parse(Console.ReadLine());
total += Scores[i];
i++;
Not sure what it actually changed but it seems to work pretty flawlessly!

Comparing in Array

There is something wrong with my code. I am teaching myself c# and one of the challenges in this chapter was to prompt the user for 10 numbers, store them in an array, than ask for 1 additional number. Then the program would say whether the additional number matched one of the numbers in the array. Now what I have below does work, but only if I enter in a comparison number that is less than 10 which is the size of the array.
I'm not sure how to fix it. I am not sure how to do the comparison. I tried a FOR loop first which kind of worked, but ran through the loop and displayed the comparison against all 10 numbers so you would get 9 lines of No! and 1 line of Yes!. I put in a break; which stopped it counting all 10 but if I entered the number 5 for comparison, then I would get 4 lines of No! and 1 of Yes!. The below has been the only way I could get it to work reliably but only as long as the number isn't out of the bounds of the array.
I can see why I get the error when the number is above 10, I just don't know what to use to compare it but still allow the user to enter in any valid integer. Any assistance would be great!
int[] myNum = new int[10];
Console.WriteLine("Starting program ...");
Console.WriteLine("Please enter 10 numbers.");
for (int i = 0; i <= 9; ++i)
{
Console.Write("Number {0}: ", i + 1);
myNum[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers ");
foreach (int i in myNum)
{
Console.Write("{0} ", i);
}
Console.WriteLine("");
Console.Write("Please enter 1 additional number: ");
int myChoice = Int32.Parse(Console.ReadLine());
Console.WriteLine("Thank you. You entered the number {0}.", myChoice);
int compareArray = myNum[myChoice - 1];
if (compareArray == myChoice)
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
Console.WriteLine("End program ...");
Console.ReadLine();
You were on the right track- you want to loop through the array in myNum and compare each element to the variable myChoice. If you don't want to print whether each element of the array is a match, create a new variable and use it to keep track of whether you've found a match or not. Then after the loop you can check that variable and print your finding. You'd usually use a bool variable for that- set it false to start, then true when you find a match.
bool foundMatch = false;
for (int i = 0; i < 10; i++) {
if (myNum[i] == myChoice) {
foundMatch = true;
}
}
if (foundMatch) {
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
If you include the System.Linq namespace (or if you change the type of myNum to be something that implements ICollection<T>, like List<T>), you can use myNum.Contains(myChoice) to see if the value myChoice matches one of the values in myNum. array.Contains returns a boolean that is true if the specified value is found in the array and false if it is not.
You can update your code to use this like so:
//int compareArray = myNum[myChoice - 1]; // This line is no longer needed
if (myNum.Contains(myChoice))
{
Console.WriteLine("Yes! The number {0} is equal to one of the numbers you previously entered.", myChoice);
}
else
{
Console.WriteLine("No! The number {0} is not equal to any of the entered numbers.", myChoice);
}
If you're looking for numbers that are definitely between 1 and 10, then before you use
int compareArray = myNum[myChoice - 1];
check if it's over the value of 10. For example:
while(myChoice > 10)
{
Console.Write("Please choose a number less than or equal to 10: ");
myChoice = Int32.Parse(Console.ReadLine());
}
The benefit of putting it inside a while loop instead of an if tag means that, when the user enters another number, the value of myChoice will be rewritten, and compared against. If they enter a number over 10, it'll keep responding Please choose a number less than or equal to 10. until the number they input is below or equal to 10:` Then, your program will continue.
However, if you want to compare it against the array, rather than put in a fixed number comparison, consider the following while loop:
while(myChoice > myNum.Length)
{
Console.Write("Please choose a number less than or equal to {0}: ", myNum.Length);
myChoice = Int32.Parse(Console.ReadLine());
}
This will work for any sized array then, without you having to change the while loops content. By using this system, you can then ensure that you won't get an IndexOutOfBounds exception, so long as you subtract 1 when using it as an index.
You are looking to compare a final, 11th value and trying to determine if its in an array of 10 previous entries?
Try:
for(int i = 0; i < array.length - 1; i++;)
{
If(array[i] == input)
return true;
}
return false;
You should be able to figure out how to implement this completely yourself, as you did want to do it as an exercise.
Edit: If someone wants to check this or complete it in correct syntax, go ahead. I posted this rough outline from a phone.

Categories