Finding the right value for amount of digits in binary numbers - c#

I am trying to create a console application where the user inputs a base 10 number and the program outputs the number in binary.
I want to get the exact number of times to execute the for loop to get correct value (the value HERE in the code below).
I also have to reverse everything that the console is now outputting for everything to be correct but that I can do on my own later.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decimal_to_Binary
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
decimal Number = Decimal.Parse(NumberIn);
decimal[] Squared = new decimal[100];
for (int i = 0; i < HERE + 1; i++)
{
//Squared[i] = Math.Pow(2, i);
Squared[i] = 2 ^ i ;
if (Number == Squared[i])
{
Console.Write("1");
}
else
{
Console.Write("0");
}
}
Console.ReadKey();
}
}
}

A nice feature of logarithms is that they'll tell you the highest order bit (in the case of log2) or digit that is set for any number. You can use log2 to find out the highest order bit set and then shift the number repeatedly checking for the 0th bit and print the binary representation.
using System;
using System.Text;
namespace BinaryCount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number and the computer will convert it into binary.");
string NumberIn = Console.ReadLine();
int Number = Int32.Parse(NumberIn);
double loopCount = Math.Log(Number, 2); // Log2 of a number will tell you the highest order bit that's set
StringBuilder s = new StringBuilder();
for (int i = 0 ; i < loopCount ; ++i)
{
if (Number % 2 == 1)
s.Append("1");
else
s.Append("0");
Number = Number >> 1;
}
StringBuilder done = new StringBuilder();
for (int i = s.Length - 1 ; i >= 0 ; i--)
{
done.Append(s[i]);
}
Console.WriteLine(done);
Console.ReadLine();
}
}
}

Related

Getting User Input and Adding it to an array at C#

I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.

Struggling With Instructor Tutorial

