How to get the number of elements in an int array? - c#

in this case I want to take the number of elements in the array , but the array is dependent on user input
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
for (int i = first; i <= second; i++)
{
if (i % 5 == 0)
{
int[] some =new int [i];
int c =some.Length;
Console.WriteLine(c);
}
}
I tried several options, but the output is still a list of the numbers divisible by 5 without remainder. How is right to do?
example: first = 15, second = 50.
Expected output = 8.
8 numbers divisible by 5 without remainder(15,20,25,30...50)

You can just loop through the numbers and count how many you find that are divisible by 5:
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
int cnt = 0;
for (int i = first; i <= second; i++) {
if (i % 5 == 0) {
cnt++;
}
}
However, you dont have to generate the numbers to know how many there are. You can just calculate where the last number is (as that is easier than the first) and then calculate how many there are before that but after the first:
int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
second -= second % 5;
int cnt = (second - first) / 5 + 1;
For example for the input 3 and 11 you want to count the numbers 5 and 10. The expression 11 % 5 gives 1, so second becomes 10 (the last number). Then second - first is 7, doing integer division with 5 gives 1, and then add 1 gives 2.

Related

Pertaining to random and non-repeating numbers

My code is supposed to generate random and non-repeating numbers, but when I print it it doesn't do it properly and sometimes it repeats itself. How can I fix?
Console.WriteLine("choose how many digits your password should be\nminimum 5 maximum 10 digits");
Console.Write("number of digits:");
int digit = int.Parse(Console.ReadLine());
int[] passwordarray = new int[digit];
Random r = new Random();
for (int i = 0; i < passwordarray.Length; i++)
{
if (digit <= 10 && digit >= 5)
{
do
{
passwordarray[i] = r.Next(0, 10);
} while (!(passwordarray.Contains(passwordarray[i])));
}
else
{
Console.WriteLine("your number of digits is less than 5 or more than 10");
}
}
I restructured your code:
Console.WriteLine("choose how many digits your password should be\nminimum 5 maximum 10 digits");
Console.Write("number of digits:");
int digit = int.Parse(Console.ReadLine());
int[] passwordarray = new int[digit];
Random r = new Random();
// check the digits first
if (digit <= 10 && digit >= 5)
{
int tempVal;
for (int i = 0; i < passwordarray.Length; i++)
{
// generate values until you have a value thats not in the array
do
{
tempVal = r.Next(0, 10);
} while (passwordarray.Contains(tempVal));
// add the value
passwordarray[i] = tempVal;
}
}
Basically you want to check first if the digits are between 5 and 10, then iterate trough your array, generate random values until you have one that isn't in the password array yet, and add this value. I just restructured your code, I didn't run it.
EDIT: obviously there are better solutions to implement this behavior, like Dmitrys answer, I restructured the code just to show you where your logic is wrong

How to generate a number from first or last digits of an array and check if it is divisible by a certain number in C#?

