How can this code work?

Jun 23, 2014 at 5:30pm
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.
Jun 23, 2014 at 5:37pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

using namespace std;

int 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;
}


antal is added on line 23.
Jun 23, 2014 at 6:09pm
oh yeah saw that now thx!, but could you explain line 19. How prim_tab[i] is not just a random number? :)
Jun 23, 2014 at 6:46pm
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
Jun 24, 2014 at 8:16am
yeah now I see it thx for the help!
Topic archived. No new replies allowed.