How to iterate numbers to a limit by addition - c#

Here is the code I have right now:
for(int i=0; i< 35; ++i)
{
int a = 1;
a+=1;
Console.WriteLine(a);
}
The output is:
2
2
2
...
and so on, until the loop terminates.
What I want to do is add the previous two numbers to make the nest number then so on all the way to 34.

This is how you can achieve what you want:
//Initializing the elements
int a = 0;
int b = 1;
int c = 1;
Console.WriteLine(a); //Typing the 0'th element
Console.WriteLine(b); //Typing the first element
for(;c <= 34; c = a + b) {
Console.WriteLine(c); //Typing the actual element
a = b;
b = c;
}

You mean count to some number by adding other and using this as what? Escape condition? Just as a constant in addition?
as escape condition:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
public static void Main()
{
for (i = 0; i < 100; i++){
a += i;
if (a == 595) break;
}
Console.WriteLine(i);
}
}
as a constant in addition:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
static private int d = 1;
public static void Main()
{
for (i = 0; i < 34; i++){
a += d;
}
Console.WriteLine(a);
}
}
Both seem highly illogical to use tho :/
EDIT: Your question is now different from what you told before :D
You are wondering why is a not getting larger than 2? Because you initialize it each step of for loop. You need to move initialization out of the scope of for. Try this:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
static private int d = 1;
public static void Main()
{
int a = 1;
for(int i=0; i< 34; ++i)
{
Console.WriteLine(a);
a+=1;
}
}
}
I understand you need numbers from 1 to 34. So you can't start with 1, immediately increment by 1 and then write it cause it will be 2. Write first, then increment.
Or you can start with 0 then you can increment first. But adjust end condition as well.

You are declaring a new variable a with each iteration and then add 1 to it. Since the initial value of a is 1, you calculate 1+1 with each iteration. Step through the code in a debugger to see what I mean.
Move the declaration out of the loop and you should see your desired output:
int a = 1;
for(int i=0; i< 35; ++i)
{
a+=1;
Console.WriteLine(a);
}
There are tons of tutorials how you can print out the fibonacci sequence, for example with two nested for-loops:
for (int i = 0; i < 10; ++i)
{
int a = 0;
int b = 1;
for (int j = 0; j < i; ++j)
{
var temp = a;
a = b;
b = temp + b;
}
Console.WriteLine(a);
}
Example taken from dotnetperls (albeit slightly edited by me).

Related

Why is bubble sort running faster than selection sort?

