How do i remove the 0 from and array? - c#

the assignment asks me to find the second lowest number from the user input (max 10), and if a 0 is entered the program should stop and find the second lowest, without counting. But I have to declare the size of the array beforehand.
For example, if I type in 4 7 3 8 0 the program also counts all the 0 until there are 10 numbers so it sees this: 4 7 3 8 0 0 0 0 0 0. Is there a way for me to stop the program from seeing the other 0 or to somehow change the array size?
Edit:
Ok, so here is the code I have so far:
int s;
s = 10;
int[] numbers = new int[s];
for (int i = 0; i < numbers.Length; i++)
{
int.TryParse(Console.ReadLine(), out numbers[i]);
}
int firstLowestNumber = numbers[0];
int secondLowestNumber = numbers[0];
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < firstLowestNumber)
{
firstLowestNumber = numbers[i];
}
}
for (int x = 0; x < numbers.Length; x++)
{
if (numbers[x] < secondLowestNumber && firstLowestNumber != numbers[x])
{
secondLowestNumber = numbers[x];
}
}
Console.WriteLine("Second Lowest Number is {0}", secondLowestNumber);
Console.ReadLine();

With the initialization of an int-array all numbers will be 0. This means you only need to stop reading when a 0 is given as input.
So a little change in the first foreach will do:
int input;
int.TryParse(Console.ReadLine(), out input);
if (input == 0) break; //This will jump out of the foreach
number[i] = input;

It depends on goal of your homework.
1) Using of Linq (its possible teacher requested this task for you especially to not use a Linq)
using System.Linq;
/*...*/
List<int> ints = new List<int>();
ints.Add(/*...*/);
/*...*/
ints = ints.Where(x => x != 0).ToList();
/*...*/
2) As #Aldert's answer.
3) change printing mechanics of array
int[] ints = new int[10];
foreach (int element in ints) {
if (element == 0)
continue;
Console.Write("{0} ", element);
}

Related

How to refactor this code to combine several sections?

Let's say I have these 3 not so different codes.
How can I combine them, or let's just say I want to enter 10 numbers once I open the application.
I want those numbers to be added to each other, and at the same time show me if the number is even or not.
Here is the input code:
int[] dizi = new int[10];
for (int i=0; i<=10; i++)
{
dizi[i] = Convert.ToInt32(Console.ReadLine());
}
Here is the addition code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
toplam=toplam+sayi;
}
Console.WriteLine("Dizideki sayıların toplamı = " + toplam);
Here is the even number code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
if (sayi%2 ==0)
Console.WriteLine(sayi);
}
All code in one for loop.
For input 10 elements you need for from 0 to i < array.Length
because array int[10] access by index from 0 to 9
var array = new int[10];
var sum = 0;
for (var i = 0; i < array.Length; i++)
{
var number = Convert.ToInt32(Console.ReadLine());
sum += number;
if (number % 2 == 0)
Console.WriteLine($"The number {number} is even");
}
Console.WriteLine($"Sum = {sum}");

Find the first uneven number in random array in c#

i must create array and fill it with random numbers , between 1-100. From there, i must find the 1st uneven number and print it.
Also have to print 0 if no uneven numbers are in the array.
Heres what i did:
int[] tab = new int[10];
int[] uneven = new int[tab.Length];
int i;
for (i = 0; i < tab.Length; i++)
tab[i] = new Random().Next(100) + 1;
do
{
uneven[i] = tab[i];
} while (tab[i] % 2 == 1);
Console.WriteLine(uneven[0]);
So my reasoning is that i add uneven numbers in uneven[i] as long as tab[i] is uneven,then print the first element of the array.
However, i get "out of bonds exception".
Thank you in advance for any help.
Your for loop set i to 10 which is outside the bounds of the array. You need to re-set it to 0 before the do loop. Also, you need to increment i.
i = 0;
do
{
uneven[i] = tab[i];
i++;
} while (tab[i] % 2 != 0);
By the time your do loop starts your "i" variable is stuck on 10. Arrays start at 0 so it only goes up to 9 which is why you're seeing the out of bounds exception. Here's a small example of what you're trying to achieve:
int[] tab = new int[10];
var rnd = new Random();
// Create 10 random numbers
for (int i = 0; i < tab.Length; i++)
{
tab[i] = rnd.Next(100) + 1;
}
// Find the first uneven number
bool found = false;
for (int i = 0; i < tab.Length; i++)
{
if (tab[i] % 2 != 0)
{
Console.WriteLine(tab[i]);
found = true;
break;
}
}
// Didn't generate an uneven number?
if (!found)
{
Console.WriteLine("Nothing found");
}
This creates an array[] with random numbers assigned to each element.
The second for loop checks if the number is even/odd then breaks the loop if it is odd.
static void Main(string[] args)
{
int[] numList = new int[100];
var rand = new Random();
Console.WriteLine(rand.Next(101));
for (int i = 0; i <= 99; i++)
{
numList[i] = rand.Next(101);
Console.WriteLine($"Element; {i}: {numList[i]}");
}
for (int i = 0; i <= 99; i++)
{
int num = numList[i];
if (num / 2 != 0)
{
Console.WriteLine($"The first uneven number is: {num} in element: {i}");
break;
}
if(i == numList.Count())
{
Console.WriteLine("All numbers are even");
break;
}
}
Console.ReadLine();
}

