C Program to Print Prime Numbers up to Given Number
Following C program Print Prime Numbers up to Given Number, then display the result on the screen:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Print Prime Numbers How it Works?
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.
After the body of the ‘for’ loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, and then again condition). After the condition becomes false, the ‘for’ loop terminates.
Example : C Program to Print Prime Numbers up to Given Number
/*Program to generate prime numbers till nth number*/ void main() { int n,i,factr,j; printf("enter the range"); scanf("%d",&n); printf(“Prime numbers are\n”); for(i=1;i<=n;i++) { factr=0; for(j=1;j<=i;j++) { if(i%j==0) factr++; } if(factr==2) printf("%d “,i); } getch(); }
Save program in a file, Compile program, debug errors, Execute or Run program with necessary inputs. Verify the outputs obtained.
Output
Enter the range 10 Prime numbers are 3 5 7
Let me know if you find any difficulty in understanding this C Program to Print Prime Numbers up to Given Number example and I would be glad to explain it further.