I need to create a program that adding the user input to reach a target, as a result, is just like below.
I have to use 'While Loop' for this,
but it is difficult for me to use while loop...
Here is my code
Console.WriteLine("Enter Target Value: 6");
int total = 0;
int target = 6;
int i;
for (i = 1; i <= 4; i++)
{
Console.Write("Enter #{0}:\t", i);
total += Convert.ToInt32(Console.ReadLine());
}
while (total == target);
Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);
Console.ReadLine();
Could you please help me to find the problems?
Do you know what number the user will enter? No, you do not know. So you do not know how many numbers will it take to reach the sum as well.
Pick the right tool for the job.
For Loop
A "For" Loop is used to repeat a specific block of code a known number of times.
While Loop
A "While" Loop is used to repeat a specific block of code an unknown number of times,
Given the above 2 options, your pick should be a while loop since you do NOT know how many times you will need to ask the user to enter a number to reach the sum. It may be 1 or many, many times.
In C#, there is also the do while loop, which is to be used if you know you must do something at least once and possibly more, Therefore, for your case the best option would be to use do while.
You may read more on while loop, for loop, and do while.
Here is the complete example.
static void Main(string[] args)
{
try
{
int i = 0;
int number;
int input=0;
Console.WriteLine("Enter target number ");
number = int.Parse(Console.ReadLine());
while (input != number && input < number)
{
Console.WriteLine($"Enter number {i+1}");
input += int.Parse(Console.ReadLine());
i++;
}
Console.WriteLine($"It took {i} number to make the sum {number}");
}
catch (Exception e)
{
}
Console.ReadLine();
}
Your code is perfectly operational. I hope this helps:
Console.WriteLine("Enter Target Value: 6");
int total = 0;
int target = 6;
int i = 1;
while (i <= 4)
{
Console.Write("Enter #{0}:\t", i);
total += Convert.ToInt32(Console.ReadLine());
i++;
}
while (total == target);
Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);
Console.ReadLine();
Related
The Problem:
Imagine you are a developer and get a job in which you need to create a program for a teacher. He needs a program written in c# that calculates the average score of his students. So he wants to be able to enter each score individually and then get the final average score once he enters -1.
So the tool should check if the entry is a number and should add that to the sum. Finally once he is done entering scores, the program should write onto the console what the average score is.
The numbers entered should only be between 0 and 20. Make sure the program doesn't crash if the teacher enters an incorrect value.
Test your program thoroughly.
My solution to the problem :
static void Main(string[] args)
{
int digit = 0,sum=0,counter=0;
string x;
try
{
for (int i = 0; i <= counter; i++)
{
Console.WriteLine("Please Enter Score");
x = Console.ReadLine();
bool isParsable = Int32.TryParse(x,out digit);
if (isParsable)
{
if (digit >= 0 && digit <= 20)
{
Console.WriteLine("Valid Number");
sum += digit;
counter++;
Console.WriteLine($"Student number {counter} got {digit}");
}
else if (digit == -1)
{
Console.WriteLine($"Total sum is {sum}");
Console.WriteLine($"Total number of students is {counter}");
Console.WriteLine($"Average score of {counter} students is {sum / counter}");
break;
}
else
{
Console.WriteLine("Please enter a valid score");
}
}
Console.WriteLine("Please enter Numerical Values only");
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Unable to get results");
}
}
I'm new to C# and programming as a whole and i have a quick question to ask you guys, I've searched a bit but only found far too complicated examples for me to implement in my work so here goes:
int[] newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (int i = 0; i < newArray.Length; i++)
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
}
This is the first part of a bingogame im trying to write, but i can't understand why the names loop and i don't exist, should i make something static? Move some brackets around? Please help.
You need to wrap the entire for statement in braces, otherwise it will only execute the next line of code, which is just bool loop = true;.
for (int i = 0; i < newArray.Length; i++)
{ // <-- Add this
bool loop = true;
do
{
try
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
loop = false;
}
catch
{
Console.WriteLine("You may only enter numbers!");
}
} while (loop);
Console.Write("You entered the following numbers: ");
}
It's worth to mention about string.Join method to print all elements of the list.
Console.WriteLine("You entered the following numbers: ");
Console.WriteLine(string.Join(", ", newArray));
After using Parse/TryParse method, you don't need to use Convert.ToInt32 any more.
To validate number and be able to reenter it, it is much better to do 2 IF statements instead of using Constains method of Enumerable class.
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 25)
{
Console.WriteLine("You may only enter numbers from range 1-25!");
}
Make one single bracket right after your for cycle.
You're missing an open brace. This looks like homework so I'm not going to rewrite it for you. Take a closer look and work on the formatting and indentations. That will give you a clue as to were that missing brace should be.
Here is a nicer way to test for number input without the try/catch
var newArray = new int[7];
Console.WriteLine("Hello! Please enter 7 numbers between 1-25, press ENTER after each number. ");
for (var i = 0; i <= newArray.Length - 1; i++)
{
int number;
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("You may only enter numbers!");
}
newArray[i] = Convert.ToInt32(number);
}
Console.WriteLine("You entered the following numbers: ");
foreach (var t in newArray)
{
Console.WriteLine(t);
}
edit: for those who have answered, I apologize, I should have been more clear, the assignment REQUIRES use of the for loop per my professor.
I'm doing a small assignment for class and am having trouble breaking out of a for loop and prompting the user to enter a valid value. My code is set up thus far as:
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
for (int.TryParse(strInput, out input); input >= MINRANGE && input <= MAXRANGE; input--)
{
Console.WriteLine("{0,2} {1,5}", input, Math.Pow(input, 3));
}
The program displays everything I need it to correctly. When the user enters a value out of the range I have specified, I need to give them a short message and then break out of the loop and return to the beginning prompt. I think I need to use something like the following if statement:
if (input >= MAXRANGE || input <= MINRANGE)
{
Console.WriteLine("That is not a valid value, please try again.");
}
Perhaps with a break; following it? But I'm not sure how to use it inside of the for loop. I've tried placing it outside, but that doesn't get me back to the user prompt, but neither does placing it inside the loop, so I'm obviously doing something wrong.
You can use a while loop
int input;
while(!int.TryParse(Console.ReadLine(), out input) || input >= MAXRANGE)
{
Console.WriteLine("Not valid!");
}
Note that this may get the user "stuck" and a helpful message as to why it isn't valid would be nice
If for some bizarre reason you must use a for loop you can use the following but it is horrible code that I would never condone
int input;
for(;;)
{
if(int.TryParse(Console.ReadLine(), out input) && input < MAXRANGE)
break;
}
Its better to do the validation before entering the loop. Try this out.....
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
if (input > MAXRANGE || input < MINRANGE)
{
Console.WriteLine("That is not a valid value, please try again.");
}
else
{
for (int.TryParse(strInput, out input); input >= MINRANGE && input <=
MAXRANGE; input--)
{
Console.WriteLine("{0,2} {1,3}", input, Math.Pow(input, 3));
}
}
I would rewrite your code as follows. Creating a method for asking the input:
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
string strInput = AskInput();
while (!int.TryParse(strInput, out input)) /*while the number is invalid*/
{
Console.WriteLine("Your input is invalid. Try again.");
strInput = AskInput();
}
while (input >= MINRANGE && input <= MAXRANGE)
{
Console.WriteLine("{0,2} {1,3}", input, Math.Pow(input, 3));
input--;
}
Where AskInput is:
private static string AskInput()
{
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
return strInput;
}
for ([(fist) Initialization];
[(second)Condition];
[(third or exit the loop) Progression])
{
[(fourth) Loop's body -if we reached third than we got here ]
}
The for loop is constructed of three parts:
The initialization part which happens only once when the loop starts.
The condition evaluation part which happens for every iteration.
The indexer progression part which also happens for every loop.
The order is as follows:
Start Loop => init => CheckCondition => if OK Progress the indexer and execute loop's body, else the loop is done.
The initialization part happens just once, if you want it to happen foreach interation it should be inside the loop or in the conditional section of the loop instead.
Best practice would be to use a while loop when the number of iterations is unknown ahead, like in this case, when it's determined by user's input.
Not Homework..So I've got a simple console program to read exam scores and prints out the average and grade. So far it's the following:
public static void Main ()
{
int sum = 0;
int count = 0;
double average = 0;
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (scores != "-99") {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average);
Console.WriteLine(....more scores etc...);
Now I want to check for invalid entries with TryParse. I thought I'd stick in another while loop before the other and change the original one like this:
Console.WriteLine ("Enter all your exam scores one by one. When finished, enter -99");
string scores = Console.ReadLine ();
while (int.TryParse(scores, out numbers) == false){
Console.WriteLine("Please enter a valid integer")
scores = Console.ReadLine();
sum += int.Parse(scores);
count++;
}
while (scores != "-99" && int.TryParse(scores, out numbers) == true) {
sum += int.Parse (scores);
count++;
scores = Console.ReadLine ();
}
if (scores == "-99") {
average = sum / count;
if (average >= 90)
Console.WriteLine ("Your average score is {0}. This is good for a letter grade of A", average); ...etc...
The problem here is that if the user enters valid entries at first and then enters an invalid one, the compiler can't get back to the first while loop to check for the invalid entry. So I tried to swap the positions of the while loops. But this has the same effect; it can't get back to the first while loop to check for valid entries after an invalid one is entered. The answer is most likely simple, but I'm stuck.
The issue you are having is that you break from the first loop when the TryParse returns true, but have no recourse to re-enter the loop. Instead you should nest your loops. The loop with the sentinel should be the outer loop, and the loop that validates and re-prompts the user should be the inner loop. Here is an example:
while(scores != "-99")
{
scores = Console.ReadLine();
while((int.TryParse(scores, out numbers) == false)
{
//validation failed, re-prompt user for better number
Console.WriteLine("Bad value, try again")
scores = Console.ReadLine()
}
//do stuff here with the valid score value
}
I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.
After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??
My Code
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?
The Code reffered to above
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
Any sort of help is much appreciated!! Thank You :)
I'm not sure what you're asking, since the second snippet of code you found online should fix your issue.
Your code works, if you just change the line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.
To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.
Try to follow it step by step with pen and paper (or with a debugger).
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i<sNum.Length; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
I think that will do it... Untested!!
As dognose (and Eren) correctly assert you only need to go halfway through
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length/2; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...
Easiest way:
public static Boolean isPalindrom(Int32 number){
char[] n1 = number.ToString().ToCharArray();
char[] n2 = number.ToString().ToCharArray();
Array.Reverse(n2);
String s1 = new String(n1);
String s2 = new String(n2);
return (s1 == s2);
}
https://dotnetfiddle.net/HQduT5
you could also use Integers for s1 and s2 and return (s1-s2 == 0)
You have many ways of accomplish this exercise.
A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)
B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.
C. there are much more ways without using the string solutions, just with calculation..
int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
{
int temp=x%10;
ar[i]=temp;
x=x/10;
i++;
}
for(int j=0, j<i,j++)
{
temp2=temp2*10+ar[j];
}
if(temp2==x){cout<<"palindrome"}
else {"not palindrome"}
ok here is the logic:
we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..
Use the following code:
public boolean isPalindrom(Integer number)
{
return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}