I had an assignment that required me to request an array size from the user and then request numbers to fill the array. The program was to print only the unique numbers for each loop. It also would notify the user if the number they entered was a duplicate. I have completed this and it worked as it should. The instructor then posted a tutorial video on how it could/should have been written. That code is quite different from mine and I tried to rewrite it to understand her logic. I could not get it to work as the tutorial showed and I am not understanding some of the things she included. Can someone look at this and help me understand what she is trying to do and if it works as written?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DuplicateHandsOn
{
class Program
{
static void Main(string[] args)
{
//create an array of type int
int[] aList;
//create a counter to keep track of how many numbers have been entered
int counter = 0;
//create a boolean flag to let us know whether the number can be added or not
bool isDuplicate = false;
//ask the user how many numbers they will be entering
Console.WriteLine("How many numbers will you enter?");
int arraySize = Convert.ToInt32(Console.ReadLine());
//initialize the array with that amount
aList = new int[arraySize];
while (counter < arraySize)
{
//prompt the user for the first number
Console.Write("Enter Number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
//check if the number is between 10 and 100
if (num1 >= 10 || num1 <= 100)
{
//check if this number exists in the array
for (int i = 0; i < aList.Length; i++)
{
if (aList[i] == num1)
{
//this number exists in the list
Console.WriteLine("{0} has already been entered", aList[i]);
isDuplicate = true;
}
}
if (isDuplicate)
{
//put the number into the array
aList[counter] = num1;
}
//print the array
for (int j = 0; j < aList.Length; j++)
{
//exclude zeros
if (aList[j] == 0)
{
continue;
}
else
{
Console.WriteLine(aList[j]);
}
}
//increment the counter
counter++;
//reset the flag
isDuplicate = false;
}
else
{
Console.WriteLine("Numbers should be between 10 and 100");
}
}
#if DEBUG
Console.ReadKey();
#endif
}
}
}
There are three bugs in the code, and lots of style issues I'd have with it, but the bugs are easy to point out. I've added // FIX comments to show what I changed, hopefully it makes sense.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DuplicateHandsOn
{
class Program
{
static void Main(string[] args)
{
//create an array of type int
int[] aList;
//create a counter to keep track of how many numbers have been entered
int counter = 0;
//create a boolean flag to let us know whether the number can be added or not
bool isDuplicate = false;
//ask the user how many numbers they will be entering
Console.WriteLine("How many numbers will you enter?");
int arraySize = Convert.ToInt32(Console.ReadLine());
//initialize the array with that amount
aList = new int[arraySize];
while (counter < arraySize)
{
//prompt the user for the first number
Console.Write("Enter Number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
// FIX: This should be && instead of || to test if
// both of these conditions are true to match
// the comment
//check if the number is between 10 and 100
if (num1 >= 10 && num1 <= 100)
{
//check if this number exists in the array
for (int i = 0; i < aList.Length; i++)
{
if (aList[i] == num1)
{
//this number exists in the list
Console.WriteLine("{0} has already been entered", aList[i]);
isDuplicate = true;
}
}
// FIX: This should only happen if the number
// is not a duplicate
if (!isDuplicate)
{
//put the number into the array
aList[counter] = num1;
// FIX: Move this line into here to only increment
// the counter if th enumber is placed in the array
//increment the counter
counter++;
}
//print the array
for (int j = 0; j < aList.Length; j++)
{
//exclude zeros
if (aList[j] == 0)
{
continue;
}
else
{
Console.WriteLine(aList[j]);
}
}
//reset the flag
isDuplicate = false;
}
else
{
Console.WriteLine("Numbers should be between 10 and 100");
}
}
#if DEBUG
Console.ReadKey();
#endif
}
}
}

C# factorial calculator is not working right

My factorial calculator isn't working quite correctly.
It works as expected from 1 to 20, as my professor wants. However, entering 0 should return a factorial of 1; it returns 0
Here is my code:
private void CalculateFactorial(long number)
{
//perform the calculations
long result = number;
for (int i = 1; i < number; i++)
{
result = result * i;
}
//display the calculated Factorial to the user
txt_Factorial.Text = result.ToString("n0");
}
Here is the method which calls the above method, the event handler for the calculate button:
private void btn_Calculate_Click(object sender, EventArgs e)
{
//get the users input
long number = long.Parse(txt_Number.Text);
// make sure the number not invalid. If it is invalid, tell the user
// otherwise, proceed to calculation.
if (number < 0 || number > 20)
txt_Factorial.Text = "Invalid Number";
else
CalculateFactorial(number);
txt_Number.Focus(); // returns the focus to the number box whether or not data was valid
Ideas?
If you step through this in a debugger the problem becomes pretty clear. And as you're just getting started with programming I highly recommend getting used to a debugger as early as you can. It's an absolutely invaluable tool for programming.
Look at your for loop:
for (int i = 1; i < number; i++)
What happens when number is 0? The loop never runs. You can't include 0 in the loop range because that would set every result to 0 by first multiplying it by 0. So you need to add an explicit check for 0 in the function logic:
if (number == 0)
return 1;
// continue with your loop here
Factorial of 0 is 1 by definition, not by calculation, and your code does not reflect that. Add a check before your code:
if (number == 0)
result = 1;
else
// compute factorial
Also think about creating a function that returns an integer value as the result.
You can use this :
if(number == 0){
result = 1;
}
for (int i = 1; i <= number; i++)
result *= i;
}
also your formula is wrong because n! = 1*2*3*.....*n
You can test the following code! tested and works. Recursive Implementation as well as basic implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}

method to return largest integer c#

I'm having trouble with this method return of the largest integer, compiler says no errors but it won't let me run it
I have no clear idea what you are asking for.. I think at one time you had code but it is now gone?
Anyway, here is a console example for making an array and displaying its max value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//Declare i
int i;
Console.WriteLine("Please enter 5 random numbers");
//Make some array
string[] numbers = new string[5];
for (i = 0; i < 5; i++)
{
Console.Write("\nEnter your number:\t");
//Storing value in an array
numbers[i] = Console.ReadLine();
}
//ta da your array is now completed.. lets see what is the largest..
var converted = numbers.Select(int.Parse);
int largest = converted.Max();
//ta da
Console.WriteLine("The largest number is..." + (largest));
}
}
}

Add Numbers Until Palindromic

I've been working on a C# console application, and have successfully instituted a palindromic check based on the user inputing an int. I'm now having trouble with the condition involving addition of the user input and the reverse of said input. I want to continue checking for a palindromic number via this addition and then stop execution of the program when one is reached. My program appears to have difficulty saving the state of the reversed number, any help would be much appreciated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathPalindromeConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int num, temp, remainder, reverse = 0;
Console.WriteLine("Enter an integer \n");
num = int.Parse(Console.ReadLine());
bool palindromic = true;
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
Console.WriteLine("Given a number is = {0}", temp);
Console.WriteLine("Its reverse is = {0}", reverse);
while (palindromic)
{
if (temp == reverse)
{
Console.WriteLine("Number is a palindrome \n");
palindromic = false;
Console.ReadLine();
}
if (temp != reverse)
{
Console.WriteLine("Number is not a palindrome \n");
Console.WriteLine(temp += reverse);
Console.ReadLine();
}
}
}
}
}
I was going to say the same thing as L.B. He put it in a comment, so I'll put it here. Why not use:
bool pal = num.ToString() == new string(num.ToString().Reverse().ToArray());

Categories