# how to make a random in a loop in C#



## Noctosphere (Sep 2, 2017)

Hello
So today i'Ve been given a homework and in this, I must create a code where it asks for a int number to the user, then generate that amount of random number between 0 and 99, and then categorize them in three category (between 0-33, 34-66, 67-99)
however, I've been told to not use random in a loop because I would have 100% of those number in the same category
I tryed and indeed, they're all 100% in the same category, always, each try, no matter what i do.
So, I have the loop, I have all the system required, but the opart where it generates a random number
can someone pelase help me??
Ofc, I'll quote this link in my program commentary so teatcher will know where I got my help

thanks


----------



## Dr.Hacknik (Sep 2, 2017)

Could I see your present work. That might help me further.


----------



## Deleted User (Sep 2, 2017)

snip


----------



## Noctosphere (Sep 2, 2017)

Spoiler





```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition)==false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)
            {
               
                if (nbAleatoire <= 0 && nbAleatoire >= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 34 && nbAleatoire >= 66)
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            Console.WriteLine("Nombres entre 0 et 33 : " + nbSection1);
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2);
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3);

        }
    }
}
```




--------------------- MERGED ---------------------------



MyLegGuy said:


> ?
> 
> ```
> Random myRandom = new Random();
> ...


i didnt learn that lane
Console.Out.Writeline

just Console.WriteLine

--------------------- MERGED ---------------------------

btw i rremoved the random number affectation because it didnt work, but it was between the for lane and the first if


----------



## gnmmarechal (Sep 2, 2017)

Noctosphere said:


> Spoiler
> 
> 
> 
> ...


https://stackoverflow.com/questions/1149131/why-does-console-out-writeline-exist


----------



## Noctosphere (Sep 2, 2017)

gnmmarechal said:


> https://stackoverflow.com/questions/1149131/why-does-console-out-writeline-exist


mmh not sure to 100% understand but they have no difference in that context, right?


----------



## Deleted User (Sep 2, 2017)

snip


----------



## Noctosphere (Sep 2, 2017)

MyLegGuy said:


> Console.Out.Writeline does the same thing as Console.WriteLine in this case.
> 
> The problem wasn't your random number generation, it was your "if" statements.
> I've fixed your loop for you.
> ...


sooo... It'S just a dumb mistake xD


----------



## Noctosphere (Sep 2, 2017)

maybe you guys can help me furthermore
I'm trying to convert a float to a string, using ToString function to get a percentage
But I always get 2 extra 0 before the dot
I can'T figure out where I made a mistake


Spoiler





```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition)==false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)//on m'a aidé http://gbatemp.net/threads/how-to-make-a-random-in-a-loop-in-c.482959/#post-7554192
            {
                nbAleatoire = rnd.Next(0, 100); // Generate a new random number 1 through 99
                if (nbAleatoire <= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 66) // There is no need to check if it's greater than 33 again because if it was less than or equal to 33, this "if" statement would never happen because the last one would be true.
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            float sec1Pct = 0f;
            float sec2Pct = 0f;
            float sec3Pct = 0f;
            sec1Pct = nbSection1 / nbRepetition * 100;
            sec2Pct = nbSection2 / nbRepetition * 100;
            sec3Pct = nbSection3 / nbRepetition * 100;
            Console.WriteLine("Nombres entre 1 et 33 : " + nbSection1 + "  " + sec1Pct.ToString("##.0#%"));
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2 + "  " + sec2Pct.ToString("##.0#%"));
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3 + "  " + sec3Pct.ToString("##.0#%"));


        }
    }
}
```


----------



## Deleted User (Sep 2, 2017)

snip


----------



## Noctosphere (Sep 3, 2017)

MyLegGuy said:


> ```
> sec1Pct = nbSection1 / nbRepetition * 100;
> ```
> In this line, you're dividing integers, so the answer will be an integer, a whole number. You need to cast one of the numbers as a float so it'll do float division and give you a float as the result.
> ...


oh it multiplies by 100?
i didnt know, i dont think it did that before, ill try

--------------------- MERGED ---------------------------



MyLegGuy said:


> ```
> sec1Pct = nbSection1 / nbRepetition * 100;
> ```
> In this line, you're dividing integers, so the answer will be an integer, a whole number. You need to cast one of the numbers as a float so it'll do float division and give you a float as the result.
> ...


alright, it works, but whenever I get another answer other than 100%, I get a .0%
When i get 100% by entering 1, I get 100.0%
but when I enter 2, I get 3 .0%


----------



## Deleted User (Sep 3, 2017)

snip


----------



## Noctosphere (Sep 3, 2017)

MyLegGuy said:


> You didn't look at the article on format strings.
> 
> ```
> sec1Pct.ToString("##.0#%")
> ...


