So I have a little bit code here that writes out the 50 first prime number.
#include <iostream>
#include <iomanip>
using namespace std;
main()
{
const int max_antal = 50;
int prim_tab[max_antal];
bool primtal;
int antal=0, tal=1;
while (antal < max_antal)
{
tal++;
primtal=true;
for (int i=0; i<antal && primtal; i++)
if (tal%prim_tab[i] == 0)
primtal=false;
if (primtal)
prim_tab[antal++] = tal;
}
for (int j=0; j<max_antal; j++)
cout << prim_tab[j] << endl;
}
This code works but I dont know how. Firstly shouldn't the while loop be infinite? I cant see anywhere that "antal" is getting added and should therefore always be lower then max_antal. Secondly (tal%[prim_tab[i]==0) always gives the same anwser but prim_tab[i] is not defined? prim_tab is an array with 50"spaces" but those "spaces" is not defined and have a random number in them. So prim_tab[i] should just be a random number right?
Hope you understood my question and thanks for the help.
well antal has a starting number of 0, and since 0 !< 0, it breaks the condition, thus not executing the for loop the first time, and then in the if underneathit gets its initial value. you know, after realizing that, this program is actually quite clever