I am working on a project that compares the time bubble and selection sort take. I made two separate programs and combined them into one and now bubble sort is running much faster than selection sort. I checked to make sure that the code wasn't just giving me 0s because of some conversion error and was running as intended. I am using System.Diagnostics; to measure the time. I also checked that the machine was not the problem, I ran it on Replit and got similar results.
{
class Program
{
public static int s1 = 0;
public static int s2 = 0;
static decimal bubblesort(int[] arr1)
{
int n = arr1.Length;
var sw1 = Stopwatch.StartNew();
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
s1++;
}
}
}
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static decimal selectionsort(int[] arr2)
{
int n = arr2.Length;
var sw1 = Stopwatch.StartNew();
// for (int e = 0; e < 1000; e++)
// {
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
s2++;
}
}
// }
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static void Main(string[] args)
{
Console.WriteLine("Enter the size of n");
int n = Convert.ToInt32(Console.ReadLine());
Random rnd = new System.Random();
decimal bs = 0M;
decimal ss = 0M;
int s = 0;
int[] arr1 = new int[n];
int tx = 1000; //tx is a variable that I can use to adjust sample size
decimal tm = Convert.ToDecimal(tx);
for (int i = 0; i < tx; i++)
{
for (int a = 0; a < n; a++)
{
arr1[a] = rnd.Next(0, 1000000);
}
ss += selectionsort(arr1);
bs += bubblesort(arr1);
}
bs = bs / tm;
ss = ss / tm;
Console.WriteLine("Bubble Sort took " + bs + " miliseconds");
Console.WriteLine("Selection Sort took " + ss + " miliseconds");
}
}
}
What is going on? What is causing bubble sort to be fast or what is slowing down Selection sort? How can I fix this?
I found that the problem was that the Selection Sort was looping 1000 times per method run in addition to the 1000 runs for sample size, causing the method to perform significantly worse than bubble sort. Thank you guys for help and thank you TheGeneral for showing me the benchmarking tools. Also, the array that was given as a parameter was a copy instead of a reference, as running through the loop manually showed me that the bubble sort was doing it's job and not sorting an already sorted array.
To solve your initial problem you just need to copy your arrays, you can do this easily with ToArray():
Creates an array from a IEnumerable.
ss += selectionsort(arr1.ToArray());
bs += bubblesort(arr1.ToArray());
However let's learn how to do a more reliable benchmark with BenchmarkDotNet:
BenchmarkDotNet Nuget
Official Documentation
Given
public class Sort
{
public static void BubbleSort(int[] arr1)
{
int n = arr1.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
}
}
}
}
public static void SelectionSort(int[] arr2)
{
int n = arr2.Length;
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
}
}
}
}
Benchmark code
[SimpleJob(RuntimeMoniker.Net50)]
[MemoryDiagnoser()]
public class SortBenchmark
{
private int[] data;
[Params(100, 1000)]
public int N;
[GlobalSetup]
public void Setup()
{
var r = new Random(42);
data = Enumerable
.Repeat(0, N)
.Select(i => r.Next(0, N))
.ToArray();
}
[Benchmark]
public void Bubble() => Sort.BubbleSort(data.ToArray());
[Benchmark]
public void Selection() => Sort.SelectionSort(data.ToArray());
}
Usage
static void Main(string[] args)
{
BenchmarkRunner.Run<SortBenchmark>();
}
Results
Method
N
Mean
Error
StdDev
Bubble
100
8.553 us
0.0753 us
0.0704 us
Selection
100
4.757 us
0.0247 us
0.0231 us
Bubble
1000
657.760 us
7.2581 us
6.7893 us
Selection
1000
300.395 us
2.3302 us
2.1796 us
Summary
What have we learnt? Your bubble sort code is slower ¯\_(ツ)_/¯
It looks like you're passing in the sorted array into Bubble Sort. Because arrays are passed by reference, the sort that you're doing on the array is editing the same contents of the array that will be eventually passed into bubble sort.
Make a second array and pass the second array into bubble sort.

Sort by selection in C#

I am a complete beginner in programming. Trying to make sorting a choice. Everything seems to be ok. Only there is one caveat. Only numbers up to 24 index are filled in the new array. I can’t understand what the problem is.
int[] Fillin(int[] mass)
{
Random r = new Random();
for(int i = 0; i < mass.Length; i++)
{
mass[i] = r.Next(1, 101);
}
return mass;
}
int SearchSmall(int[] mass)
{
int smallest = mass[0];
int small_index = 0;
for(int i = 1; i < mass.Length; i++)
{
if (mass[i] < smallest)
{
smallest = mass[i];
small_index = i;
}
}
return small_index;
}
int[] Remove(int[] massiv,int remind)
{
List<int> tmp = new List<int>(massiv);
tmp.RemoveAt(remind);
massiv = tmp.ToArray();
return massiv;
}
public int[] SortMass(int[] mass)
{
mass = Fillin(mass);
Print(mass);
Console.WriteLine("________________________________");
int[] newmass = new int[mass.Length];
int small;
for(int i = 0; i < mass.Length; i++)
{
small = SearchSmall(mass);
newmass[i] = mass[small];
mass = Remove(mass, small);
}
return newmass;
}
I think your main issue is that when you remove an element in the Remove function, the main loop in for (int i = 0; i < mass.Length; i++) will not check all elements o the initial array. A simple (and ugly) way to fix that would be not to remove the elements but to assign a very high value
public static int[] Remove(int[] massiv, int remind)
{
massiv[remind] = 999999;
return massiv;
}
Or as Legacy suggested simply modify the mass.length for newmass.lengh in the main loop.
As some others have mentioned this is not the best way to order an array, but it is an interesting exercise.

How can I fill array with unique random numbers with for-loop&if-statement?