yea ive read this article, in french but ive read it
i might change it to # but I guess i'll still have the same problem
when it'S supposed to show 50.0%, it shows .0%


----------



## Deleted User (Sep 3, 2017)

snip


----------



## Noctosphere (Sep 3, 2017)

Spoiler





```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition) == false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)//on m'a aidé http://gbatemp.net/threads/how-to-make-a-random-in-a-loop-in-c.482959/#post-7554192
            {
                nbAleatoire = rnd.Next(0, 100); // Generate a new random number 1 through 99
                if (nbAleatoire <= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 66) // There is no need to check if it's greater than 33 again because if it was less than or equal to 33, this "if" statement would never happen because the last one would be true.
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            float sec1Pct = 0f;
            float sec2Pct = 0f;
            float sec3Pct = 0f;
            sec1Pct = nbSection1 / nbRepetition;
            sec2Pct = nbSection2 / nbRepetition;
            sec3Pct = nbSection3 / nbRepetition;
            Console.WriteLine("Nombres entre 1 et 33 : " + nbSection1 + "  " + sec1Pct.ToString("##.##%"));
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2 + "  " + sec2Pct.ToString("##.##%"));
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3 + "  " + sec3Pct.ToString("##.##%"));


        }
    }
}
```


----------



## FAST6191 (Sep 3, 2017)

Amusing that you cited a forum post in the comments.

Anyway I am sitting here thinking this looks like classic introduce you to how to adapt your program territory a la fizzbuzz



Then trying to imagine what the obvious expansions will be, guessing more than 99 numbers and all of a sudden a few different categories or overlapping ones. You may also be asked to translate it to another language and having to pull all the strings out of that to translate might be seen as bad form but don't worry about that one too much yet.

Also, and this is why my haziness with c# will come to the fore, do you not have to exit the program properly? Most starting to program courses will try to drill that into you for a reason.


----------



## Noctosphere (Sep 3, 2017)

FAST6191 said:


> Amusing that you cited a forum post in the comments.
> 
> Anyway I am sitting here thinking this looks like classic introduce you to how to adapt your program territory a la fizzbuzz
> 
> ...



not sure to understand what you mean


----------



## FAST6191 (Sep 3, 2017)

The way the program you have now will do what you set out to do. However in real life someone will have another idea about what to do next and you get to implement it, or perhaps you get to implement it on someone else's code that is no longer with the company (making new things is easy and you can get any intern to do that, the ability to be repairing and improving old things is what means you still keep your job when everybody else is being made redundant.

The video above explains the general idea of why you want to program that way all far more clearly but the next step would be something like to change the numbers to between 0 and 133 or something but keep the 33 ranges for groupings (basically another group added) which is fine as it is just another few lines of code, however if you had kicked it to a variable you declared at the top it would be far easier. If instead of just another group I had asked to go to 1000 in groups of 33 you would be there for ages, or at best playing with a spreadsheet to do it for you. Another might be 1000 groups of 33 and another check to tell whether the numbers are odd or even.
I am probably jumping the gun though, bad habit of mine in threads like these. On the other hand if in the next lesson, or the lesson after you get asked that you will be able to sit there with a knowing smile.

In C you would do a return 0 or a proper exit command, however I am not sure for C# and the quick search I did before that did not reveal much more. Not so important for this as the entire functionality (give or take the random nature of it) is there and easily testable, for bigger programs the fact it did not exit cleanly (and maybe crashed instead) is your first clue something is wrong.


----------