How do I create an infinite loop with a question that when answered, categorizes the answer into 1 of 3 different arrays?

I have 3 different categories.
1. Todlers (Age 1-4)
2. Children (Age 5-17)
3. Grownups (Age 18 and above)
I'd like to infinitely loop "Give a number", so that even when all 3 arrays are filled, it still continues. I want the loop to end only when a 0 is typed. (This I seemed to manage)
Only the ten first values have to be stored, any values after the arrays have been filled can be disregarded. (10 values per 3 arrays is 30 values total)
Then I'd like to categorize the ages as explained above. My current age output ('input') remains 0 for every element in each of the 3 arrays. I realise my if-statements aren't being triggered because of "...Length", but how would you recommend replacing that?
I tried "i < 10" but that lead to Array Out of Bounds Exception, as well as putting todlers[i]/children[i]/grownups[i] < 10
Sorry if I am not being concise enough, but I'm still a beginner and English isn't my mothertongue.
Thanks in advance.
class Program
{
static void Main(string[] args)
{
int[] todlers = new int[10];
int[] children = new int[10];
int[] grownups = new int[10];
for (int i = 0; ; i++)
{
Console.Write("Give a number (0 = stop) : ");
int input = int.Parse(Console.ReadLine());
if (todlers.Length < 10 && input < 5 && input > 0)
{
todlers[i] = input;
}
else if (children.Length < 10 && input > 4 && input < 18)
{
children[i] = input;
}
else if (grownups.Length < 10 && input > 17)
{
grownups[i] = input;
}
else if (input == 0)
{
break;
}
else
{
continue;
}
}
Console.Write("\n");
Console.WriteLine("TODLERS");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Todler {0} is {1} years old", i, todlers[i]);
}
Console.Write("\n");
Console.WriteLine("CHILDREN");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Child {0} is {1} years old", i, children[i]);
}
Console.Write("\n");
Console.WriteLine("GROWNUPS");
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Man/Woman {0} is {1} years old", i, grownups[i]);
}
Console.ReadKey();
}
}
The Length of your arrays doesn't change, it stays the same as at initialization (10) throughout your program. As a result todlers.Length < 10 is always false.
Given that you never put 0 inside your arrays you can replace todlers.Length < 10 with todlers[9] == 0 that will effectively check that you haven't yet changed the last element in the array.
for (int i = 1; i < 11; i++)
you should change to
for (int i = 0; i < 10; i++)
it because you had initialize array with 10 elements and the first one will be 0
todlers[0],todlers[1] ... todlers[9]
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
Use a List to store a collection of things when you don't know how many items you will have. Use a do - while loop to run a block of code at least once and at most infinitely.
Try something like this (untested code):
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
List<int> todlers = new List<int>();
List<int> children = new List<int>();
List<int> grownups = new List<int>();
int input = 0;
do
{
Console.Write("Give a number (0 = stop) : ");
input = int.Parse(Console.ReadLine());
if (todlers.Count < 10 && input < 5 && input > 0)
{
todlers.Add(input);
}
else if (children.Count < 10 && input > 4 && input < 18)
{
children.Add(input);
}
else if (grownups.Count < 10 && input > 17)
{
grownups.Add(input);
}
}while(input>0);
Console.Write("\n");
Console.WriteLine("TODLERS");
for (int i = 0; i < todlers.Count; i++)
{
Console.WriteLine("Todler {0} is {1} years old", i+1, todlers[i]);
}
Console.Write("\n");
Console.WriteLine("CHILDREN");
for (int i = 0; i < children.Count; i++)
{
Console.WriteLine("Child {0} is {1} years old", i+1, children[i]);
}
Console.Write("\n");
Console.WriteLine("GROWNUPS");
for (int i = 0; i < grownups.Count; i++)
{
Console.WriteLine("Man/Woman {0} is {1} years old", i+1, grownups[i]);
}
Console.ReadKey();
}
}
This will stop adding to the lists when there are 10 entries, but the user will have no warning their input is being discarded. It will also only output the number of entries that have been added, instead of zeroes if the user inputs fewer than ten in a category.

Store value from a whileloop into an array then sum the array