I'm trying to fill one dimensional array with random BUT unique numbers (No single number should be same). As I guess I have a logical error in second for loop, but can't get it right.
P.S I'm not looking for a more "complex" solution - all I know at is this time is while,for,if.
P.P.S I know that it's a really beginner's problem and feel sorry for this kind of question.
int[] x = new int[10];
for (int i = 0; i < x.Length; i++)
{
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) break;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i);
}
Here is a solution with your code.
int[] x = new int[10];
for (int i = 0; i < x.Length;)
{
bool stop = false;
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) {
stop = true;
break;
}
}
if (!stop)
i++;
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
A simple trace of the posted code reveals some of the issues. To be specific, on the line…
if (x[i] == x[j]) break;
if the random number is “already” in the array, then simply breaking out of the j loop is going to SKIP the current i value into the x array. This means that whenever a duplicate is found, x[i] is going to be 0 (zero) the default value, then skipped.
The outer i loop is obviously looping through the x int array, this is pretty clear and looks ok. However, the second inner loop can’t really be a for loop… and here’s why… basically you need to find a random int, then loop through the existing ints to see if it already exists. Given this, in theory you could grab the same random number “many” times over before getting a unique one. Therefore, in this scenario… you really have NO idea how many times you will loop around before you find this unique number.
With that said, it may help to “break” your problem down. I am guessing a “method” that returns a “unique” int compared to the existing ints in the x array, may come in handy. Create an endless while loop, inside this loop, we would grab a random number, then loop through the “existing” ints. If the random number is not a duplicate, then we can simply return this value. This is all this method does and it may look something like below.
private static int GetNextInt(Random r, int[] x, int numberOfRandsFound) {
int currentRand;
bool itemAlreadyExist = false;
while (true) {
currentRand = r.Next(RandomNumberSize);
itemAlreadyExist = false;
for (int i = 0; i < numberOfRandsFound; i++) {
if (x[i] == currentRand) {
itemAlreadyExist = true;
break;
}
}
if (!itemAlreadyExist) {
return currentRand;
}
}
}
NOTE: Here would be a good time to describe a possible endless loop in this code…
Currently, the random numbers and the size of the array are the same, however, if the array size is “larger” than the random number spread, then the code above will NEVER exit. Example, if the current x array is set to size 11 and the random numbers is left at 10, then you will never be able to set the x[10] item since ALL possible random numbers are already used. I hope that makes sense.
Once we have the method above… the rest should be fairly straight forward.
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
int numberOfRandsFound = 0;
int[] ArrayOfInts = new int[DataSize];
int currentRand;
for (int i = 0; i < ArrayOfInts.Length; i++) {
currentRand = GetNextInt(random, ArrayOfInts, numberOfRandsFound);
ArrayOfInts[i] = currentRand;
numberOfRandsFound++;
}
for (int i = 0; i < ArrayOfInts.Length; i++) {
Console.WriteLine(ArrayOfInts[i]);
}
Console.ReadKey();
}
Lastly as other have mentioned, this is much easier with a List<int>…
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
List<int> listOfInts = new List<int>();
bool stillWorking = true;
int currentRand;
while (stillWorking) {
currentRand = random.Next(RandomNumberSize);
if (!listOfInts.Contains(currentRand)) {
listOfInts.Add(currentRand);
if (listOfInts.Count == DataSize)
stillWorking = false;
}
}
for (int i = 0; i < listOfInts.Count; i++) {
Console.WriteLine(i + " - " + listOfInts[i]);
}
Console.ReadKey();
}
Hope this helps ;-)
The typical solution is to generate the entire potential set in sequence (in this case an array with values from 0 to 9). Then shuffle the sequence.
private static Random rng = new Random();
public static void Shuffle(int[] items)
{
int n = list.Length;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
int temp = items[k];
items[k] = items[n];
items[n] = temp;
}
}
static void Main(string[] args)
{
int[] x = new int[10];
for(int i = 0; i<x.Length; i++)
{
x[i] = i;
}
Shuffle(x);
for(int i = 0; i < x.Length; i++)
{
Console.WritLine(x[i]);
}
}
//alternate version of Main()
static void Main(string[] args)
{
var x = Enumerable.Range(0,10).ToArray();
Shuffle(x);
Console.WriteLine(String.Join("\n", x));
}
You can simply do this:
private void AddUniqueNumber()
{
Random r = new Random();
List<int> uniqueList = new List<int>();
int num = 0, count = 10;
for (int i = 0; i < count; i++)
{
num = r.Next(count);
if (!uniqueList.Contains(num))
uniqueList.Add(num);
}
}
Or:
int[] x = new int[10];
Random r1 = new Random();
int num = 0;
for (int i = 0; i < x.Length; i++)
{
num = r1.Next(10);
x[num] = num;
}

