+ 1

Attention ! I need help. I cant understand the following program.

/* A program that prints prime number in a given range. */ #include<stdio.h> #include<math.h> int main() { int start, end, count, flag,inum; printf("Enter the range: "); scanf("%d %d",&start,&end); while(start<end) { inum=sqrt(start); count=2; flag=1; while(count<=inum) { if(start%count==0) { flag=0; break; } count++; } if(flag==1) printf("%d ",start); start++; } }

22nd Jun 2020, 8:06 AM
Rakibur Rahman
Rakibur Rahman - avatar
1 Respuesta
+ 1
It is easy. suppose the range is 4 to 6. "while (start < end)" is to be executed 2 times, starting with 4. First, "inum" is going to be equal to the square root of 4, which is 2. "count" is going to be equal to 2 and "flag" is going to be equal to 1. Then "while (count <= inum)" is executed, since 2 is less than or equal to 2. Then "if (start% count == 0)" is executed, which analyzes if the remainder of 4/2 is equal to 0, as this is true, the following lines are executed: flag = 0; break; "break" will break "while (count <= inum)" and then execute "if (flag == 1)", as "flag" equals 0, this condition is false and the number is not printed on the screen, then run "start ++;" which changes the value of "start" from 4 to 5. now we repeat the same procedure but with 5: inum = 2.2360; (square root of 5) count = 2; flag = 1; "while (count <= inum)" is executed since 2 is less than or equal to 2.2360 "if (start% count == 0)" is executed which evaluates if the remainder of 5/2 is equal to 0, as this is false "count ++" is executed which increases the value of "count" from 2 to 3. Since count is 3 and is greater than "inum", "while (count <= inum)" is not rerun Then "if (flag == 1)" is executed, which is true because "if (start% count == 0)" was not true, the following line is executed: printf ("% d", start); which prints the number 5 on the screen then "start ++" increases the value of "start" from 5 to 6 As ( 6(start) < 6(end) ) is false the program ends giving as a result that 5 is a prime number. I hope I've helped.
22nd Jun 2020, 9:59 PM
Oscar Diaz