How to count number of 1s without using an array? - c#

static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
int[] a = new int[m];
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1s in the Entered Number : "+count);
Console.ReadLine();
}
here get each value into the array, and check each value equal to one are not. But i need this task without using an array. Could you please help us.

Just check the input when it's entered, without storing it:
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
if(Console.ReadLine() == "1")
count++;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();
}

You can simply keep a count where you add it to the array
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
count += Console.ReadLine() == "1" ? 1 : 0;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();

You could use LINQ and remove the for loop as well as the array.
Console.WriteLine("Enter the Limit : ");
int m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
int count =
Enumerable
.Range(0, m)
.Select(n => Console.ReadLine())
.Where(x => x == "1")
.Count();
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();

I would advice using more meaningful variable names and adding input validation Int32.TryParse instead Convert.ToInt32.
Just do the if (o == 1) check in the first for and forget about the second one.

You can use List instead of array.
code is here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberofOnes
{
public class Program
{
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
List<int> a = new List<int>();
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a.Add( Convert.ToInt32(Console.ReadLine()));
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();
}
}
}

Related

How do I merge two arrays in C#?

Would it be possible to merge two arrays without using concat function or copy? I tried using copy but I'm looking for a method where it you don't need to use a function to merge two arrays. Thank you.
using System;
namespace console;
{
class Program
{
public static void Main()
{
try {
string input = "Enter the elements [{0}]: ";
//User input for integer
Console.Write("Please enter the first size of the array: ");
int yourfirstArray = Convert.ToInt32(Console.ReadLine());
int i;
string[] yourArrays = new string[yourfirstArray];
for (i = 0; i != yourArrays.Length; i++)
{
Console.Write(input, i, yourArrays[i]);
yourArrays[i] = Console.ReadLine();
}
Console.Write("Please enter the second size of the array: ");
int yoursecondArray = Convert.ToInt32(Console.ReadLine());
string[] myArrays = new string[yoursecondArray];
int j;
for (j = 0; j != myArrays.Length; j++)
{
Console.Write(input, j, yourArrays[j]);
yourArrays[j] = Console.ReadLine();
}
string[] thisMerged = new string[myArrays.Length + yourArrays.Length];
myArrays.CopyTo(thisMerged, 0);
yourArrays.CopyTo(thisMerged, myArrays.Length);
for (int k = 0; k != myArrays.Length; k++)
{
Console.Write("", i + myArrays[i], "", j + yourArrays[j]);
}
Console.ReadLine();
}
catch
{
Console.Write("Please input the correct data value.");
Console.ReadLine();
}
}
}
}

Exercise in C#,it doesn't work

this is the problem:You are given a sequence of positive integer numbers given as string of numbers separated by a space. Write a program, which calculates their sum. Example: "43 68 9 23 318" -> 461.
That's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercises2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int[] array;
for (i = 0; i < numbers.Length; i++)
{
array = new int[int.Parse(numbers[i])];
int s = Sum(array);
Console.Write("the sum of your numbers is: {0} ", s);
}
}
static int Sum(int[] array)
{
int sum = 0;
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
}
}
I dont know why it doesn't work,is giving me that the sum is 0.
Thank you.
The problem is:
array = new int[int.Parse(numbers[i])];
You actually create array with the length is the given numbers[i]. the array values are all 0. So
int s = Sum(array);
s is always 0.
The correct code is simple:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
s += int.Parse(numbers[i]);
}
Console.Write("the sum of your numbers is: {0} ", s);
Console.ReadLine();
}
}
You should only iterate on each element of your array of strings retrieved by .Split and sum.
working example .Net Fiddle:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine("Give some numbers");
string n = Console.ReadLine();
int sum = 0;
foreach(var i in n.Split(' ')){
sum += int.Parse(i);
}
Console.Write("the sum of your numbers is: {0} ", sum);
}
}
There is problem with the code where you getting the value of user given array in summation array as initialization of array.
array = new int[int.Parse(numbers[i])];
Here this is in loop array is initialized every time the value is getting. As per your input "43 68 9 23 318". Array will initialize by 43, then 68, then by 9 and so on. When array is initialized the values are by default 0 for int.
So Please refer this solution with proper null and integer check. Hope this will help you!.
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
if (numbers != null && numbers.Length > 0)
{
int[] array = new int[numbers.Length];
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
// Check if numbers[i] values is integer then add to array for some
int number;
bool result = Int32.TryParse(numbers[i], out number);
if (result)
{
array[i] = number;
}
}
s = Sum(array);
Console.Write("The sum of your numbers is: {0} ", s);
}
Console.Read();
}

