Using condition operator ? for getting even number - c#

I am trying to write a simple code, which will take a input from user and save it into number variable and then I am trying to find out if this number is even, or odd using condition operator, but I am bit stuck of how to use Console.WriteLine() in this condition operator and where to call it. Maybe someone can help me to understand it more clearly. Thanks in advance!
using System;
namespace ConditionalOperatorExercise
{
class Program
{
static void Main(string[] args)
{
int number;
number = Convert.ToInt32(Console.ReadLine());
var evenNumber = number % number == 1 ? Console.WriteLine("Number is even"); : Console.WriteLine("Number is odd");
}
}
}

You can change your code like this:
var message = number % 2 == 0 ? "Number is even" : "Number is odd";
Console.WriteLine(message);
Please note that you need to check the number % 2 is equal to 0 instead, to check whether a number is even or odd.

Related

Submiting solution to CodeChef shows wrong answer when results are correct. Why?

Original task: You are given a number N. Find the sum of all numbers from 1 to N. Input: First-line will contain the number N. Output: Print the answer in a single line. Constraints 1 ≤ N ≤ 10^9.
Sample Input 1: 4
Sample Output 1: 10
Sample Input 2: 8
Sample Output 2: 36
This is my code attempt:
using System;
public class Test
{
public static void Main()
{
// your code goes here
double sum, N;
N = Convert.ToDouble(Console.ReadLine());
sum = N * (N + 1)/2;
Console.Write(sum);
Console.ReadLine();
}
}
I think my logic is right, but after submission it shows wrong answer. Why?
Your solution is correct. I think the problem is with evaluation and given statement Print the answer in a single line. You are printing it on the line, but not adding "new line". So the "automated machine that checks if results are correct" doesn't know where to split results. Also waiting for input Console.ReadLine() at the end of code is not supposed to be there, it would break system from continuing.
What you should do, is:
using System;
public class Test
{
public static void Main()
{
double sum, N;
N = Convert.ToDouble(Console.ReadLine());
sum = N * (N + 1)/2;
Console.WriteLine(sum); //Changed to console WriteLine
// Console.ReadLine(); // (remove this)
}
}

How to get odd or even numbers in C# with a user input?

I am very new to C# and have been set a task to make a program that asks for a user input of a number and then says if that number is odd or even. How can I do that?
You need to figure how to check if a number is odd or even. How can do, you ask?
You may not have learned this yet, but modulus is the simplest way to do it. It uses the character % and it basically acts as a division, but instead of telling what value each parts of the division equals, it tells you what is left from the division. Coming from that, you know that if the number divided by % 2 is 0, your number is even because there is nothing left. 4 / 2 = 2 vs 4 % 2 = 0
My example here is not the shortest or fastest, but is easier to understand for a beginner
Console.WriteLine("Enter your number : ");
string number = Console.ReadLine();
Int32.Parse(number);
if(number % 2 == 0)
{
Console.WriteLine("Your number is even.");
}
else
{
Console.WriteLine("Your number is odd.");
}
Have a look at the remainder (modulus) operator.
An example:
int userInput = // get your input
bool isEven = userInput % 2 == 0;
An even number will have a remainder of 0 when divided by 2.
In one line
Console.WriteLine(int.Parse(Console.ReadLine()) % 2 == 0 ? "even":"odd");

Cannot convert type 'String' To 'Int'?

