I have the current coding and I feel as if it is close to what I need but I can't seem to get it to work for what I want. I am trying to get it to output the highest common factor of the two numbers entered.
i = myInt;
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
}
else
i--;
goto;
}
As others said in comments, you should really avoid goto statements because they are bad practice, especially when you are learning your college course of programming (that usually should conform to structural programming). Instead use while loop (or any other) with two conditions as you can see in the example. Also, I think that you should start your search from the smaller number (the first entered does not need to be smaller one) which is a little improvement in terms of performance. This is the code:
static void Main(string[] args)
{
string myInput;
int myInt;
string myInput2;
int myInt2;
int i;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
Console.Write("Please enter another number: ");
myInput2 = Console.ReadLine();
myInt2 = Int32.Parse(myInput2);
i = myInt > myInt2 ? myInt2 : myInt;
bool found = false;
while(!found && i>0)
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
found = true;
}
else
i--;
}
}
EDIT: I included the other possible solution thanks to #Servy
bool found = false;
for( i = Math.Min(myInt, myInt2); !found && i>0; i--)
{
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
found = true;
}
}
{
label:
if (myInt % i == 0 && myInt2 % i == 0)
{
Console.Write("Your GCF is...");
Console.Write("{0} ", i);
Console.ReadLine();
}
else
i--;
goto label;
}
will do. However, this is a very bad idea. Rather learn how to use while.
Related
why does my code not calculate an average score when entering "-1" into the console? It comes up at 0. It's a part of a loop exercise, so I'm sure there are faster ways to code this. I want to fix it within my current C# comprehension.
Here's the task
using System;
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
if(int.TryParse(individualScore, out individualScoreIntoInt) && individualScoreIntoInt > 0 && individualScoreIntoInt < 21)
{
totalScore += individualScoreIntoInt;
//longer way: totalScore = individualScoreIntoInt + totalScore;
}
else if(individualScoreIntoInt < 0 || individualScoreIntoInt < 20)
{
Console.WriteLine("Enter a score > 0 and < 21");
continue;
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
scoreCount++; // adding the individualscore entered to the count. writing it here so that it's only
//added to the count if it meets the requirements
}
}
}
}
Order of operations was incorrect:
1st validate if it's -1 or not,
2nd parse value and if it's possible perform below operations, if not drop error.
This was logic issue, rather than code itself.
You had added iteration despite exceptions, you didn't include possibility of 21 etc.
namespace Challenge_Loops1
{
internal class Program
{
static void Main(string[] args)
{
string individualScore = "0";
int scoreCount = 0;
int totalScore = 0;
int individualScoreIntoInt = 0;
while (individualScore != "-1")
{
Console.WriteLine($"Last number was {individualScoreIntoInt}");
Console.WriteLine("Please enter the next score");
Console.WriteLine($"Current amount of entries: {scoreCount}");
Console.WriteLine("Enter '-1' when you're ready to calculaate the average");
individualScore = Console.ReadLine();
if (individualScore.Equals("-1"))
{
Console.WriteLine("--------------------------------------------");
double averageScore = (double)totalScore / (double)scoreCount;
Console.WriteLine($"The average total score is {averageScore}");
}
else if (int.TryParse(individualScore, out individualScoreIntoInt))
{
if(individualScoreIntoInt > 0 && individualScoreIntoInt <= 21)
{
totalScore += individualScoreIntoInt;
scoreCount++;
}
//as mentioned in comment else here would also work, it's unnecessary to add any other validation.
else if (individualScoreIntoInt < 0 || individualScoreIntoInt > 21)
{
Console.WriteLine("Enter a score > 0 and < 21");
}
}
else
{
Console.WriteLine("Please only enter numbers");
}
}
}
}
}
For my C# programming homework, we had to write a program that allows the user to input an integer and use a loop to print out the factors of that integer.
I got the program to output the integers.
The problem is, for example, when I enter in the integer "24", I want the output to be
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
but the output that comes out is
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 and
I don't want the extra "and" at the end of my Factors List
Here is what my code looks like:
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
Console.Write(b + " ");
}
}
Console.ReadLine();
}
}
}
EDIT: The output has to be formatted as
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
or else I won't get credit for the assignment
You can enumerate factors, and then Join them with " and "
private static IEnumerable<int> Factors(int value) {
// Simplest, not that efficient
for (int i = 1; i <= value; ++i)
if (value % i == 0)
yield return i;
}
...
Console.Write(string.Join(" and ", Factors(24)));
Or you can add " and " before, not after printing factors (i)
int value = 24;
bool firstTime = true;
// Simplest, not that efficient
for (int i = 1; i <= value; ++i) {
if (value % i == 0) {
// print "and" before printing i
if (!firstTime)
Console.Write(" and ");
firstTime = false;
Console.Write(i);
}
}
How about adding the numbers to a List and printing after the loop:
int a, b;
a = int.Parse(Console.ReadLine());
var result = new List<int>();
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
result.Add(b);
}
}
Console.Write(string.Join(" and ", result));
static void Main(string[] args)
{
//get input from user
Console.WriteLine("Please enter your integer: ");
int a = int.Parse(Console.ReadLine());
//enumerate factors
var factors = Enumerable.Range(1, a)
.Where(i => a % i == 0).ToArray();
//join for nicely printed output
Console.Write(string.Join(" and ", factors));
Console.ReadLine();
}
I would recommend you to create a string and output that string becouse it allows you to do more things with it, then do something like this:
int a, b;
string x="";
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
x=x + b.toString() +" and";
}
}
if you know that always will be an "and" at the end you can simply do this
string x = x.Substring(0, x.Length - 3);
and then
Console.Write(x);
Console.ReadLine();
I'm on my first week of studying C#.
I guess there should be some way to use 1 "While()" condition instead of 2 in the code below. Is there any way to make my code more simple:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
while (num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}
You can use the OR operator to combine both conditions:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10 || num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}
I'm having problems with a task. I need to find and alert the user if the number is prime or not.
Here is my code:
int a = Convert.ToInt32(number);
if (a % 2 !=0 )
{
for (int i = 2; i <= a; i++)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
}
else
{
Console.WriteLine("prime");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("not prime");
}
Console.ReadLine();
Where did I go wrong, and how can I fix it?
Prime numbers is divisible by 1 and themselves you will need to check if number has exactly two divisor starting from one till number then it is prime.
int devisors = 0;
for (int i = 1; i <= a; i++)
if (a % i == 0)
devisors++;
if (devisors == 2)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You can skip one iteration as we know all whole numbers are divisible by 1 then you will have exactly on divisor for prime numbers. Since 1 has only one divisor we need to skip it as it is not prime. So condition would be numbers having only one divisor other then 1 and number should not be one as one is not prime number.
int devisors = 0;
for (int i = 2; i <= a; i++)
if (a % i == 0)
devisors++;
if (a != 1 && devisors == 1)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You just printed prime or not prime, and continued with the loop, rather than stopping. The %2 check is not really needed. Modified appropriately:
int a = Convert.ToInt32(number);
bool prime = true;
if (i == 1) prime = false;
for (int i = 2; prime && i < a; i++)
if (a % i == 0) prime = false;
if (prime) Console.WriteLine("prime");
else Console.WriteLine("not prime");
Console.ReadLine();
public bool isPrime(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return num == 1 ? false : true;
}
Presumably your code is outputting lots of messages, which seem jumbled and meaningless? There are 3 key issues:
You arn't breaking out of your for loop when you've decided it can't be prime
You are assuming it is prime when it might not be, see the comments in the code below.
You are comparing to a itself, and that will always be divisible by a, the <= in the for condition needs to be <
Code:
int a = Convert.ToInt32(number);
if (a % 2 != 0)
{
for (int i = 3 i < a; i += 2) // we can skip all the even numbers (minor optimization)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
goto escape; // we want to break out of this loop
}
// we know it isn't divisible by i or any primes smaller than i, but that doesn't mean it isn't divisible by something else bigger than i, so keep looping
}
// checked ALL numbers, must be Prime
Console.WriteLine("prime");
}
else
{
Console.WriteLine("not prime");
}
escape:
Console.ReadLine();
As other have mentioned, you could only loop to the square root of the a, by per-evaluating the square root and replacing this line:
for (int i = 3 i < a; i += 2)
with this:
float sqrRoot = (Int)Math.Sqrt((float)a);
for (int i = 3 i <= sqrRoot; i += 2)
It is important to per-evaluate it else your program will run much slower, rather than faster, as each iteration will involve a square root operation.
If you don't like goto statements (I love goto statements), post a comment and I'll replace it will a breakout boolean (or see Dukeling's more recent answer).
I've done far too much prime checking.
I did this:
bool isPrime = true;
List<ulong> primes = new List<ulong>();
ulong nCheck, nCounted;
nCounted = 0;
nCheck = 3;
primes.Add(2);
for (; ; )
{
isPrime = true;
foreach (ulong nModulo in primes)
{
if (((nCheck / 2) + 1) <= nModulo)
{ break; }
if (nCheck % nModulo == 0)
{ isPrime = false; }
}
if (isPrime == true)
{
Console.WriteLine("New prime found: " + (nCheck) + ", prime number " + (++nCounted) + ".");
primes.Add(nCheck);
}
nCheck++;
nCheck++;
}
This is not EXACTLY what you are looking for though, so what I'd do is put this in a background worker, but with the list of ulongs as a concurrent list, or something that you can access in 2 threads. Or just lock the list while it's being accessed. If the prime hssn't been worked out yet, wait until it is.
Yet another optimized way is to use Sieve of Eratosthenes algorithm.
From Wikipedia
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.
C# code
int[] GetPrimes(int number) // input should be greater than 1
{
bool[] arr = new bool[number + 1];
var listPrimes = new List<int>();
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (!arr[i])
{
int squareI = i * i;
for (int j = squareI; j <= number; j = j + i)
{
arr[j] = true;
}
}
for (int c = 1; c < number + 1; c++)
{
if (arr[c] == false)
{
listPrimes.Add(c);
}
}
}
return listPrimes.ToArray();
}
private static void checkpirme(int x)
{
for (int i = 1; i <= x; i++)
{
if (i == 1 || x == i)
{
continue;
}
else
{
if (x % i == 0)
{
Console.WriteLine(x + " is not prime number");
return;
}
}
}
Console.WriteLine(x + " is prime number");
}
where x is number to check it if prime or not
I have this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _121119_zionAVGfilter_Nave
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
}
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine(); }
}
}
The problem here is that if in the beginning I enter a negative or bigger than hundred number, I will get this message: "zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n".
If I then meenter -1, this what that shows up instead of the AVG: "Enter next zion, if you want to exit
tap -1 \n."
How can I solve this problem so when the number is negative or bigger than hundred and than tap -1 I will see the AVG an not another message?
You can just add a flag variable and it's done.
namespace _121119_zionAVGfilter
{
class Program
{
static void Main(string[] args)
{
int cnt = 0, zion, sum = 0;
double avg;
int flag = 0;
Console.Write("Enter first zion \n");
zion = int.Parse(Console.ReadLine());
while (zion != -1)
{
while (zion < -1 || zion > 100)
{
Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n");
zion = int.Parse(Console.ReadLine());
if(zion== -1)
flag = 1;
}
cnt++;
sum = sum + zion;
if (flag == 1)
break;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0) { }
}
if (cnt == 0)
{
Console.WriteLine("something doesn't make sence");
}
else
{
avg = (double)sum / cnt;
Console.Write("the AVG is {0}", avg);
}
Console.ReadLine();
}
}
}
Just enclose this code that you don't want to be executed in if statement like this
if(zion != -1)
{
cnt++;
sum = sum + zion;
Console.Write("Enter next zion, if you want to exit tap -1 \n");
zion = int.Parse(Console.ReadLine());
if (cnt != 0){}
}