I am a beginner in C# and I am struck with this problem. To question is as follows
You are given an array of size n that contains integers. Here, n is an even number. You are required to perform the following operations:
1. Divide the array of numbers in two equal halves
Note: Here, two equal parts of a test case are created by dividing the array into two equal parts.
2. Take the first digit of the numbers that are available in the first half of the array (first 50% of
the test case)
3. Take the last digit of the numbers that are available in the second half of the array (second 50% of
the test case)
4. Generate a number by using the digits that have been selected in the above steps
Your task is to determine whether the newly-generated number is divisible by 11.
And this is my code-
using System;
namespace IsDivisible
{
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int div = 0, digit;
string str = " ";
string[] numArray = Console.ReadLine().Split(' ');
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = Convert.ToInt32(str[i]);
if (i <= n / 2)
{
while (arr[i] >= 10)
{
div = arr[i] / 10;
}
str += div;
}
else
{
digit = arr[i] % 10;
str += digit;
}
}
long newNumber = Convert.ToInt64(str);
if (newNumber % 11 == 0)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
Console.Read();
}
}
}```
It has no errors during compile time in visual studio. The code is not printing anything after I input the array and I am unable to figure out what's wrong. Please help.

Get divisible numbers in a range without certain operators (+, -, /, *, %, += %=, etc)

find numbers in an input range that are evenly divisible by 3. Only =, ++, -- operators can be used.
I've tried to get the remainder using shift operators and other loops but I always require a -= or something similar.
Console.Clear();
int n,
d,
count = 1;
// get the ending number
n = getNumber();
// get the divisor
d = 3;// getDivisor();
Console.WriteLine();
Console.WriteLine(String.Format("Below are all the numbers that are evenly divisible by {0} from 1 up to {1}", d, n));
Console.WriteLine();
// loop through
while (count <= n)
{
// if no remainder then write number
if(count % d == 0)
Console.Write(string.Format("{0} ", count));
count++;
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to try again. Press escape to cancel");
Expected results:
Enter the ending number: 15
Below are all the numbers that are evenly divisible by 3 from 1 up to 15
3, 6, 9, 12, 15
If the == operator is permitted for the assignment, you can have something like
int remainder = 0; // assumes we always count up from 1 to n, we will increment before test
Inside the loop replace the existing if with
remainder++;
if (remainder == 3) {
Console.Write(string.Format("{0} ", count));
remainder = 0;
}
[EDIT: Typo in code corrected]
Think about the underlying maths:
2 x 3 = 3 + 3
3 x 3 = 3 + 3 + 3
4 * 3 = 3 + 3 + 3 + 3
...and so on.
Also, to be evenly divisible by 3 means that the number multiplying 3 must be even.. So...
public bool EvenlyDivisibleBy3(int aNumber)
{
int even = 2;
int currentMultiple = 0;
while (currentMultiple < aNumber)
{
int xTimes = 0;
for (int x = 1; x <= even; x++)
{
((xTimes++)++)++; // add three to xTimes
}
currentMultiple = xTimes;
(even++)++: // next even number
}
return currentMultiple == aNumber;
}

How to check how many times a value appears in an array?

So this is what I want my output to look like:
How many numbers? 10
Give number 1: 1
Give number 2: 3
Give number 3: 1
Give number 4: 3
Give number 5: 4
Give number 6: 6
Give number 7: 4
Give number 8: 8
Give number 9: 2
Give number 10: 1
Number 1 appeared 3 times
Number 2 appeared 1 times
Number 3 appeared 2 times
Number 4 appeared 2 times
Number 6 appeared 1 times
Number 8 appeared 1 times
The thing is, I've got the part which reads the user input done. However, I have no idea how to continue with the part which tells how many times each number appeared.
Also, I'm doing this as a schoolwork so most of the code is in Finnish. I hope you can still understand it, though.
using System;
namespace Ohjelma
{
class Ohjelma
{
static void Main()
{
Console.Write("Kuinka monta lukua? ");
int pituus = Convert.ToInt32(Console.ReadLine());
int[] luvut = new int[pituus];
for (int i = 0; i < pituus; i++)
{
Console.Write("Anna {0}. luku:", i + 1);
luvut[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < luvut.Length; i++)
{
Console.Write(luvut[i]);
}
Console.ReadLine();
}
}
}
Edit: Sorry about the code block on the example of what it should output, not exactly sure how to use blockquotes even though I tried. Thanks!
You can use LINQ like:
var query = luvut.GroupBy(r => r)
.Select(grp => new
{
Value = grp.Key,
Count = grp.Count()
});
For output you can use:
foreach (var item in query)
{
Console.WriteLine("Value: {0}, Count: {1}", item.Value, item.Count);
}
int[] num = { 1, 1, 1, 3, 3, 4, 5, 6, 7, 0 };
int[] count = new int[10];
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++){
for (int y = 0; y < num.Length; y++){
if (num[y] == x)
count[x]++;
}
}
//For displaying output only
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
Program Output:
Number 0 appears 1 times
Number 1 appears 3 times
Number 2 appears 0 times
Number 3 appears 2 times
Number 4 appears 1 times
Number 5 appears 1 times
Number 6 appears 1 times
Number 7 appears 1 times
Number 8 appears 0 times
I understand how bad it feels when all your classmates had finish theirs, and you are still struggling. My codes should be simple enough for your learning.
If you don't want to use LINQ, you can code as follows:-
public class Program
{
public static void Main()
{
int[] arr1 = new int[] {1,3,3,5,5,4,1,2,3,4,5,5,5};
List<int> listArr1 = arr1.ToList();
Dictionary<int,int> dict1 = new Dictionary<int,int>();
foreach(int i in listArr1)
{
if(dict1.ContainsKey(i))
{
int value = dict1[i];
value++;
dict1[i]= value;
}
else
{
dict1.Add(i,1);
}
}
for(int x = 0 ; x < dict1.Count(); x++)
{
Console.WriteLine("Value {0} is repeated {1} times", dict1.Keys.ElementAt(x),dict1[dict1.Keys.ElementAt(x)]);
}
}
}

Split two digit int

I would like to split a two digit int into 2 one digit ints! For example:
20 = 2 and 0
15 = 1 and 5
8 = 0 and 8
That's easy: use % to get the mod of the number, and / for the integer division (i.e. division where the fractional part is discarded).
Your numbers are in the decimal system (i.e. the base is 10) so you divide and mod by 10, like this:
int a = 20 / 10; // 2
int b = 20 % 10; // 0
To print a number digit-by-digit, least significant digit first, you can use this loop:
int a = 12345;
while (a != 0) {
lastDigit = a % 10;
Console.WriteLine(lastDigit);
a /= 10;
}
int i = 45; // or anything you want
int firstDigit = i / 10;
int secondDigit = i % 10;
It's quite simple really.
You can do this for 3-digit numbers using a Modulos and Division operations as well, but I'll let you figure that out by yourself. ;)
Yeah , easy.
int m =2123;
int n=m;
while (n != 0) {
y=n%10; //variable holds each digit out of the number m.
Console.WriteLine(y);
n /= 10;
}
int input = 15;
int first = 0;
int second = Math.DivRem(input, 10, out first);
If you have a array of integers then you can very well use LINQ, else just use any of the below answers.
int num = 86;
int digit1 = num / 10;
int digit2 = num % 10;
Do your numbers have only two digits?

Categories