okay so, I have been asked to write a console application for a theater ticket system. A user will type in the number of seats required, and the area of the theater chosen (using the code number 1-4 to represent the seating area chosen) The program should work out and display the cost of the tickets, based on the pricing plan shown below
Area Code price
Stalls 1 £24
Grand circle 2 £30
Upper circle 3 £27
Gallery 4 £20
I've so far came up with the following, But it's got an error to do with string + Int conversions under the IF Statements section, this is probably very easy to fix, but I'm new to programming so i'm unsure how to resolve it:
//Declare variables and constants
int iSeatNum;
int iArea;
int iCost;
int iTotalCost;
//Ask the user how many seats they require
Console.WriteLine("How many seats would you like to purchase?");
iSeatNum = Convert.ToInt32(Console.ReadLine());
//Ask the user what area they would like to be in
Console.WriteLine("Where would you like to sit? Please enter 1 for Stalls, 2 for Grand Circle, 3 for Upper Circle or 4 for Gallery");
iArea = Convert.ToInt32(Console.ReadLine());
**if (iArea = "1")**
{
iCost = 24;
}
//Clarify information & work out
Console.WriteLine("You are buying " + iSeatNum + " Seats at " + iArea);
iTotalCost = iSeatNum * iCost;
Console.WriteLine("Your total ticket cost is " + iTotalCost);
//Prevent from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
if (iArea = "1")
iArea is an integer, "1" is a string. So you cannot compare those two. You should compare with the integer 1 instead. Also note that a single equals symbol (=) is an asignment, and not a comparison. You will want to use two there: ==
if (iArea == 1)
now it displays a further error, when I put iTotalCost = iSeatNum * iCost; it comes up the error of "Use of unassigned local variable iCost" Any idea how I fix this?
The problem is that you declare the variable iCost at the beginning, but never safely assign any value to it before using it. You do assign a value when iArea equals to 1, but for all other cases, the variable remains uninitialized. Of course the compiler doesn’t know that you will end up typing in 1 when the program runs for testing, and that’s not a safe thing anyway. So it requires you to initialize your variable with anything instead.
So at the beginning, you can just say int iCost = 0; to fix this.
Well "1" is a string, not int.
if (iArea == 1)
Because you have already converted you string (the Console.ReadLine() return a string) into number using:
iArea = Convert.ToInt32(Console.ReadLine());
you can compare it as number using:
if (iArea == 1)
note the == instead of =, the single is used for assignment, the double for comparison.
if (iArea = "1")
This doesn't make sense. First of all you're using the assignment equals operator. You're attempting to assign iArea the value of "1". Instead, you need the logical equality operator == which will return true or false depending on whether the first operand is equal to the second operand.
Second, you have already converted the string value read from the console to a strongly typed integer. So you need to write your if statement as follows:
if (iArea == 1)
String strArea =Console.ReadLine();
if (strArea.Equals("1"))
{
iCost = 24;
}
or
int iArea = Convert.ToInt32(Console.ReadLine());
if (iArea == 1))
{
iCost = 24;
}

Creating an application that determines whether a number is odd/even

I am very new to C# and I am having some issues. I have been trying for a while now and I cant seem to get it right. I think I have the idea but I just don't know how to make it work. There aren't any examples in the chapters of my book either. I need to "create an application that reads an integer, then determines and displays whether it’s odd or even. Have the user enter an integer and output to the console: The number you have entered is: input value + even or odd" I'm hoping I can get some help here. Not looking for someone to just do the work either. If you can explain it, please do!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Student_Challenge_Lab_2
{
class Program
{
// main method begins the execution of C# program
static void Main(string[] args)
{
int number1; // declares the integer to be added
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
number1 = Convert.ToInt32(Console.ReadLine());
int %(number1, );
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
if (% == 0)
Console.Write("Your integer is even.", number1);
else Console.Write("Your integer is odd.", number1);
}
} // end main
} // end Student challenge lab 2
Every binary operator should be used in a form:
[argument1] [THE OPERATOR] [argument2]
The % is also a binary operator, which can be used in the same way as + and /. So analogically, if the / operator produces the result of a division operation:
float result = (float)number1 / number2;
the % will produce the remainder in the same fashion:
int remainder = number1 % number2;
All what's left is that numbers that are even produce 0 remainder when modulo against 2 is calculated.
I'm not sure how you've come up with the syntax you're using here
int %(number1, );
You've already defined number1 as an int above. You want to define a new variable that contains the value of your mod operation on number1. So something like:
int remainder = number1 % 2;
Then
if (remainder == 0)
Here, I have done your homework...
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.
I also added a Console.ReadKey so that you can see the output, press any key to end the app.
using System;
namespace Student_Challenge_Lab_2
{
internal class Program
{
// main method begins the execution of C# program
private static void Main(string[] args)
{
// following code prompts user to input the two sets of integers
Console.Write("Please enter your integer: ");
var number1 = Convert.ToInt32(Console.ReadLine());
// the program now tests to see if the integer is even or odd. If the remainder is 0 it is an even integer
Console.Write(number1 % 2 == 0 ? "Your integer ({0}) is even." : "Your integer ({0}) is odd.", number1);
Console.ReadKey();
}
}
// end main
}
// end Student challenge lab 2

Comparing in Array

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.

Categories