Console (Input string was not in correct format)

Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}

Adding the sum of the entered numbers when you enter 0 in C#?

I am absolutely new to C# and I am at total lost. What I need to do is enter numbers as many as possible and keep entering but when you enter the value "0" that is when you add all the entered numbers all up.
This is my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
Console.WriteLine("The sum is: " + n);
}
Console.ReadLine();
}
}
}
Some advices:
The while loop is a better practice than the do..while loop.
You should use the int.TryParse method for input validation.
You should calculate sum of numbers inside loop.
You can solve the problem with only two int variables: n for readed numbers and sum for numbers sum.
For example, you can solve your problem with the following code:
static void Main(string[] args)
{
int sum = 0;
while (true)
{
Console.WriteLine("Enter a Number: ");
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
if (n == 0)
break;
sum += n;
}
}
Console.WriteLine("The sum is: " + sum);
}
you can simply do that with do ... while ... loop.
private static void Main(string[] args)
{
int n, sum = 0;
do
{
Console.WriteLine("Enter a number:");
n = Convert.ToInt32(Console.ReadLine());
sum += n;
} while (n != 0);
Console.WriteLine("Sum is:"+sum);
Console.ReadKey();
}
ConvertToInt32() is a method for converting a string to int32 (int).
You print the sum outside while loop.
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
}
Console.WriteLine("The sum is: " + n);
Console.ReadLine();
}
}
}

Calculating factorials in C#

I am trying to write a program that will take the users input value and asks whether they want to calculate the value of the numbers 1 to n or the factorial of n!
This is what I have so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_2_Part_B
{
class Program
{
static void Main(string[] args)
{
var Fkeylow = "f";
var FkeyCap = "F";
var Skeylow="s";
var SkeyCap="S";
int n = 0;
long factorial = n;
Console.WriteLine("Input a value n");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Do you want to calculate factorial or sum");
Console.WriteLine("Enter F or S");
var A = Console.ReadLine();
if (A == Fkeylow)
Console.WriteLine();
if (A == FkeyCap)
Console.WriteLine();
var B=Console.ReadLine();
if (B == Skeylow)
Console.WriteLine();
if (B == SkeyCap)
Console.WriteLine();
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
}
}
My issue is with the syntax of the calculation to make the code execute the n*(n-1) while n>1.
static void Main(string[] args)
{
Console.WriteLine("Input a value n");
string number = Console.ReadLine(); // Read number
int n = Convert.ToInt32(number); // Converting to int
Console.WriteLine("Do you want to calculate factorial or sum? ");
Console.WriteLine("Enter F or S. ");
string choose = Console.ReadLine(); // F or S
int result = -1; // To view later
if (choose == "f" || choose == "F")
{
result = 1;
for (int i = n; i >= 1; i--) // Loop for calculating factorial
result *= i;
}
else if (choose == "s" || choose == "S")
{
result = 0;
for (int i = n; i >= 1; i--) // Loop for calculating sum
result += i;
}
Console.WriteLine(result); // Printing answer
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
Using recursion is another way of doing it:
static void Main(string[] args)
{
int n = 5;
Console.WriteLine(factorial(n));
Console.WriteLine(sum(n));
Console.Read();
}
public static int sum(int n)
{
if(n==0)
return 0;
return n+sum(n-1);
}
public static int factorial(int n)
{
if (n == 1)
return 1;
return n * factorial(n - 1);
}
Prints:
120 -->5!
15 -->1+2+3+4+5
Basic solution is here, tested,
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("Factorial of six is :" + manipulator.factorial(16));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
}
}

Categories