C#: Calculate win condition in console [duplicate] - c#

This question already has an answer here:
How can i check the winner in the my Connect four java code? [closed]
(1 answer)
Closed 4 years ago.
I got an assignment to program connect-4 in console. I have already programmed the board, but I am having a very hard time calculating the winner.
This is what I got so far:
// Array play board
int[,] intRaster = new int[6,7];
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
Label_0:
Console.Write(" \n\n\t\t\t Speler 1: Maak uw zet!");
// Player 1
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("1");
Console.SetCursorPosition(60, 13);
}
// Gives error message if player tries to put a disk in a
// full colom
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_0;
}
// Player 2
Label_1:
Console.Write(" \n\n\t\t\t Speler 2: Maak uw zet!");
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("2");
Console.SetCursorPosition(60, 13);
}
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_1;
}
goto Label_0;
So what I basicly did was declaring a 2 dimensional integer array [6,7].
The for loop will display the gameboard with the values of the array (which at the start would be 0 for every value).
Then the switch will read de character input of the player. If player 1 presses 1 the value 0 ([6, 0]) will be replaced by 1 etc...
Of course the switch contains more cases, but I left those out to shorten this code. So how do I calculate the winner horizontal, vertical and diagonally?
Any help will be much appreciated!

Here you are, I got overexcited.. :-)
class Game
{
static int[,] intRaster = new int[6, 7];
static int[] positionsDiskCount = new int[7];
public static void Main()
{
// Array play board
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
while (true)
{
MakeMove(1);
MakeMove(2);
}
}
static private int MakeMove(int Player)
{
Console.Write(" \n\n\t\t\t Speler {0}: Maak uw zet! ", Player);
int num = -1;
bool moveMade = false;
while (!moveMade)
{
while (true)
{
string key = Console.ReadKey(true).KeyChar.ToString();
if (key == "\u001b") Environment.Exit(0);
if (int.TryParse(key, out num) && num > -1 && num < 8) break;
}
num--;
if (positionsDiskCount[num] < 6)
{
intRaster[num, positionsDiskCount[num]] = Player;
Console.SetCursorPosition(32 + num * 2, 9 - positionsDiskCount[num]);
Console.Write(Player);
Console.SetCursorPosition(60, 10);
bool win = CheckWinner(num, positionsDiskCount[num]);
if (win)
{
Console.WriteLine(" \n\n\t\t\t Speler {0} has won the game!!!!!!", Player);
Console.WriteLine("Press any key to exit");
Console.ReadKey(true).KeyChar.ToString();
Environment.Exit(0);
}
positionsDiskCount[num]++;
moveMade = true;
}
else
{
Console.SetCursorPosition(60, 10);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!! Maak uw zet!");
Console.ReadKey();
Console.SetCursorPosition(60, 10);
}
}
return num;
}
static public bool CheckWinner(int x, int y)
{
//Horizontal
int count = countDirection(x, y, -1, 0);
count += countDirection(x, y, 1, 0);
if (count > 2) return true;
count = countDirection(x, y, 0, -1);
count += countDirection(x, y, 0, 1);
if (count > 2) return true;
count = countDirection(x, y, -1, -1);
count += countDirection(x, y, 1, 1);
if (count > 2) return true;
count = countDirection(x, y, 1, -1);
count += countDirection(x, y, -1, 1);
if (count > 2) return true;
return false;
}
static public int countDirection(int x, int y, int stepX, int stepY)
{
int count = 0;
int Player = intRaster[x, y];
x += stepX;
y += stepY;
while (x >= 0 && x < intRaster.GetUpperBound(1) && y >= 0 && y < intRaster.GetUpperBound(0))
{
if (Player == intRaster[x, y]) count++;
else break;
x += stepX;
y += stepY;
}
return count;
}
}

Related

Sum of value in lists using c# -- BlackJack

