A for loop can be used to print all prime numbers from 1 to 100. A prime number is a number that has exactly two factors: 1 and itself. In this program, the outer for loop checks every number from 2 to 100. The inner for loop counts how many times the current number is exactly divisible. If the count is equal to 2, the number is a prime number and is displayed on the screen.
How It Works?
i, j, and count.for loop to check numbers from 2 to 100.count = 0 before checking each number.for loop to divide the current number by every value from 1 to the number itself.count by 1.count == 2.#include <stdio.h> #include <conio.h> main() { int i, j, count; clrscr(); printf("Prime Numbers from 1 to 100:\n\n"); for(i = 2; i <= 100; i = i + 1) { count = 0; for(j = 1; j <= i; j = j + 1) { if(i % j == 0) { count = count + 1; } } if(count == 2) { printf("%d\t", i); } } getch(); }
for loop to print all prime numbers from 1 to 50.for loops and the if statement to check whether a number is prime and display all prime numbers within a given range.for loop from 2 to 50. For each number, use another for loop to count its factors. If the count is equal to 2, print the number.#include <stdio.h> #include <conio.h> main() { int i, j, count; clrscr(); printf("Prime Numbers from 1 to 50:\n\n"); for(i = 2; i <= 50; i = i + 1) { count = 0; for(j = 1; j <= i; j = j + 1) { if(i % j == 0) { count = count + 1; } } if(count == 2) { printf("%d\t", i); } } getch(); }
for loops. The outer loop checks each number from 2 to 50. The inner loop counts how many numbers divide the current number exactly. If the count is equal to 2, the number has only two factors (1 and itself), so it is printed as a prime number.