how do you repeat the total entered? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am very new to c# and I don't get it very quickly. If you can explain how and why like your talking to a 3yr old that would be great!!!
how do you make (enter the amount (-1 to stop)) repeat and end up with a total of all amounts entered?

Luckily, my 3-year old is sitting right here, so I had him write it out :)
var total = 0; // This will hold the sum of all entries
var result = 0; // This will hold the current entry
// This condition will loop until the user enters -1
while (result != -1)
{
// Write the prompt out to the console window
Console.Write("Enter the amount (-1 to stop): ");
// Capture the user input (which is a string)
var input = Console.ReadLine();
// Try to parse the input into an integer (if TryParse succeeds,
// then 'result' will contain the integer they entered)
if (int.TryParse(input, out result))
{
// If the user didn't enter -1, add the result to the total
if (result != -1) total += result;
}
else
{
// If we get in here, then TryParse failed, so let the user know.
Console.WriteLine("{0} is not a valid amount.", input);
}
}
// If we get here, it means the user entered -1 and we exited the while loop
Console.WriteLine("The total of your entries is: {0}", total);

We are calling it loops, little boy :P
UPDATE I dont know if i understood you, but now the code writes sum each time, and if you enter for example -5 it will be sum = sum - 5
class Program
{
static void Main(string[] args)
{
// thoose are variables, and they are storing data
int input = 0; // input integer number
int sum = 0; // sum of all numbers
while (true) //Infinite loop (executes undereneath code until true=true)
{
input = int.Parse(Console.ReadLine()); // read the line from user, parse to int, save to input variable
if (input == -1) break; // if integer input is -1, it stops looping (the loop breaks) and GOES (two lines down)
sum = sum+ input; // summing all input (short version -> s+=input)
Console.WriteLine("Actual Sum: "+sum); // HERE IS THE UPDATE
}
//HERE
Console.WriteLine("Your final sum is: " + s);
}
}

Related

How to do while loop/Do while loop with sentinel value with switch

Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}

How to fix this "Input string was not in a correct format" problem in the following code? [duplicate]

This question already has answers here:
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
Here is my code :
using System;
namespace CappedSum
{
class Program
{
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;
while (sum<sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
if (sum + number < sumLimit)
{
sum += number;
count++;
}
else if (sum + number > sumLimit)
{
Console.WriteLine(sum + " " + count);
}
}
}
}
}
I had to write a console application that reads from the keyboard a list of numbers until their sum reaches a certain limit also entered by the user.
The limit is given on the first line, and on the next lines will be the list of numbers which has to be added. The program will stop reading when the sum of the numbers entered so far exceeds the limit and will display the last amount that did not exceed the limit, as well as how many numbers were needed to calculate it.
for example : if I enter 10 (which is the limit) then I enter 2,3,2,6. The result will be 7 (which is the last amount that did not exceed the limit) and 3 (which represents how many numbers needed to calculate it).
Try out Int32.Parse instead of Convert.ToInt32. Also, a really basic I use sometimes to debug my same mistakes, is to write MessageBoxes after specific instructions, so if they do not work I never get to the message, viceversa if the message shows I know that works. I'd put two Messageboxes after the Int32.Parse(Console.Readline()) being like MessageBox.Show(sumlimit/number.ToString());. This way you know how far the code works.

stack sum elements (Beginer C#) [duplicate]

This question already has answers here:
Input string was not in a correct format
(9 answers)
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
I am currently learning the C # language. I have the following task:
Write program that:
Reads an input of integer numbers and adds them to a stack
Reads commands until "end" is received
Prints the sum of the remaining elements of the stack
Input
On the first line you will receive an array of integers
On the next lines,
until the "end" command is given, you will receive commands - a single command and one or two numbers after the command, depending on what command you are given
If the command is "add", you will always receive exactly two numbers after the command which you need to add in the stack
If the command is "remove",
you will always receive exactly one number after the command which represents the count of the numbers you need to remove from the stack. If there are not enough elements skip the command.
Output
When the "end" command is received, you need to Print the sum of the remaining elements in the stack
Input
1 2 3 4
adD 5 6
REmove 3
eNd
Output
Sum: 6
input:
3 5 8 4 1 9
add 19 32
remove 10
add 89 22
remove 4
remove 3
end
Output:
Sum: 16
I wrote this code. From the beginning it works, I enter a number of numbers and put them in the stack without any problems. From now on, after entering what I want to do "add", "remove" or "end", an error appears after adding numbers. after I decide to add an element the program allows me to enter numbers indefinitely until I try to change the addition of numbers with one of the other two options I get this error: System.FormatException: 'Input string was not in a correct format.'
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Stack_Sum
{
class Program
{
static void Main(string[] args)
{
Stack<int> numbers = new Stack<int>();
string input = Console.ReadLine();
string[] number = Regex.Split(input, #"\D+");
foreach (string value in number)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
numbers.Push(i);
}
}
string option = Console.ReadLine();
while (true)
{
switch (option.ToLower())
{
case "add":
int addToStack = Int32.Parse(Console.ReadLine());
for (int i = 0; i < 2; i++)
{
numbers.Push(addToStack);
}
continue;
case "remove":
int popItem = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < popItem; i++)
{
numbers.Pop();
}
continue;
case "end":
foreach (var Stack_Sum in numbers)
{
int sum = 0;
sum += Stack_Sum;
}
break;
}
}
}
}
}
You're only asking for the option selection once, before the while(true) loop:
string option = Console.ReadLine();
After that, you treat all user input as integers, so there's no opportunity for the user (you) to change the option. One easy fix is to place that line inside the loop, preferably with some more instructions:
//... Your code...
while(true)
{
Console.Write("Add, Remove, End: “);
string option = Console.ReadLine();
switch(option.ToLower())
{
//... Your code...
}
}
Now, I'm not convinced that the rest of your program works properly, but that's another story. You can debug it with breakpoints once you get over this hurdle.

While loop breaks unintentionally

I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.

how to solve application disappearing after console readline a negative number? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I wrote a short code in c#, and it's function is like this:
First you choose how many times you want to put in a number, then you pick a number to sum
static void number()
{
Console.WriteLine("how many numbers, max is 999");
int n = int.Parse(Console.ReadLine());
if (n > 999)
{
return;
}
Console.WriteLine("enter number here:");
int d = int.Parse(Console.ReadLine());
if (d < -99999 || d > 99999)
{
return;
}
Console.WriteLine(n + " " + d + "which number has to be counted up");
for (int i = 0; i < n; i++)
{
int e = int.Parse(Console.ReadLine());
int c;
c = e + d;
Console.WriteLine(e + " " + c);
Console.WriteLine("press enter to input a new number");
Console.ReadKey();
i++;
}
}
If I put positive numbers, it works correctly. But if I put in negative numbers, It asks "enter number here" and after I put in a number, it shows the which number to count up writeline very quickly and then the application stops for no reason.
Any thoughts why this happens?
If you put a negative number into n, then i will never be less than n in your for loop (which you've set to run while i < n). This means the the for loop will never run and the as this is the last bit of code in you application, the program will end.
Here's what I get:
how many numbers, max is 999
-2
enter number here:
3
-2 3which number has to be counted up
When I enter the -2 it gets stored in the variable n. Later, in the for loop, the variable i starts out at zero, which means the i < n, so the loop quits without executing anything in the loop body.

Categories

Resources