I'm creating this Blackjack game and I'm having trouble calculating the total value of both the dealer and player. I've created a method to calculate the value for both the player(PlayerTotalCalculate) and the dealer (DealerTotalCalculate) using forloops.
When I run the program, the first sequence of cards are added up correctly, but when I "HIT" to get a new card for the player, it takes the previous value shown and adds the new card given as well as the value of the 2 cards given previously..
using System;
using System.Collections.Generic;
namespace BlackJack2
{
internal class Program
{
//GLOBAL VARIABLES
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
enum Phase { StartGame, DealersFirst, PlayersTurn, DealersTurn, ChooseWinner, End }
static Phase currentPhase;
static int userInput;
static void Main(string[] args)
{
string suitFace = "";
int dealersTotalValue = 0;
int playersTotalvalue = 0;
//Creating the list of cards
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
suitFace = "Diamonds";
break;
case 1:
suitFace = "Spades";
break;
case 2:
suitFace = "Hearts";
break;
case 3:
suitFace = "Clubs";
break;
}
myListOfCards.Add(new Card("King", suitFace, 10));
myListOfCards.Add(new Card("Queen", suitFace, 10));
myListOfCards.Add(new Card("Jack", suitFace, 10));
myListOfCards.Add(new Card("10", suitFace, 10));
myListOfCards.Add(new Card("9", suitFace, 9));
myListOfCards.Add(new Card("8", suitFace, 8));
myListOfCards.Add(new Card("7", suitFace, 7));
myListOfCards.Add(new Card("6", suitFace, 6));
myListOfCards.Add(new Card("5", suitFace, 5));
myListOfCards.Add(new Card("4", suitFace, 4));
myListOfCards.Add(new Card("3", suitFace, 3));
myListOfCards.Add(new Card("2", suitFace, 2));
myListOfCards.Add(new Card("Ace", suitFace, 1));
}
for (int i = 0; i < playersHand.Count; i++)
{
playersHand.Remove(playersHand[i]);
}
for (int i = 0; i < dealersHand.Count; i++)
{
dealersHand.Remove(dealersHand[i]);
}
//Assigning the first phase
currentPhase = Phase.DealersFirst;
DealersTurn(dealersTotalValue, playersTotalvalue);
}
//Deal Card Method using Random Number Generator
static void DealCard(int dealerTotalValue, int playersTotalValue)
{
Random r = new Random();
int randomNumber = r.Next(0, myListOfCards.Count);
if (currentPhase == Phase.DealersFirst || currentPhase == Phase.DealersTurn)
{
dealersHand.Add(myListOfCards[randomNumber]);
}
else if (currentPhase == Phase.PlayersTurn)
{
playersHand.Add(myListOfCards[randomNumber]);
//PlayerTotalCalulate(ref playersTotalValue);
}
myListOfCards.RemoveAt(randomNumber);
}
//Determining dealer's actions
static void DealersTurn(int dealersTotalvalue, int playersTotalValue)
{
if (currentPhase == Phase.DealersFirst)
{
for (int i = 0; i < 1; i++)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
}
DisplayDealerCards();
Console.WriteLine($"The dealer has a total value of: {dealersTotalvalue}");
currentPhase = Phase.PlayersTurn;
PlayersTurn(dealersTotalvalue, playersTotalValue);
}
else if (currentPhase == Phase.DealersTurn)
{
while (dealersTotalvalue < 15)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
DisplayDealerCards();
Console.WriteLine($"The dealer's new total is: {dealersTotalvalue}");
}
CalculateWinner(dealersTotalvalue, playersTotalValue);
}
}
static void PlayersTurn(int dealersTotalValue, int playersTotalValue)
{
for (int i = 0; i < 2; i++)
{
DealCard(dealersTotalValue, playersTotalValue);
}
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You have a total value of: {playersTotalValue}");
while (currentPhase == Phase.PlayersTurn)
{
Console.WriteLine("Would you like to hit or stay?");
Console.WriteLine("1: HIT or 2: STAY");
int.TryParse(Console.ReadLine(), out userInput);
if (userInput == 1)
{
DealCard(dealersTotalValue, playersTotalValue);
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You now have a total value of: {playersTotalValue}");
}
else if (userInput == 2)
{
currentPhase = Phase.DealersTurn;
DealersTurn(dealersTotalValue, playersTotalValue);
}
else
{
Console.WriteLine("Invalid input! Please try again.");
}
}
}
static void DisplayPlayerCards(int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
Console.WriteLine($"You were dealt a(n): {playersHand[i].DisplayCard()}");
}
PlayerTotalCalulate(ref playersTotalValue);
}
static void DisplayDealerCards()
{
//Showing only one card from the dealer
for (int i = 0; i < dealersHand.Count; i++)
{
Console.WriteLine($"The dealer is showing: {dealersHand[i].DisplayCard()}. The other card is hidden.");
}
}
static void CalculateWinner(int dealersTotalvalue, int playersTotalValue)
{
if (playersTotalValue > dealersTotalvalue && playersTotalValue < 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Great job! You've won!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue == dealersTotalvalue)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("The game is a tie!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue < dealersTotalvalue && playersTotalValue > 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Oh no! You've lost!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
//Console.WriteLine(PlayerTotalCalulate(ref playersTotalValue));
}
static void PlayerTotalCalulate(ref int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
playersTotalValue += playersHand[i].Value;
}
}
static void DealerTotalCalculate(ref int dealersTotalValue)
{
for (int i = 0; i < dealersHand.Count; i++)
{
dealersTotalValue += dealersHand[i].Value;
}
}
static void DisplayAllCards()
{
for (int i = 0; i < myListOfCards.Count; i++)
{
Console.WriteLine(myListOfCards[i].DisplayCard());
Console.WriteLine("\n\r\t");
}
}
static void DisplayingSingleCard()
{
Console.WriteLine(myListOfCards[0].DisplayCard());
}
}
}
I've also provided a screenshot of the console itself.
ConsolePicture
In DealerTotalCalculate, you should set dealersTotalValue to 0 before you add up the cards.
You need to do that in PlayerTotalCalulate as well.
As said in my comment, it's because your total variable is never reseted. So when you call the method to add the new value, it takes also the old value into consideration. So you just need to do total = 0, before calling the compute method.
Also consider this to simplify your compute method :
int[] array = { 1, 2, 3, 4, 5 };
int sum = array.Sum();
Console.WriteLine(sum);
It's slightly better, regarding code readability in my opinion. Not a big deal at all.

