Example of what needs to be done:
"Several numbers are entered (the input again ends with 0). Determine and print the sum of the 5th,
10th, 15th number, etc."
Can someone please tell me what's wrong with my code?
class Program
{
static void Main(string[] args)
{
int counter = 0;
int sum = 0;
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
while (number != 0)
{
if (number > 0 && counter % 5 == 0)
{
counter++;
sum = sum + number;
}
Console.Write("Enter a number: ");
number = int.Parse(Console.ReadLine());
}
Console.WriteLine("Sum of the 5th, 10th, 15th ... number is = {0}", sum);
Console.ReadKey();
}
}
Problem: you increment the counter only if % 5 == 0 but it never reaches that value. As you can see your starting value is:
int counter = 0;
So the second part of the if condition will evaluate to false in the first iteration and all subsequent iterations, because the variable never gets the chance to change. It remains at 0 in all iterations
Solution: put the incrementing line outside of the if-clause.
This way you are actually counting the numbers of input numbers and thus you can identify whether it is the 5-th, 10-th, 15-th ...
Since you intend to count the input numbers I would suggest to put the
number = int.Parse(Console.ReadLine());
as the first line in the while loop. Then you can count up and after that you should evaluate wether this number is the 5-th, 10-th, 15-th ... element:
while (number != 0)
{
Console.Write("Enter a number: ");
number = int.Parse(Console.ReadLine());
counter++;
if (number > 0 && counter % 5 == 0)
{
sum = sum + number;
}
}
EDIT: Inspired by the comment by PaulF :
I would assume that the counter should only be incremented if (number > 0).
To be correct in detail of your requirements you would need to make an extra if-clause to check for this case. But as 0 is the neutral element in an addition it does not make a difference to the calculated sum. So the code should still produce the desired outcome
EDIT 2:
If your intention was also to not allow negative numbers then you should split your if clause into two and increment the counter only if the entered number is higher than 0. Afterwards you can check whether the current element is a candidate to be added to the sum:
while (number != 0)
{
Console.Write("Enter a number: ");
number = int.Parse(Console.ReadLine());
if (number > 0 )
{
counter++;
if (counter % 5 == 0)
{
sum = sum + number;
}
}
else
{
Console.Write("Please no negative numbers!");
}
}
You have to increment counter before if statment
Counter++
If (counter % 5 == 0) {
...
Related
enter image description here
Hi, I need to make a while loop. The code will take all the positive numbers and calculating the average. If 0 is pressed, then the code will stop en the average will be printed. Look at image link. Here is some code:
int input = 0;
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine());
double average = input / 3;
while (input > 0 )
{
Console.WriteLine(input);
input++;
}
if (input == 0)
{
Console.WriteLine($"Average of all positive numbers is: {average:0.00} ");
}
As per my comment here is a solution that counts how many positive numbers have been entered and uses that number to divide the result:
double count = 0; // Declared as double so fractional value is not lost when dividing the sum
int sum = 0;
int input = -1; // Arbitrarily non-zero number, will be overwritten each loop
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Console.WriteLine($"Average of all positive numbers is: {sum / count:0.00} ");
This initial value of the input variable is arbitrary and allows the while loop to run (as the question asked about writing a while loop). This could be rewritten to use a do...while loop that would run at least once. Then input would not need to be initialised at all.
I've created a program that adds all input values from the user and prints the sum if the user entered 0 or greater than 101. Here's my code:
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
I'm trying to figure how to accepts numbers alternately. For example, Input values are: 4, 7, 8, 3, 6, 1. If the user input two consecutive odd or even number the system will not accept two consecutive odd or even or it will display the sum of all inputted numbers.
Taking the recomendation of Andrew an Peter you can add the list to save your previous inputs and do some checks to the current and prev data to do the logic.
the code that implements this is the following:
//save input list
List<int> inputNumbers = new List<int>();
int n, sum = 0;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
//My Recomendation ==============================
//save previus input numbers
inputNumbers.Add(n);
//Check is there are previous input number
if(inputNumbers.Count>1){
//New control vars
Boolean previousNumberIsOdd= false,currentNumberIsOdd= false;
foreach (int item in inputNumbers)
{
Console.Write(item+",");
}
//check if previus number is odd
if((inputNumbers[inputNumbers.Count-2])%2 == 0){
previousNumberIsOdd = true;
}
//Check if current number is odd
if(n%2==0){
currentNumberIsOdd = true;
}
Console.WriteLine("Control vars:" + previousNumberIsOdd +"/"+currentNumberIsOdd);
//Check diferent scenarios and do the logic
//previous and current number are odds
if(previousNumberIsOdd && currentNumberIsOdd){
//break while and write the result
break;
}
//previous and current number are evens
if(!previousNumberIsOdd && !currentNumberIsOdd){
//break while and write the result
break;
}
}
//if there aren't numbers to break the cycle then do the original logic
//End of my recomendation =====================
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
}
You can do many optimizations to this code but a put it like that to be very clear in the logic.
By using two flag you can achieve the result.
int n, sum = 0;
bool previous = false, current;
bool init = true;
do
{
Console.Write("Enter a number:");
n = int.Parse(Console.ReadLine());
current = n % 2 == 0;
if( current == previous && !init)
break;
previous = current;
init = false;
sum += n;
}
while (n != 0 && n < 101);
Console.WriteLine("Sum is:" + sum);
Console.ReadKey();
Output
Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(true)
{
if(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
break;
}
}
The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?
cheers.
I haven't tested it but slightly refactored your code as below, it should do what you want:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
amount = Convert.ToInt32(Console.ReadLine());
}
EDIT: if you want to safely check whether it is an integer value, you can use the below version of code:
Console.WriteLine("How many dices would you like to throw?");
var input = Console.ReadLine();
while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
input = Console.ReadLine();
}
You might want to check if the entered value is actually an integer.
int amount;
Console.WriteLine("How many dices would you like to throw?");
do
{
if (int.TryParse(Console.ReadLine(), out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);
EDIT
I generally like to give the user the option to exit completely.
int amount;
Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
do
{
var input = Console.ReadLine();
if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (int.TryParse(input, out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);
Text of the task: A user needs to input numbers until the number that could be divided by 5 has been entered two times. Numbers that could be divided by 3 will reset the counter.
int a;
int b;
int counter = 0;
do
{
Console.WriteLine("Enter number");
a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number");
b = int.Parse(Console.ReadLine());
counter++;
// - I am not sure how to set up counter to count a and b together
// when the user enters a and b it counts as 1 not 2?
if (a % 3 == 0 || b % 3 == 0)
{
Console.WriteLine("Counter is reseting");
counter = 0;
}
} while (a % 5 != 0 && b % 5 != 0);
Console.WriteLine(counter);
It takes me out of the loop when I enter once a number divided by 5, and it doesn't want to allow me to enter it twice. How can I fix this?
If I have correctly understood, you want to continue looping unless both values are dividable by 5. So your logic in the final while needs to be:
while( A_is_not_dividable_by_5 OR B_is_not_dividable_by_5 )
or
while( a % 5 != 0 || b % 5 != 0 )
Note the or rather than the and.
Console.WriteLine("Enter number");
a = int.Parse(Console.ReadLine());
counter++;
Console.WriteLine("Enter number");
b = int.Parse(Console.ReadLine());
counter++;
I am using the following code to double alternative digits from a number and add every digit but its not working in c#
int sum=0,r,number;
Console.WriteLine("Enter the number");
number = int.Parse(Console.ReadLine());
if (number % 2!= 0)
{
number = number * 2;
number++;
}
Console.WriteLine("numbers:" + number);
Console.ReadLine();
while (number!= 0)
{
r = number % 10;
number= number/ 10;
sum = sum + r;
}
Console.WriteLine("sum of digits of the number:" + sum);
Console.ReadLine();
Kindly help me. Thank you in advance.
As StevieB said "You're not doubling alternative digits. You're doubling the number and adding 1 if the original number is odd. Then you're summing the digits of the number."
The following code should work for you. I have not tested it for all possible scenarios so please do so.
Also tweek it a little as per your requirements.
Console.WriteLine("Enter a number:");
char[] enteredNumber = Console.ReadLine().ToArray();
int finalNumber = 0;
for (int i = 0; i < enteredNumber.Count(); i++)
{
if (i % 2 != 0)//This condition might need tweeking
{
finalNumber = finalNumber + (Convert.ToInt32(enteredNumber[i].ToString()) * 2);
}
else
{
finalNumber = finalNumber + Convert.ToInt32(enteredNumber[i].ToString());
}
}
Console.WriteLine(finalNumber);
What you are looking for is Luhn Algorithm which I have reproduced here for you.
Luhn Algorithm - C#
Luhn Algorithm uses the last digit (rightmost digit) as a checksum digit. Hence in my first iteration I skip it since it's not required in the first parts of the function.
Since the length of a given number can vary, I have used int a to check my position and know which number I should double and which I should skip.
Read more about the Luhn Algorithm here.
using System;
public class Program {
public void Main()
{
int sum=0,d;
string oNum = "79927398713";
int a = 0;
for(int i = oNum.Length-2; i>=0;i--)
{
d = Convert.ToInt32(oNum.Substring(i,1));
if (a % 2 == 0) d = d*2;
if (d > 9) d -= 9;
sum += d;
a++;
}
if ((10 - (sum%10)) == Convert.ToInt32(oNum.Substring(oNum.Length-1)))
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Invalid");
}
Console.WriteLine("sum of digits of the number:" + sum);
}
}
There are three places where the Console writes a line. And at least two of those are visible for any given number. The line that you wanted, "sum of digits of the number:" will always show.