Selection sort just working once in C# gui

I am using selection sort in GUI and the thing is that when I select selection sort and do sorting on generate numbers it sorts generated numbers for one time but if next time I will use other number it will do just the first step of sorting by just replacing two numbers and won't work then... So why it's not working again and why showing such different behavior?
The code is:-
void SelectionSort() {
int i = 0;
int j, min, temp;
min = i;
for (j = i + 1; j < 10; j++) {
if (generate[min] > generate[j]) {
min = j;
}
}
if (min != i) {
temp = generate[i];
generate[i] = generate[min];
generate[min] = temp;
//show1(generate);
}
show1(generate);
i++;
}
My guess, you need to add i=0; at the beginning.
I guess from your function that i is a global variable.
You need to reset i to 0 every time you enter the function (Inside the function)
using System;
namespace SelectionSortExample
{
class Program
{
static void Main(string[] args)
{
int[] num = { 105, 120, 10, 200, 20 };
for (int i = 0; i < num.Length; i++)
{
int minIndex = i;
for (int j = i + 1; j < num.Length; j++)
{
if (num[minIndex] > num[j])
{
minIndex = j;
}
}
int tmp = num[i];
num[i] = num[minIndex];
num[minIndex] = tmp;
}
}
}
}

Passing Arrays as Parameters in C#

I am trying to create a function that accepts 5 integers, holds them in an array and then passes that array back to the main. I have wrestled with it for a couple of hours and read some MSDN docs on it, but it hasn't "clicked". Can someone please shed some light as to what I am doing wrong?
Errors:
Not all code paths return a value;
something about invalid arguments:
Code:
using System;
using System.IO;
using System.Text;
namespace ANumArrayAPP
{
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
}
}
}
The parameter to ReadInNum is a single int, but you're trying to pass an array. You have to make the parameter match what you're trying to pass in. For example:
static void ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readIn[i] = int.Parse(Console.ReadLine());
}
}
That will fill the array you pass into the method. Another alternative is to pass in how many integers you want, and return the array from the method:
static int[] ReadInNum(int count)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
Console.WriteLine("Please enter an interger");
values[i] = int.Parse(Console.ReadLine());
}
return values;
}
You'd call this from Main like this:
int[] input = ReadInNum(5);
for (int a = 0; a < 5; a++)
{
Console.Write(input[a]);
}
You should complete your function with return statement since its return type is not void. Also, you should change your return type to int[] since your return an array of ints, not just one int:
static int[] ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readInn;
}
You should also change your main function in order to get the result of the function ReadInNum. It seems to me that you don't really use the parameter so you can remove it, if you don't have special attention:
static void Main()
{
int j;
int[] i = ReadInNum(j);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
To summarize zome aswer already here, there are two ways to go about it:
1. Pass an array into the method
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(i[a]); // !
}
}
static int ReadInNum(int[] readIn)
{
for (int i = 0; i < rreadIn.Length; i++)
...
}
2. Return an array
static void Main()
{
// int[] i = new int[5];
int[] i = ReadInNum(5);
for (int a = 0; a < i.Length; a++)
{
Console.Write(i[a]); // !
}
}
static int[] ReadInNum(int size)
{
int[] readIn = new int[size];
for (int i = 0; i < readIn.Length; i++)
...
}
Pass an array to the function:
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int[] ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readIn;
}
}
Notice how I returned an int[] from ReadInNum. This isn't necessary but it makes the code more readable since it's not more obvious that you're planning on changing readIn.

Categories