Simple console lotto game c# match arrays

I'm trying to make a simple lotto/bingo game in c#.
Trying to make something like this:
Game where user types in 10 numbers which gets stored to an array.
Then the game makes a "lotto card" which is a 2 dimensional array with random numbers, like this:
10 | 13 | 14 | 17 | 16
18 | 24 | 21 | 23 | 8
1 | 3 | 6 | 25 | 9
7 | 22 | 15 | 12 | 2
4 | 5 | 11 | 19 | 20
Now i want to compare the contents of both arrays. I cant seem to find a way to do this with both 1 and 2 dimensionall arrays? Right now i've only managed to check if one of the numbers match.
Have tried using Linq and enumerabl and different loops in a couple of ways but with no success.
I want the game to register bingo if i match the numbers horizontally, vertically and diagonally.
This is my code so far:
static void Main(string[] args)
{
// Greet and explain the rules
Console.WriteLine("Welcome to bingo!");
string input; // Variabel for input by user
int inputnmr; // Variabel for nmrinput by user
int low = 1;
int high = 25;
int[] userNmr = new int[7]; // Creates a new array for the player
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
for (int i = 0; i < userNmr.Length; i++)
{
Console.Write("Type in a number between {0} - {1}:", low, high);
input = Console.ReadLine();
inputnmr = int.Parse(input);
userNmr[i] = inputnmr;
}
//Prints your lotto numbers:
Console.Write("These are your numbers :");
foreach (int i in userNmr)
{
Console.Write(i);
Console.Write(", ");
}
//Asks if continue:
Console.WriteLine("Are you sure about your numbers?");
Console.WriteLine("Do you want a bingo card?");
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] lottoCard = new int[x, y];
//Create random
Random randomnmr = new Random();
//Prints the lotto cards x-axis
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" |------------------------|");
Console.Write(" | ");
//Prints the lotto card y-axis
for (int j = 0; j < 5; j++)
{
//Fills lotto card with random ints:
lottoCard[i, j] = randomnmr.Next(1, 26);
Console.Write(lottoCard[i, j] + " | ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" |------------------------|");
// --- This is where im stuck ---
bool oneMatch = false;
while (oneMatch == false)
{
foreach (var numberA in userNmr)
{
foreach (var numberB in lottoCard)
{
if (numberA == numberB)
{
oneMatch = true;
}
}
}
}
if (oneMatch == true)
{
Console.WriteLine("BINGO!");
}
else
{
Console.WriteLine("No win . . .");
}
Things i've tried:
1:
bool equal = lottoCard.Rank == userNmr.Rank && Enumerable.Range(0, lottoCard.Rank).All(dimension => lottoCard.GetLength(dimension) == lottoCard.GetLength(dimension)) && lottoCard.Cast<double>().SequenceEqual(lottoCard.Cast<double>());
if (equal == true)
{
Console.WriteLine("Bingo");
}
else
{
Console.WriteLine("no win");
}
2:
bool IsContain(int[][] lottoCard, int[] userNmr)
{
foreach (int[] row in lottoCard)
{
int curlIndex = 0;
foreach (int item in row)
{
if (item == userNmr[curlIndex])
{
if (curlIndex == userNmr.Length - 1)
{
return true;
}
curlIndex++;
}
else
{
curlIndex = 0;
}
return false;
}
}
}
if (IsContain(lottoCard, userNmr))
{
Console.WriteLine("BINGO");
}
else
{
Console.WriteLine("No win");
}
Above does not work, would really appreciate some help!
Here's how I would have done it:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to Bingo!");
int[] userNmr = getUserInput();
int[,] bingoCard = genBingoCard();
Console.WriteLine();
Console.WriteLine("Your number selections are:");
Console.WriteLine(String.Join(", ", userNmr));
Console.WriteLine();
Console.WriteLine("Here is your Bingo Card!");
displayBingoCard(bingoCard);
bool bingo = checkForBingo(userNmr, bingoCard);
if (bingo)
{
Console.WriteLine("Congratulations! You had a Bingo!");
}
else
{
Console.WriteLine("Sorry, no Bingos. Better luck next time!");
}
Console.WriteLine();
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
public static int[] getUserInput()
{
int low = 1;
int high = 25;
string input;
int inputnmr;
int[] userNmr = new int[7];
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
bool valid;
for (int i = 0; i < userNmr.Length; i++)
{
valid = false;
while (!valid)
{
Console.WriteLine();
Console.WriteLine("User Selection #" + (i + 1));
Console.Write("Select a number between {0} - {1}: ", low, high);
input = Console.ReadLine();
if (int.TryParse(input, out inputnmr))
{
if (inputnmr >= low && inputnmr <= high)
{
if (!userNmr.Contains(inputnmr))
{
userNmr[i] = inputnmr;
valid = true;
}
else
{
Console.WriteLine("You already picked that number!");
}
}
else
{
Console.WriteLine("Number must be between {0} and {1}!", low, high);
}
}
else
{
Console.WriteLine("Invalid Number.");
}
}
}
return userNmr;
}
public static int[,] genBingoCard()
{
Random randomnmr = new Random();
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] bingoCard = new int[y, x];
List<int> numbers = Enumerable.Range(1, x * y).ToList();
numbers = numbers.OrderBy(z => randomnmr.Next()).ToList();
int counter = 0;
for (int r = 0; r < y; r++)
{
for (int c = 0; c < x; c++)
{
bingoCard[r, c] = numbers[counter++];
}
}
return bingoCard;
}
public static void displayBingoCard(int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
string line = "";
for (int c = 0; c < x; c++)
{
line = line + "+----";
}
line = line + "+";
Console.WriteLine(line);
for (int r = 0; r < y; r++)
{
Console.Write("|");
for (int c = 0; c < x; c++)
{
Console.Write(" " + bingoCard[r, c].ToString("00") + " |");
}
Console.WriteLine();
Console.WriteLine(line);
}
}
public static bool checkForBingo(int[] userNmr, int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
bool bingo;
// check each row
for (int r = 0; r < y; r++)
{
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Horizontal Bingo at Row: " + (r+1));
return true;
}
}
// check each column
for (int c = 0; c < x; c++)
{
bingo = true; // until proven otherwise
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Vertical Bingo at Column: " + (c+1));
return true;
}
}
// check diagonals
// top left to bottom right
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Left to Bottom Right.");
return true;
}
// top right to bottom left
bingo = true; // until proven otherwise
for (int c = (x-1); c >= 0 && bingo; c--)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Right to Bottom Left.");
return true;
}
// no bingos were found!
return false;
}
}

