Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i solved an assignment question on my own but i seems not to be able to print an else statement successfully even though the code works.
The questions is below,
Create a program that prompts the user for the first number. Show on the screen which number was chosen and if the
Number is greater than 10 then show your predecessors until you reach number 10.
My solution is below,
Console.WriteLine("Enter interger please: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
for (int num3 = num; 10 <= num3; num3-- )
{
if (num > 10)
{
Console.WriteLine(num3);
}
else
{
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
}
Well it's normal that in doesn't enter the else statement. You're doing if (num > 10) and num is the value entered by the user which never changes during the process. So if num = 15 you're always doing is 15 > 10.
Then only moment the else statement is gonna print is if the number entered is 10.
And the moment num is smaller than 10, you'll never get in the for loop so the number will never be smaller than 0 inside the loop so that line won't make sense even if it's played
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
Cause like i said if this line is printed that means the value in num was 10 which is not less than zero.
You could change it for something like this
if(num < 10)
{
Console.WriteLine("It's smaller than 10");
}
for(int num3 = num; 10 <= num3; num3--)
{
Console.WriteLine(num3);
}
You're decrementing "num3" on the for loop, but you're validating if "num" is greater than 10 which, by entering the loop in the first place, will always be true.
Change to:
if (num3 > 10)
{
Console.WriteLine(num3);
}
Are you able to provide the question?
The code you have written seems a little meaningless.
Firstly, the for loop will only run if you enter an integer >= 10
Rewriting your code:
Console.WriteLine("Please enter a positive integer: ");
var args = Console.ReadLine();
if (int.TryParse(args, out int num))
{
if (num < 0)
Console.WriteLine('Must enter a positive integer!');
for (var i = num; i >= 10; i-- )
{
//this only runs if the integer entered is >= 10
if (num > 10)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("A non-integer was entered!");
}
Related
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 2 years ago.
Improve this question
Write a program that will continue to prompt the user to guess a number until the correct number has
been entered. You should also consider user validation; that is, has the user entered a number less than
1 or greater than 10? Have they entered a character? Start by creating a new project and name its main
class (and file) as GuessingNumber. Then proceed with the following steps:
Create an integer variable called number and set it equal to 5.
Prompt the user to guess a number between 1 and 10.
If the user enters number 5, print “You have guessed the number! Well done!”
If they do not enter 5, continue to prompt the user to enter a number until they enter 5.
Here is my code so far
using System;
namespace Progam
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10");
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
}
}
}
}
How would I write the code to prompt the user to guess again if the number is not equal to 5?
Thanks
Here is your code slightly modified. There are many other ways to do this, this is one and a bit more readable for newer programmers.
bool Correct = false;
while (!Correct)
{
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
Correct = true;
}
}
static void Main(string[] args)
{
var ok = false;
do
{
Console.WriteLine("Guess a number between 1 and 10");
if (!int.TryParse(Console.ReadLine(), out var number))
{
Console.WriteLine("Not a number");
continue;
}
if (1 > number || number > 10)
{
Console.WriteLine("This is out of the range");
continue;
}
ok = number == 5;
if (ok)
{
Console.WriteLine("you have guessed the correct number");
}
} while (!ok);
Sure hope I get a good grade!
do
{
var number = Convert.ToInt32(Console.ReadLine());
....
}while(number != 5)
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 3 years ago.
Improve this question
So we have to have code that swaps the integers in a two-digit number, such as "43" being "34". The user inputs a random two digit number and that number must be swapped.
I am not sure how to separate or mess with the two digit number that the user inputs into the console, so I have not had much luck in doing this.
static void Main(string[] args)
{
Console.WriteLine("Please enter a two-digit integer");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
Console.ReadKey();
}
You can also just reverse the string before you parse it:
string input = string.Concat(Console.ReadLine().Reverse());
// If the user entered "34", 'input' will equal "43"
You can try modulo arithmetics:
number = number % 10 * 10 + number / 10;
you could do:
Console.WriteLine("Enter a No. to reverse");
int Number = int.Parse(Console.ReadLine());
int Reverse = 0;
while(Number>0)
{
int remainder = Number % 10;
Reverse = (Reverse * 10) + remainder;
Number = Number / 10;
}
Console.WriteLine("Reverse No. is {0}",Reverse);
Console.ReadLine();
this will give you 34 if you entered 43.
You can checkout this https://www.c-sharpcorner.com/blogs/reverse-a-number-and-string-in-c-sharp1 for more info.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this is my program I hope you understand what I am trying to do.
if (primeNum = int)
{
Console.WriteLine(" the number entered is not prime ");
}
If you want to know if it's a whole number, then round it and compare the numbers. If the number is a whole number, it will not change when it's rounded...so if the rounded version of the number is equal to the number itself, then it's a whole number. If they're different, then it's not a whole number:
double i = 1.2;
if (Math.Round(i, 0, MidpointRounding.AwayFromZero) == i) {
//whole number
} else {
//not a whole number
}
private static bool IsWhole(double number)
{
return (number % 1 == 0);
}
If Program.isWhole(5.67) returns true call System.Environment.Exit(0) to close application.
Try this program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace primeCsharp
{
class Program
{
static void Main(string[] args)
{
int n = 0; // Number to be test for prime-ness
int i = 2; // Loop counter
bool is_prime = true; // Boolean flag...
// Assume true for now
Console.WriteLine("Enter a number and press ENTER: ");
n = Console.Read();
// Test for a prime number by checking for divisiblity
// by all whole numbers from 2 to sqrt(n).
while (i <= Math.Sqrt(n))
{
if (n % i == 0)
{ // If i divides n,
is_prime = false; // n ix not prime
break; // BREAK OUT OF THE LOOP NOW!
}
++i;
}
// Print results
if (is_prime)
{
Console.WriteLine("Number is prime.\n");
}
else
{
Console.WriteLine("Number is not prime.\n");
}
}
}
}
See this:
How can I get the data type of a variable in C#?
and try:
if(primeNum.GetType() == typeof(int))
You can check whether the number is equal to the value of its conversion to int, like this:
if (primeNum == (int)primeNum)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The question is clear however the code is ambiguous . can anyone explain how this code work specifically this segment int thirdDigit = (number / 100) % 10;
using System;
class ThirdDigit
{
static void Main()
{
Console.Write("Please enter a number: ");
int number = int.Parse(Console.ReadLine());
int thirdDigit = (number / 100) % 10;
if (thirdDigit == 7)
{
Console.WriteLine("The third digits IS seven!");
}
else
{
Console.WriteLine("The third digit IS NOT seven.");
}
}
}
Let's think about the operations applied with a concrete example, 8821 and 7740.
8821 / 100 == 88 // integer division
88 % 10 == 8 // and is not 7
7740 / 100 == 77 // integer division
77 % 10 == 7 // and is 7
On the modulo step, the result is only == 7 if the remainder is 7.
Conceptually it's simpler to think of this as:
Strip the one's and ten's places
then strip all but the one's place
Test the result
First integer division is used (number/100), this returns a number with the third digit of the original number as its last digit. 12345/100 = 123. Secondly the modulus operator is used (% 10) this returns the reminder when dividing with ten, 123 % 10 = 3.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I got case 1-3 working, but I cant get 4-7 working or don't know how I would type it or approach it.
As you can see in number 4 I programmed so when I run the program and press 4 it should run case 4 count down to 10 but skip 7 why wont it work? Also cant figure out how to do 5-7.
I haven't learned that far yet if could help me and also explain how your code works out the problem for me it would be really appropriated.
namespace WhileLoopExercises
{
class Program
{
static void Main(string[] args)
{
int selection = 0;
while (selection != 9)
{
Console.Clear();
Console.WriteLine("\n\n Menu:\n");
Console.WriteLine("\t 1. Display 10 stars( one per line)");
Console.WriteLine("\t 2. Request a value 1 to 50 from user, then display");
Console.WriteLine("\t 3. Display 10 rows of 3 stars");
Console.WriteLine("\t 4. Add all values between 1 to 10 except 7");
Console.WriteLine("\t 5. Display all the even numbers between 10 and 100");
Console.WriteLine("\t 6. Add all the odd numbers bewteen 10 and 100");
Console.WriteLine("\t 7. Generate 6 random numbers ranging from 1 to 49");
Console.WriteLine("\t 8. Exit Apllication");
Console.Write("Enter your selection: ");
selection = int.Parse(Console.ReadLine());
switch (selection)
{
case 1:
{
int counter = 1;
while (counter <= 10)
{
Console.WriteLine("*");
counter++;
}
}
break;
case 2:
{
Console.Write("Enter integer 0-50 : ");
int N = int.Parse(Console.ReadLine());
int counter = 1;
while (counter <= N)
{
Console.Write("*");
counter++;
}
}
break;
case 3:
{
int counter = 1;
while (counter <= 10)
{
Console.WriteLine("***");
counter++;
}
}
break;
case 4:
{
int counter = 1;
while (counter <= 10)
{
if (counter == 7)
{
counter++;
}
}
}
break;
case 5:
{
int counter = 1;
while (counter <= 100)
{
}
}
break;
case 6:
{
}
break;
case 7:
{
}
break;
}// end of switch
//pause
Console.WriteLine("\n\nHit any key to coutinue");
Console.ReadKey();
}
}
}
}
We can't do your homework for you on stack overflow. However, we can point out your logical issues.
Looking at case four, we see
case 4:
{
int counter = 1;
while (counter <= 10)
{
if (counter == 7)
{
counter++;
}
}
}
Walk through the problem now. We start with a counter of 1, and while it is less than or equal to 10, we enter your if statement.
Your if statement says "If my counter is equal to seven, then increment (increase) the counter by one." However, your counter enters at 1, and there is no other logic defining the counter's behavior, so nothing happens! This loop then goes on forever (Oops!). With this in mind, try solving again.
Here are some suggestions for number 4, without just writing the solution:
Your counter starts at 1, the loop continues while counter <= 10, but you only increment it if counter == 7. Does that seem like a problem?
You're doing something when counter == 7, but in fact "7" is the only time you don't want to be doing anything.
You need to create another variable to store your "sum" in, then add each value to it.
Case 4 won't work as is since it will only increment when counter is 7. So it stays infinitely at 1. This should work (without the line numbers at the start - they're for a section below):
1 int counter = 1;
2 int sum = 0; // Need to maintain sum
3 while (counter <= 10) { // Do all numbers 1 thru 10
4 if (counter != 7) // Skip 7
5 sum += counter;
6 counter++;
7 }
8 Console.Write (sum);
A similar approach can be taken with all the other cases. All you have to do is figure out exactly what it's asking and map that to code. Try something to see if it works and, if not, run the code through your head to see where it's going wrong. During the learning process, being able to emulate a computer in your head is a valuable skill to learn.
It's often advantageous to sit down with a pencil and paper and run each line in turn (with line numbers matching those in the code above):
line | counter | sum | comment
-----+---------+-----+--------
1 | 1 | ? |
2 | | 0 |
3 | | | 1 <= 10, will enter 'while'
4 | | | 1 != 7, will enter 'if'
5 | | 1 |
6 | 2 | |
7 | | | return to while loop start
3 | | | 2 <= 10, will enter 'while'
:
and so on.
Another example of mapping the requirements to code comes from case 6: Add all the odd numbers between 10 and 100. This can be achieved thus:
the first odd number > 10 is 11.
each subsequent odd number is two more than the previous.
you loop until you're greater than 100.
That would lead to the following pseudo-code:
set sum to 0
set num to 11
while num is less than or equal to 100:
add num to sum
add 2 to num
output sum
I'll leave converting that to a real language as an exercise for the reader.
Linq lets you express code in much more compact and readable way.
case 4:
Console.Write (Enumerable.Range(1,100).Where(v => v != 42).Sum());
If you need more basic code consider for instead of while as it represent iteration over ranges in more idiomatic way (and continue is likely what you are expected to use for 4 to skip numbers):
case 4:
{
var sum = 0;
for(var i = 1; i <= 20; i++)
{
if (i != 3)
continue;
sum += 0;
}
break;
}