How to count the output of the console - c#

This is a Grading Marksheet code and I am looking for how the app may count how many times a string (e.g: Grade is A) has been repeated. Thank you!
This code sample is the part where I need to count the string from
if (p > 60 && p <= 80)
{
Console.WriteLine("Grade is A");
}
if (p > 80 && p <= 100)
{
Console.WriteLine("Grade is A++");
}
Console.ReadLine();

The idea would be to simply increase a integer variable for each time you print an A.
Example with your Code as Base:
// Use a Variable that you increase in value
// To see how many A were printed
int acount = 0;
// Is number bigger than 60 and smaller or equal to 80
if (p > 60 && p <= 80)
{
Console.WriteLine("Grade is A");
acount++;
}
// If the first statement is true the second can't be true anyway
// so use else if so it doesn't have to make usless checks
// Is number bigger than 80 and smaller or equal to 100
else if (p > 80 && p <= 100)
{
Console.WriteLine("Grade is A++");
acount++;
}
// Print out result
Console.WriteLine("A was printed: " + acount + " times");
Console.ReadLine();

Related

How do i write an if statement to be between two values?

Here is my code, for my if statements I want to have it between two values for example:
if(rating < 5 > 2);
So I'm saying i want it to only print the command if that value is below 5 but higher than 2.
Is there a way to do this? Thank you for your time.
Here is my code.
public static void Main(string[] args)
{
Console.WriteLine("What would you rate starcraft out of 10?");
int rating = Console.Read();
if (rating < 5) ;
{
Console.WriteLine("Not good enough!");
Console.ReadLine();
}
if (rating > 5) ;
{
Console.WriteLine("OOOOOOOOO yeeeeeeee");
Console.ReadLine();
}
if (rating > 8) ;
{
Console.WriteLine("We are bestfriends now ;)");
Console.ReadLine();
Use conditional logical AND operator &&:
if (rating < 5 && rating > 2)
{
}
Or pattern matching (read more #1, read more #2):
if (rating is < 5 and > 2)
{
}
P.S.
You can refactor a bit with switch expression and ordering the checks to remove some code repetition and improve readability (note that original code does not cover rating == 5 case compared to the following):
var rating = ...;
var message = rating switch
{
< 2 => "Terrible",
< 5 => "Not good enough!",
< 8 => "OOOOOOOOO yeeeeeeee",
_ => "We are bestfriends now ;)"
};
Console.WriteLine(message);
Console.ReadLine();
To avoid complications, you can sort ratings' thresholds and then check them in order with a help of if ... else if pattern, e.g. having
2 - Nightmare
5 - Not good enough!
8 - OOOOOOOOO yeeeeeeee
more - We are bestfriends now
We can put it as
if (rating <= 2) // 2 or less
Console.WriteLine("Nightmare");
else if (rating <= 5) // (2..5]
Console.WriteLine("Not good enough!");
else if (rating <= 8) // (5..8]
Console.WriteLine("OOOOOOOOO yeeeeeeee");
else // more than 8
Console.WriteLine("We are bestfriends now");
Console.ReadLine();

What will be the output of this and how?

The output of this code is
0 1 2 3
But I am not getting the factorial part. I mean 1!=1 (i.e. i factorial equals to 1), so it does not satisfy the condition, so type for input 2 and 3, but they get printed as output?
static void Main(string[] args)
{
int i = 0;
int b = 8, a = 32;
for (i = 0; i <= 10; i++)
{
if ((a / b * 2)== 2)
{
Console.WriteLine( i + " ");
continue;
}
else if (i!=4)
Console.Write(i + " ");
else
break;
}
Console.ReadLine();
}
OK, let's see:
int b = 8, a = 32;
...
a / b * 2 == 32 / 8 * 2 == 4 * 2 == 8
That's why if ((a / b * 2) == 2) will never succeed, and so we can drop this if and simplify the loop into
for (i = 0; i <= 10; i++)
if (i != 4) // i != means "i doesn't equal", not "i factorial equals"
Console.Write(i + " "); // print 0, 1, 2, 3
else
break; // break on 4
Here we can clearly see that the routine will be printing out i up to 4 So you have
0 1 2 3
Side note: in order to avoid such errors, format out your code and let the compiler help you:
i!=4 // Bad, it can be read in different ways (not equal or factorial)
i != 4 // i is not equal to 4
i! = 4 // assign 4 to i factorial: compile time error
i! == 4 // i factorial equals to 4: compile time error - C# doesn't have factorials

Defining boolean local variables

Note: This is my first time using "Stack Overflow" and I am relatively new to C#
(please excuse my poor programming skills at the moment)
My Code:
static void Main(string[] args)
{
Challenge(5, 12);
}
static void Challenge(int num1, int num2)
{
//finds the sum of the two variables
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is...\n{2}", num1, num2, sum);
bool isDivisible = true;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else if ((sum % 10 != 5) || (sum % 10 != 0))
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
//depending on value of 'isDivisible', returns certain functions
if (isDivisible == true)
{
Console.WriteLine("This value is usable.");
Console.WriteLine("\n\nThe remaining usable values are: ");
for (int newVal = sum + 1; newVal <= 55; newVal++) // '+ 1' added to make sure 'sum' is not printed again
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
else if (isDivisible == false)
{
Console.WriteLine("This value is not usable.");
Console.WriteLine("\n\nThese values are considered usable: ");
for (int newVal = 0; newVal <= 55; newVal++)
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
Console.ReadLine();
}
I viewed some articles online, as well as the "Stack Overflow" post: Why compile error "Use of unassigned local variable"? . After learning that local variables are not initialized (and must be given a value), I set my bool value for "isDivisible" equal to true by default.
Question:
Is there a better way to define a local variable that is of Boolean value (at least in the case of the program I am trying to run here)?
Thanks!
Your condition in the else if is wrong, it's not the complement of the first condition, so it doesn't make sense. The correct complement would be:
else if ((sum % 10 != 5) && (sum % 10 != 0))
However, you don't need to use an else if at all, you can just use an else as you want to catch every case that is not caught by the first condition. That also means that you don't have to initialise the boolean variable, as the compiler can see that it always will be set by one of the code blocks:
bool isDivisible;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
Side note: Instead of (sum % 10 == 5) || (sum % 10 == 0) you could just use sum % 5 == 0.
Side note 2: You don't need to compare a boolean variable to true, you can just use it as a condition. Also, you don't need the else if there either. Instead of this:
if (isDivisible == true)
{
...
}
else if (isDivisible == false)
{
...
}
you can use:
if (isDivisible)
{
...
}
else
{
...
}
Comparison expressions in C# will return a boolean value indicating whether or not they are true. So you could simplify your initial assignment to:
bool isDivisible = ((sum % 10 == 5) || (sum % 10 == 0));
Instead of explicitly setting it to true or false. Then your variable would always be set.
This doesn't work for all cases. Sometimes, it is difficult to reduce the comparison operation to a simple expression. But, it is often a handy way to initialize bools.

C# console app: How can I continue returning an error message until user enters valid data?

I'm building a method to calculate shipping cost. I've already validated the data type to an integer. As long as the integer entered is greater than 0, the logic works correctly. When the number entered is less than one, an error message is generated and repeats the request for a larger whole integer. Okay so far.
However, after the error message asks for a valid integer, the data entered is ignored and the calculation is incorrect. How can I repeat the request until the user enters a number greater than 0 and then perform the desired calculation with it? Thanks!
static double CalculateShipping(int items, double shippingCharge)
{
if (items == 1)
shippingCharge = 2.99;
else if (items > 1 && items < 6)
shippingCharge = 2.99 + 1.99 * (items - 1);
else if (items > 5 && items < 15)
shippingCharge = 10.95 + 1.49 * (items - 5);
else if (items > 14)
shippingCharge = 24.36 + 0.99 * (items - 14);
else
{
Console.WriteLine("You must order at least 1 item.");
Console.WriteLine();
Console.Write("Please enter a whole number greater than zero: ");
items = Console.Read();
}
return shippingCharge;
}
static int ReadItemsCountFromInput()
{
while(true)
{
Console.WriteLine("enter items count: ");
string s = Console.ReadLine();
int r;
if(int.TryParse(s, out r) && r > 0)
{
return r;
}
else
{
Console.WriteLine("you should enter number greater than zero");
}
}
}
static double CalculateShipping(int items, double shippingCharge)
{
if (items == 1)
shippingCharge = 2.99;
else if (items > 1 && items < 6)
shippingCharge = 2.99 + 1.99 * (items - 1);
else if (items > 5 && items < 15)
shippingCharge = 10.95 + 1.49 * (items - 5);
else if (items > 14)
shippingCharge = 24.36 + 0.99 * (items - 14);
return shippingCharge;
}
static void Main()
{
int items = ReadItemsCountFromInput();
double result = CalculateShipping(items, 0);
Console.WriteLine("Shipping: {0}", result);
}
Wrap your Console statements in a While loop. Something like...
bool MyValidationFlag = false;
While MyValidationFlag == False
{
// Prompt User
If (UserInput is an integer > 1)
MyValidationFlag = True
else
MyValidationFlag = False
}
(You might also want to throw in some kind of check for an "escape" value in case the user wants to quit.)

Count the numbers that are not divisible by 2, 3, 5

In my program, I think my count variable is not holding the value. What do I do so that it can hold? here`s my code.
static void Main(string[] args)
{
double a;
double count = 0;
Console.WriteLine("Enter the Numbers : ");
for (double i = 1; i <= 10; i++)
{
a = Convert.ToDouble(Console.ReadLine());
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0)
{
count = count++;
}
//else
//{
// }
Console.ReadLine();
}
Console.WriteLine("The Numbers That Are divisible by 2,3,5 are : " + count);
Console.ReadLine();
}
Your mistake is the line count = count++;. This does not increase count by one. You need to use just count++;.
The expression count++ will increment the value of count by one and then return as the expression's value the original value of count. In this case the increment of count++ happens before the assignment, so count is first incremented by one, but then you assign the value of count++, that is, the original value, to count again, so it does not increase at all.
Your program lists numbers that are not divisible by any of those numbers. If you want to count numbers which aren't divisible by all of them then you need to use if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) instead. I would also suggest using integers instead of doubles if possible.
Finally, your print statement says numbers that are divisible by 2,3,5, but count is the number of numbers which are not divisible by those numbers.
Edit: Are you entering 10 numbers each time you test? I'm not sure what kind of result you will get if you give a blank input.
Not to add to what jk and David Kanarek said in their answers or what the others the comments on those answers, As pointed out by jk use count+1 instead of count ++ , also a few notes:
1) Your using console.Readline() twice in the loop, so the user will enter 20 inputs but only 10 will be read..
2) Just alittle extra thought on Anton's comment, in your if clause , if you use || your trying to catch any of the conditions being true, in other words:
// a=2
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0) // False || True || True = True
{
count = count + 1 ;// count will increase
}
on the other hand, using && :
// a=2
if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) // False && True && True = false
{
count = count + 1 ; //count will not increase
}
A useful Link explaining operators

Categories