Alternating Odd Even or Even Odd in C# - c#

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

Related

Write a program that determines whether two or more consecutive numbers are equal

Write a program that determines whether, in a sequence of N numbers entered by the user, if two or more consecutive numbers are equal. Print out, if any, the position of the first elements of the sequence of equal numbers.
This is what i got so far but it isn't working for some reason. What am I doing wrong?
using System;
public class Exercises
{
static void Main()
{
Console.WriteLine("Insert the length of the sequence of numbers:");
int n = Convert.ToInt32(Console.ReadLine());
List<int> seq = new List<int>();
int equalSeqStart = -1;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Insert the number in position" + (i + 1) + ":");
seq.Add(i);
if ((seq[i] == seq[i - 1]) && (equalSeqStart == -1))
{
equalSeqStart = i - 1;
}
}
if (equalSeqStart != -1)
{
Console.WriteLine("The sequence of equal numbers starts at" + (equalSeqStart));
}
else
{
Console.WriteLine("There is no sequence of equal numbers");
}
}
}
All you have to do is to compare prior item with current one; you have no need in collections:
static void Main() {
Console.WriteLine("Insert the length of the sequence of numbers:");
//TODO: int.TryParse is a better choice
int n = int.Parse(Console.ReadLine());
int equalSeqStart = -1;
for (int i = 0, prior = 0; i < n; ++i) {
Console.WriteLine($"Insert the number in position {i + 1}:");
//TODO: int.TryParse is a better choice
int current = int.Parse(Console.ReadLine());
if (i > 0 && equalSeqStart < 0 && current == prior)
equalSeqStart = i;
prior = current;
}
if (equalSeqStart != -1)
Console.WriteLine($"The sequence of equal numbers starts at {equalSeqStart}");
else
Console.WriteLine("There is no sequence of equal numbers");
}

While loop, sum the fifth, tenth, fifteenth...etc number

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) {
...

Ask user for starting and stopping point within the array?

In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();

sort without Array.Sort

I just barely understood how to use if statement and "for loop." In addition right now I have to do this
Sort the integer elements within the array from lowest (element 0) to highest (element 4). Do not use the preexisting Array.Sort method; code your own.
This is a homework problem and I don't even know where to start. Can somebody walk me through this?
class Program
{
static void Main(string[] args)
{
int i;
double power = 0, sum = 0;
int[] mArray = new int[5];
Console.WriteLine("Please Enter Number Between 10 and 50 \nMake sure all of your Number entered correctly \notherwise you will need to enter everything again ");
for (i = 0; i < mArray.Length; i++)
{
Console.WriteLine("Please enter your Number.");
mArray[i] = Convert.ToInt32(Console.ReadLine());
if (mArray[i] >= 50 || mArray[i] <= 10)
{
i--;
Console.WriteLine("Please enter numbers only between 10 and 50.");
}
}
for (i = 0; i < mArray.Length; i++)
{
sum = sum + (mArray[i]);
}
double mean = sum / mArray.Length;
for (i = 0; i < mArray.Length; i++)
{
power += Math.Pow((mArray[i] - mean), 2);
}
double rMean = power / (mArray.Length - 1);
Console.WriteLine("Mean {0}", mean);
Console.WriteLine("Variance {0}", rMean);
Console.WriteLine("Here is sorted numbers");
Console.ReadKey();
}
}
There are many sorting algorithms you can try like Insertion Sort
Selection Sort,
Bubble Sort,
Shell Sort,
Merge Sort,
Heap Sort,
Quick Sort,
And many Others.

Checking for a prime number

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

Categories

Resources