I have this code that lets you enter 4 values and it prints the highest value you entered.
I understand everything up until the second for loop, how does it print the highest value? I'm rather new to c# and this is part of a school assignment.
The part of code which is within "**" is what I don't really understand.
int[] inputNum = new int[4];
for(int i = 0; i < 4; i++)
{
Console.Write("Enter number: ");
inputNum[i] = int.Parse(Console.ReadLine());
}
**int inputMax = 0;
for(int i2 = 0; i2 < inputNum.Length; i2++)
{
if(inputNum[i2] > inputMax)
{
inputMax = inputNum[i2];
}**
}
Console.WriteLine($"Highest value number: {inputMax}");
The second loop goes over the numbers that were inputted in the first loop and for each iteration checks if the current number is larger than the previous maximum, and if it is, saves it in inputMax. Once the loop is done, you'll be left with the largest number in that variable.
To be honest, though, this problem doesn't really need both loops. If the only requirement is to input four numbers and print out the largest one, there's no need to save them to an array, and you could just perform this check on each number that's inputted.
Related
So this is a very simple code that i can for the love of me get right because of some small mistake but the point here is the first int the user gives is the amount of numbers you will give after it so i have made this but for some reason the program wants 1 more int than it should. Lets say i enter 3 at first. That should mean that it would take 3 ints after that and then print them and end the program but fore some reason if i enter 3 after that it wants 4. if i enter 4 after that it wants 5 and you get the point. I have tried changing the whole code but i think the problem is that i am just making it to long and to complicated. here is the code
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
int[] numbers = new int[ammount];
for(int i = 0; i < ammount; i++)
{
numbers[i] = Enters;
Enters = int.Parse(Console.ReadLine());
}
int ammountEntered = 0;
while(ammountEntered < ammount)
{
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
int ammount = int.Parse(Console.ReadLine());
int Enters = int.Parse(Console.ReadLine());
Take a moment to think about this. If the user enters amount = 1, what would Happen? You would first ask a number, then enter the loop one time, where it asks for another number. Why is it asking for another number in this case? Why not just skip the Enter variable and assign numbers inside the loop?
for(int i = 0; i < ammount; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
I would highly recommend reading eric lipperts article on How to debug small programs, since problems like this should be very easy to diagnose when stepping thru a program. You might also consider reading the coding convensions guide, local variables should for example use "camelCasing".
You might also consider using a foreach loop when printing variables:
foreach(var number in numbers){
Console.WriteLine(number);
}
I think i understand your code!
This is how i would do it, and do read my explanation down below aswell!
using System;
namespace Homework_PrPr
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you want to add to your array?");
int amount = int.Parse(Console.ReadLine());
int[] numbers = new int[amount];
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Numer {i+1}/{amount}"); // Just tells the user what I of number their adding. aka unessecary
int Enters = int.Parse(Console.ReadLine());
numbers[i] = Enters;
}
Console.WriteLine("\n");
int ammountEntered = 0;
while (ammountEntered < amount)
{
Console.Write($"Number {ammountEntered + 1}/{amount} : ");
Console.WriteLine(numbers[ammountEntered]);
ammountEntered++;
}
}
}
}
The first problem was that you asked for a unnesecary ReadLine in the beggining, so that i removed! Then inside you for-loop i switched the position of the adding, aswell as the one asking for a new number. I also added a few counters so that you can see a bit more in detail what the code does!
I am reposting this and edited it because I somehow can't see the answers for the old one.
Old Question: I want to make a program that generates 20 random numbers and search the array for a number. If one of the 20 random numbers was typed in the input the output should say "it is here". If the number is not in the ReadLine it should say"Yes it is there".I want to know how to make all 20 random numbers to be able to search. The code right now can only search the number on the right. Even if the input is one of the 20 random numbers except for the one on the right it would say "No it is not here."
NEW: I want to make this work by having 2 for loops one for creating an array and 1 for searching the number. I have edited this program to have 2 for loops but the output is strange as you see on the picture. Please help me by editing this code to complete work but still have 2 for loops again one for creating an array and 1 for searching the number.
public static void Main(string[] args)
{
Random random = new Random();
int[] myIntArray = new int[100];
for (int i=0; i <20; i++)
{
int x = random.Next(100);
myIntArray[i] = x;
Console.Write(myIntArray[i] + " ");
}
Console.Write("\nType a number to search for:");
bool isValueFound = false;
int z = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i <20; i++)
{
if (z==myIntArray[i])
{
Console.WriteLine("Yes it is there.");
}
else
Console.WriteLine("No it is not here.");
}
Console.ReadKey();
}
if (z==myIntArray[i])
{
Console.WriteLine("Yes it is there.");
}
else
Console.WriteLine("No it is not here."); <- The problem is here
}
At every number, if it is not a match you are printing 'No'. You should rather utilize isValueFound variable that you defined, You can do the following:
Don't print anything in the loop
When there is a match sent isValueFound to true, and break the loop
Outside the second loop, check the isValueFound to decide whether it is a found or not-found.
Additionally, you have a good opportunity to learn the Binary search as well. Happy coding!
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.
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.
In general, I know that int32 errors mean that a string value is not getting converted for the console program. I have seen a lot of code trying to find the answer to this including the following stackoverflow questions (seen much more but these were most useful:
How to sum up an array of integers in C#
Error CS1501: I'm not overloading a Sum() method correctly
CS0019 Operator cannot be applied to operands of type 'bool' and 'int'
That being said, this is also a homework assignment, titled UsingSum.cs as seen in a couple of these links. The difference in mine and these is that I am trying to make it so that the user enters however many Integers they want, then they are added up. The entire assignment is written in link 2....
The problem: I keep getting either 0 or System.Int32[] instead of the sum, despite the changes I make.
I cannot use Linq.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingSum
{
class Program
{
static void Main(string[] args)
{
int i;
int usrInput;
bool running = true;
//Enter Question Asking Loop w/ running=true
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int[] array1 = new int[0];
for (i = 0; i < array1.Length; i++)
{
usrInput = Convert.ToInt32(Console.ReadLine());
array1[i] = Convert.ToInt32(usrInput);
}
for (i = 0; i < array1.Length; i++)
{
Console.WriteLine(array1[i]);
}
/*If the user enters 999, calls Sum() and asks user to press any key to exit.
changes 'running' from true to false to exit the question loop*/
int exit = Convert.ToInt32 (Console.ReadLine());
if (exit == 999)
{
running = false;
Sum(array1);
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
public static void Sum(int[] numbers)
{
int [] sum1 = new int [0];
int sum2 = 0;
//Program accepts user responses with or w/o this loop...Int.32 error present both ways
//for (int a = 0; a < numbers.Length; ++a)
//sum1[a] = a;
//additional loop tried w/o the loop above/below;
//when used in the WriteLine w/ sum2 it displays 0, when used with sum1 or numbers Int.32 error
//Array.ForEach(sum1, delegate(int i) { sum2 += i; });
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum1);
/*tried changing 'numbers' to sum1, sum2, sum1.Convert.ToString(),sum2.Convert.ToString()
numbers.Convert.ToString(), also tried converting sum2 to a string.*/
}
}
}
Here is my final solution!
static void Main(string[] args)
{
AskUserForNumbers();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
public static List<Int32> AskUserForNumbers()
{
bool running = true;
List<int> numbers = new List<int>();
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999")
{
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0)
{
numbers.Add(inputValue);
}
else
{
Console.WriteLine("Please enter a whole number greater than 0");
}
}
return numbers;
}
}
}
A few problems:
First, you're always declaring your arrays as int[] array1 = new int[0];. This means that your code for actually getting the user input will never hit. Maybe you should try using a different collection type (List<int> maybe).
Second, you never perform any error checking when parsing the integer. That's bad practice. You should be using int.TryParse(string input, out result) to verify it was a valid number before adding it to the array.
Third, you are looping over the length of the array for inputs, meaning you will loop through however long the array is, and will continue doing so until the last input you have is the exit number (999).
Fourth, the input you get for the exit code is discarded (not added to the array to sum).
Just remember that programming is very procedural. There should be clear (logical) steps from point a to point b. In fact, imagine you are the program and you're asking a friend to give you numbers to sum up for him. Give him whatever information you think might be useful (such as the exit condition). Diagram the steps, and then try to translate that to code.
Edit: The main point is that an array (which has a fixed size) is NOT the tool for the job here. You're not actually filling the array with any data, so that's why the sum never happens. The culprit is here:
int[] array1 = new int[0]; // Instantiate a zero-length array? Can't hold any values
// Will never hit inside the loop here, because i < array1.Length (which is zero) will always be false.
for (i = 0; i < array1.Length; i++)
You need to either increase the size of the array to begin with (and either reuse the indexes or resize the array) or use an non-fixed collection (List, for example). Finally, when you pass array1 to the Sum method, array1 is empty because you declared it as a zero element array. That is why you always get a zero printing out. Like I said before, imagine you are the program, and actually run through all these steps, LINE BY LINE.
For example, you start in the loop. You prepare a miniature notebook to write down all the numbers your friend is telling you with no pages in it. For every page (and realize there are none) in the notebook, you ask your friend for a number. After you've gone through every page, you now go through every page again to read all the values he gave you (keep in mind he couldn't give you any numbers, since the notebook was empty). Then you ask him one more time for a number, and if it's 999 you tell him you're done and give him the sum of all the numbers you wrote down. If he didn't give you 999 as the number, you repeat the cycle.
Do you understand WHY it's not working now?
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
foreach (int i in numbers)
sum2 =+ i;
should become
foreach (int i in numbers)
sum2 += i;
Your problem is with your first for loop. You never will add items to your array because your
for (i = 0; i < array1.Length; i++)
Since you only add to your array1 array when you enter the loop, it won't ever increment. Since i = 0 and the array1.Length is 0 to start, i will never be less than the length.
Here is what I would suggest you do.
private static void Main(string[] args) {
var running = true;
var numbers = new List<int>();
//Enter Question Asking Loop w/ running=true
while (running) {
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999") {
//Display the numbers entered
foreach (var number in numbers) {
Console.WriteLine(number);
}
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0) {
//We have valid input, append it to our collection
numbers.Add(inputValue);
}
else {
//The user entered invalid data. Let them know.
Console.WriteLine("Please enter a whole number greater than 0");
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
You have several small mistakes here.
In your Sum method you are no longer using the array sum1, you're summing the values into sum2, but you're printing sum1. Your sum method should be (as described by Wiktor):
public static void Sum(int[] numbers)
{
int sum2 = 0;
foreach (int i in numbers)
sum2 += i;
Console.WriteLine("The sum of the values in your array is: " + sum2);
}
Also note that you used sum2 =+ i rather than sum2 =+ i. What that's saying is "set sum2 to be equal to the positive value of i" rather than, "add i to sum2.
Next, you have some issues in how you gather your input from the user. First off, arrays don't have a mutable size. The size that they have is fixed when they are created, and the array that you create to hold onto the values to sum up from the users is initialized to a size of 0. (int[] array1 = new int[0];) If you want to get a fixed number of values from the user you can put something other than 0 there for the array size, but based on the context it appears that you want the users to be able to add values until they enter 999 at which point you end. Since you don't know the size before hand you'll want to use a List<int> rather than an array, as you can just add items to it and it will magically grow to support the new items.
I would also suggest making a new method to get all of the values from the user, rather than embedding it in your Main method.
public static List<int> AskUserForNumbers()
{
List<int> numbers = new List<int>();
while(...)//todo determine end condition
{
string userInput = Console.ReadLine();
if(...)//todo determine if user is done
{
}
else
{
int nextNumber = ...;//todo parse user input
numbers.Add(nextNumber);
}
}
return numbers;
}
I'm not sure if it's a requirement for you to stop asking for numbers when the user enters 999 or if that's just what you did. if you have a choice, I would suggest using something different such as a blank line, 0, "quit", "exit", etc. 999 is a number that someone might want to sum.
As mentioned by SPFiredrake, it's best to use int.TryParse() to parse user input, that way if they enter a number that's not an int it won't crash, and you can tell the user that it was no good and they need to try again.