w3resource

C Exercises: Find the prime numbers within a range of numbers

C For Loop: Exercise-34 with Solution

Write a program in C to find the prime numbers within a range of numbers.

Sample Solution:

C Code:

#include <stdio.h>

void main(){
    int num,i,ctr,stno,enno;

    printf("Input starting number of range: ");
    scanf("%d",&stno);

    printf("Input ending number of range : ");
    scanf("%d",&enno);
    printf("The prime numbers between %d and %d are : \n",stno,enno);
  
    for(num = stno;num<=enno;num++)
       {
         ctr = 0;

         for(i=2;i<=num/2;i++)
            {
             if(num%i==0){
                 ctr++;
                 break;
             }
        }
        
         if(ctr==0 && num!= 1)
             printf("%d ",num);
    }
printf("\n");  
}

Sample Output:

Input starting number of range: 1                                                                             
Input ending number of range : 50                                                                             
The prime numbers between 1 and 50 are :                                                                      
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47  

Flowchart:

Flowchart : Find the prime numbers within a range of numbers.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a C program to display Pascal's triangle
Next: Write a program in C to display the first n terms of Fibonacci series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Printing hexadecimal characters in C:

You are seeing the ffffff because char is signed on your system. In C, vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since c0 and 80 have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

char    int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061
Here's a solution:
char ch = 0xC0;
printf("%x", ch & 0xff);

This will mask out the upper bits and keep only the lower 8 bits that you want.

Ref : https://bit.ly/3vOLizM