I'm trying to store an unknown amount of data into an array, while using a forloop to get data! My task is to find and sum all the numbers form 1 to 1000 that can be divided be 3 and 5.
for (int i = 1; i < 1001; i++)
if (i%3==0)
{
if (i%5==0)
{
//this doesn't work, have tried to convert it to string, didn't work either
int[] array = { i };
//trying to loop the values
for (int j = 0; j < array.Length; i++)
{
//how can I loop this so I dont have to write it all out?
int sum1 = array[j]
}
}
}
Console.ReadKey();
Just because computers can perform repetitive task well doesn't mean you ignore Mathematics. If I got it right, you are trying to find the sum of all the numbers less than 1000 which are divisible by both 3 and 5. So that boils down to all the multiples of 15. Now if you take the floor of 1000/15, you get the the last multiple, which in this case is 66. So, you have to sum the series:
15, 15*2, 15*3,...15*66
=15*(1+2+3+..+66) [15*sum of first 66 positive natural numbers]
=15*66*67/2
So generalizing, finding sum of all numbers less than a and divisible by b is given by:
limit = floor(a/b);
sum = b*limit*(limit+1)/2;
Something like this:
var ListOfInts=new List<int>();
for (int i = 1; i < 1001; i++) {
if (i % 3 == 0 && i % 5 == 0)
ListOfInts.Add(i);
}
var result = ListOfInts.Sum();
Perhaps this code does what you want:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
}
}
}
The number devides by 3 and 5 means it devides by 15. So you can start iterating from 15 and incrementing by 15 to skip some iterations:
int sum = 0;
for (int i = 15; i <= 1000; i += 15)
sum += i;
Thanks guys! Alot of good answers, i'm still trying to understand some of them but thanks :)
How come that
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
give me this
while the code down under
var ListofInts = new List<int>();
for (int i = 0; i < 1001; i++)
{
if (i%3==0 && i%5==0)
{
ListofInts.Add(i);
var result = ListofInts.Sum();
Console.Write(result + ", ");
}
}
gives me this?

find diagonal in 2 dimensional array

I have a 2-dimensional array with user-entered values. I need to find sum of the even elements in the diagonal of the array.
I know how to declare the array and get it filled by the user, but I'm not sure what even elements in the main diagonal really means.
I know I can find out if a number is even by saying:
if n / 2 == 0
Once I've reported the sum of the even elements in the diagonal, I would like to replace all 0 values in the array with ones.
Diagonal means all places where x and y cordinates are the same
Do if your array contains:
1 3 8 5
3 3 9 7
4 4 5 7
5 1 7 4
Then the diagonal are in bold.
Assuming the array is a square:
int sum = 0;
for(int i = 0; i < numOfArrayRows; i++)
{
//Use the mod operator to find if the value is even.
if(array[i][i] % 2 == 0)
sum += array[i][i];
//Change 0's to ones
for(int j = 0; j < numOfArrayCols; j++)
if(array[i][j] == 0)
array[i][j] = 1;
}
Also, next time add the "Homework" tag if you have a homework question :P
With a two-dimensional array it's really easy, since you don't need any index magic:
int a[N][N] = ...;
int sum = 0;
for(int i=0; i<N; ++i)
if(a[i][i] % 2 == 0) //or a[i] & 1, if you like, just check if it's dividable by 2
sum += a[i][i];
This C++ code shouldn't be that different in C or C#, but you should get the point. Likewise the second question would be as simple as:
int a[M][N] = ...;
for(i=0; i<M; ++i)
for(j=0; j<N; ++j)
if(a[i][j] == 0)
a[i][j] = 1;
And I suspec that the main diagonal is the one that begins with coordinates 0,0.
To replace 0 elements with 1 you would do something like:
if (array[i,j] == 0) array[i,j] == 1;
This sounds like homework - however I will help out :)
So if you have an 2D array, and in order to find the sum of the diagonal values, you will know that the indices of both of the values would match in order to provide you with each of the diagonal values.
To iterate through these you could use a simple loop that would sum up every diagonal value, as shown:
//Your Sum
int sum = 0;
//This will iterate and grab all of the diagonals
//You don't need to iterate through every element as you only need
//the diagonals.
for(int i = 0; i < sizeOfArray; i++)
{
//This will add the value of the first, second, ... diagonal value to your sum
sum += array[i,i];
}
To set each of the values that is 0 to 1, you could iterate through each element of the array and check if the value is 0, then set that value to 1, for example:
for(int i = 0; i < sizeOfArray; i++)
{
for(int j = 0; j < sizeOfArray; j++)
{
//Check if this value is 0;
//If it is 0, set it to 1, otherwise continue
}
}
int[,] array = new int[,] {{1,2,3},
{4,5,6},
{7,8,9}};
//Suppose you want to find 2,5,8
for(int row = 0; row < 3; row++)
{
for(int column = 0; column < 3; column++)
{
if((row == 0 && column == 1) || (row == 1 && column == 1) || (row == 2 && column == 1))
{
Console.WriteLine("Row: {0} Column: {1} Value: {2}",row + 1, column + 1, array[row, column]);
}
}
}
Here is the code you need, not much explain:
//Read the size of the array, you can get it from .Count() if you wish
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
//Reading all the values and preparing the array (a)
for (int a_i = 0; a_i < n; a_i++)
{
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp, Int32.Parse);
}
//performing the operation (google what diagonal matrix means)
int PrimarySum = 0, SecondarySum = 0;
for (int i = 0; i < n; i++)
{
//The If condition is to skip the odd numbers
if (a[i][i] % 2 == 0) { PrimarySum += a[i][i]; }
//For the reverse order
int lastelement = a[i].Count() - 1 - i;
if (a[i][lastelement] % 2 == 0) { SecondarySum += a[i][lastelement]; }
}
//Get the absolute value
Console.WriteLine(Math.Abs(PrimarySum - SecondarySum).ToString());
Console.ReadKey();

Categories