must save the position of the array element

I used the translator. I'm sorry.
Hello!
C# I'm a beginner.
Please help me because I'm having a hard time writing....
Whenever the coordinates of the array change, I want to save the changed coordinates in a different array.
What should I do?
Please advise.
You just have to show the direction.
Thank you!
string size = Console.ReadLine();
int Consize = Convert.ToInt32(size);
int[,] array = new int[Consize, Consize];
for (int i = 0; i < Consize; i++)
{
string value = Console.ReadLine();
string[] result = value.Split();
for (int j = 0; j < result.Length; j++)
{
int value2 = Convert.ToInt32(result[j]);
array[i, j] = value2;
this is an array A that stores the entered array.
int x = 0, y = 0;
string movePath = "";
int _max = 0;
while (x != Consize && y != Consize)
{
int[,] _array = new int[x, y];
int max = -101;
int[] temp = new int[4] { -101, -101, -101, -101 };
if (x - 1 > 0)
temp[0] = array[x - 1, y];
if (y - 1 > 0)
temp[1] = array[x, y - 1];
if (x + 1 < Consize)
temp[2] = array[x + 1, y];
if (y + 1 < Consize)
temp[3] = array[x, y + 1];
int index = 0;
for (int i = 0; i < temp.Length; i++)
{
if (max < temp[i])
{
max = temp[i];
index = i;
}
}
switch (index)
{
case 0:
movePath += "U";
_max += temp[0];
x--;
break;
case 1:
movePath += "L";
_max += temp[1];
y--;
break;
case 2:
movePath += "D";
_max += temp[2];
x++;
break;
case 3:
movePath += "R";
_max += temp[3];
y++;
break;
default:
break;
}
Compare each element of the array
They move on to the big factor.
I want to save the coordinates of the moving element in a different arrangement.

Don't allow different option

I got stuck with a small problem. I create a program where the user must to choose 5 options( 1.input numbers 2. Show smallest 3. Show Greatest 4. Display all numbers 5 Quit.)
All the option are working. The problem is that when the user is choosing the option, if the press any letters is giving me error. I want that if the user is pressing any letter ori any symbol to be a warning message like "Unknown option value entered" and to try again. I suppose is about conversion or something similar, but i can't find where is the problem.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignmen2014_15
{
class Program
{
const int MAXNUMBERS = 3;
static void Main(string[] args)
{
int[] theNumbers = new int[MAXNUMBERS];
int chosenOption = 0;
bool quit = false;
InitialiseNumbers(theNumbers);
while (quit == false)
{
DisplayHeader();
DisplayMenu();
chosenOption = ReadNumber("Please choose an option: ");
quit = ProcessMenu(chosenOption, theNumbers);
Console.Clear();
}
}
static void InitialiseNumbers(int[] numbers)
{
for (int index = 0; index < MAXNUMBERS; index++)
{
numbers[index] = 0;
}
}
static void DisplayHeader()
{
WriteText("*******************************************************************************", 0, 0); // Top left hand corner of screen is x = 0, y = 0;
WriteText("* This application is designed to allow you to choose numbers *", 0, 1); // Next line down is x = 0, y = 1, etc WriteText("* and finds the biggest and the smallest value *", 0, 2);
WriteText("*******************************************************************************", 0, 3);
}
static void DisplayMenu()
{
WriteText("Select an option", 20, 8); // Display menu at at x = 20, y = 8
WriteText("1. Enter the numbers", 20, 9);
WriteText("2. Find the smallest", 20, 10);
WriteText("3. Find the largest", 20, 11);
WriteText("4. Display all numbers", 20, 12);
WriteText("5. Quit", 20, 13);
}
static void WriteText(string text, int x, int y)
{
Console.CursorLeft = x;
Console.CursorTop = y;
Console.Write(text);
}
static int ReadNumber(string prompt)
{
string text;
int number;
WriteText(prompt, 20, 14);
text = Console.ReadLine();
number = int.Parse(text);
ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
return number;
}
static void ClearText(int x, int y, int length)
{
// Write space ' ' characters starting at x, y for 'length' times
WriteText(new String(' ', length), x, y);
}
static void DisplayNumbers(int[] theNumbers)
{
Console.Write("Your numbers are: ");
for (int i = 0; i < MAXNUMBERS; i++)
{
Console.WriteLine(theNumbers[i]);
}
}
static bool ProcessMenu(int option, int[] numbers)
{
bool quit = false;
switch (option)
{
case 1:
GetNumbers(numbers);
break;
case 2:
WriteText(string.Format("The smallest value is {0}", FindSmallest(numbers)), 20, 15);
Console.ReadKey(); // Pause
break;
case 3:
WriteText(string.Format("The largest value is {0}", FindLargest(numbers)), 20, 15);
Console.ReadKey(); // Pause
break;
case 4:
DisplayNumbers(numbers);
Console.ReadKey();
break;
case 5:
quit = IsQuitting();
break;
default:
WriteText("Unknown option value entered", 20, 15);
Console.ReadKey(); // Pause
break;
}
return quit;
}
static void GetNumbers(int[] numbers)
{
for (int index = 0; index < MAXNUMBERS; index++)
{
numbers[index] = ReadNumber("Enter number: ");
}
}
static int FindSmallest(int[] numbers)
{
int smallest = numbers[0];
for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
{
if (numbers[index + 1] < smallest)
{
smallest = numbers[index + 1];
}
}
return smallest;
}
static int FindLargest(int[] numbers)
{
int largest = numbers[0];
for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
{
if (numbers[index + 1] > largest)
{
largest = numbers[index + 1];
}
}
return largest;
}
static bool IsQuitting()
{
string response;
bool quit = false;
WriteText("Do you really wish to quit? ", 20, 13);
response = Console.ReadLine();
if (response.Equals("Yes" , StringComparison.InvariantCultureIgnoreCase) || response.Equals("Y", StringComparison.InvariantCultureIgnoreCase))
{
quit = true;
}
return quit;
}
}
}
Use Int32.TryParse(String, Int32) method which tries to parse string into integer and returns boolean value representing if parsing was successful or not. In your case, if parsing fails, you can return -1 from your ReadNumber method which will call default: part of your switch case and an error message will be displayed. Otherwise, if parsing was successful, you can simply return the parsed number, which will be either be one of your desired numbers or it will call default: action.
The following is example from Microsoft documentation
String[] values = { null, "160519", "9432.0", "16,667",
" -322 ", "+4302", "(100);", "01FA" };
foreach (var value in values)
{
int number;
bool success = Int32.TryParse(value, out number);
if (success)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
value ?? "<null>");
}
}
In your specific example you need to modify your ReadNumber(string prompt) method:
static int ReadNumber(string prompt)
{
string text;
int number;
WriteText(prompt, 20, 14);
text = Console.ReadLine();
bool is_parsing_successful = Int32.TryParse(text, out number);
ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
if(is_parsing_successful){
return number;
} else {
return -1;
}
}

c# program for finding if number is prime

I have this task: Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime.
int number = int.Parse(Console.ReadLine());
for (int i = 1; i < 100; i++)
{
bool isPrime = (number % number == 0 && number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
}
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
}
This doesn't seem to work. Any suggestioins?
int number = int.Parse(Console.ReadLine());
bool prime = true;
// we only have to count up to and including the square root of a number
int upper = (int)Math.Sqrt(number);
for (int i = 2; i <= upper; i++) {
if ((number % i) == 0) {
prime = false;
break;
}
}
Console.WriteLine("Number {0} is "+ (prime ? "prime" : "not prime"), number);
a. What are you expecting number % number to do?
b. Your isPrime check is "reset" each time through the loop. Something more like this is required:
bool isprime = true;
for(int i = 2; i < number; i++) {
// if number is divisible by i then
// isprime = false;
// break
}
// display result.
The problems are:
the for should start from 2 as any number will be dived by 1.
number % number == 0 - this is all the time true
the number is prime if he meats all the for steps so
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
shold not be there.
The code should be something like this:
int number = int.Parse(Console.ReadLine());
if (number == 1)
{ Console.WriteLine("Number 1 is prime");return;}
for (int i = 2; i < number / 2 + 1; i++)
{
bool isPrime = (number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
return;
}
}
Console.WriteLine("Number {0} is prime", number);
please notice that I didn't test this...just wrote it here. But you should get the point.
Semi-serious possible solution with LINQ (need smaller range at least):
var isPrime = !Enumerable.Range(2, number/2).Where(i => number % i == 0).Any();
The Program checks the given number is prime number or not.
A prime number is a number that can only be divided by 1 and itself
class Program
{
bool CheckIsPrimeNumber(int primeNum)
{
bool isPrime = false;
for (int i = 2; i <= primeNum / 2; i++)
{
if (primeNum % i == 0)
{
return isPrime;
}
}
return !isPrime;
}
public static void Main(string[] args)
{
Program obj = new Program();
Console.Write("Enter the number to check prime : ");
int mPrimeNum = int.Parse(Console.ReadLine());
if (obj.CheckIsPrimeNumber(mPrimeNum) == true)
{
Console.WriteLine("\nThe " + mPrimeNum + " is a Prime Number");
}
else
{
Console.WriteLine("\nThe " + mPrimeNum + " is Not a Prime Number");
}
Console.ReadKey();
}
}
Thanks!!!
Here is for you:
void prime_num(long num)
{
bool isPrime = true;
for (int i = 0; i <= num; i++)
{
for (int j = 2; j <= num; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine ( "Prime:" + i );
}
isPrime = true;
}
}

Categories