C Program To Count Prime Numbers Between Range

Lets write a C program to count prime numbers between user entered/input range of numbers, using function/method.

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Related Read:
C Program To Find Prime Number or Not using For Loop

Video Tutorial: C Program To Count Prime Numbers Between Range


[youtube https://www.youtube.com/watch?v=vY6HFMblBJY]

YouTube Link: https://www.youtube.com/watch?v=vY6HFMblBJY [Watch the Video In Full Screen.]

Source Code: C Program To Count Prime Numbers Between Range

#include<stdio.h>
#include<math.h>

int isPrime(int num)
{
    int inum = sqrt(num), prime = 1, count;

    for(count = 2; count <= inum; count++)
    {
         if(num % count == 0)
         {
            prime = 0;
            break;
         }
    }

    return(prime);
}

int main()
{
    int start, end, temp, num, slno = 0, on_off;

    printf("Enter start and end value\n");
    scanf("%d%d", &start, &end);

    printf("Do you want to print prime numbers? (yes = 1, no = 0)\n");
    scanf("%d", &on_off);

    if(start > end)
    {
        temp  = start;
        start = end;
        end   = temp;
    }

    if(on_off)
        printf("\nPrime numbers between %d and %d are:\n\n", start, end);

    for(num = start; num <= end; num++)
    {
        if(num == 1)
        {
            continue;
        }

        if( isPrime(num) )
        {
            slno++;

            if(on_off)
            {
                printf("%d. %d is prime number.\n", slno, num);
            }
         }
    }

    printf("\nThere are %d prime numbers between %d and %d.\n", 
             slno, start, end);

    return 0;
}

Output 1:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 10 and 30 are:

1. 11 is prime number.
2. 13 is prime number.
3. 17 is prime number.
4. 19 is prime number.
5. 23 is prime number.
6. 29 is prime number.

There are 6 prime numbers between 10 and 30.

Output 2:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 6 prime numbers between 10 and 30.

Output 3:
Enter start and end value
1
10
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 1 and 10 are:

1. 2 is prime number.
2. 3 is prime number.
3. 5 is prime number.
4. 7 is prime number.

There are 4 prime numbers between 1 and 10.

Output 4:
Enter start and end value
1
300
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 62 prime numbers between 1 and 300.

Output 5:
Enter start and end value
1
1000
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 168 prime numbers between 1 and 1000.

Logic To Count Prime Numbers Between Range

First we ask the user to enter the range and store it inside address of variables start and end. We make sure that start value is less than end value. If start value is greater than end value, we use a temporary variable to swap the values of start and end.

Swap 2 Numbers Using a Temporary Variable: C

Next we ask the user if he / she wants to display the prime numbers between the range or just want to know the count of prime numbers between the entered range. We store the user answer in a variable called on_off.

We start the for loop: We initialize the loop counter variable num to start and iterate through the loop until num is less than or equal to end. For each iteration of the for loop we increment the value of num by 1. This for loop selects number one by one from start to end. And this selected number, which is present inside variable num is checked for prime or not. If its prime we display it to the console window and keep track of the count of prime numbers, if not we simply ignore that non-prime number.

We use a function to check if the selected number present in variable num is a prime number or not. We call the function/method isPrime() inside if condition and pass the value of num to it. isPrime() returns 1 or 0 value. 1 means true and 0 means false. So if isPrime() returns 1, then the if condition becomes true and we increment the value of slno by 1 and optionally printout the prime number. If isPrime() returns 0, then we simply ignore it and go to the next number.

isPrime() function has the logic to determine if the given number is prime or not. We have explained the complete logic of this in a separate video tutorial, link to which is present below.

C Program To Find Prime Number or Not using For Loop

Note:
1. We are including math.h header file or library file since we are using sqrt() builtin method. sqrt() method is present inside math.h file.

2. We are also using continue and break keywords in our program and we’ve explained about it in detail in separate videos. Please watch them for more clarity about the topic.

Continue Statement In C Programming Language
break Statement In C Programming Language

Stay subscribed to our blog and YouTube channel. Thank you ..

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Prime Numbers From 1 To 300 using For Loop

Lets write a C program to print all the prime numbers from 1 to 300. (Hint: Use nested loops, break and continue).

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Note: Number 1 is neither prime nor composite number.

Related Read:
Nested For Loop In C Programming Language
C Program To Find Prime Number or Not using For Loop

Continue Statement In C Programming Language
break Statement In C Programming Language

Video Tutorial: C Program To Find Prime Numbers From 1 To 300 using For Loop


[youtube https://www.youtube.com/watch?v=a9GtETARgPk]

YouTube Link: https://www.youtube.com/watch?v=a9GtETARgPk [Watch the Video In Full Screen.]

Outer For loop Logic

Outer for loop selects number one by one for each iteration. We initialize num to 1 and for each iteration num value increments by 1. Outer for loop executes until num is less than or equal to 300.

Inner For loop Logic

All the numbers are perfectly divisible by number 1, so we initialize the variable i to 2, instead of 1. So our inner for loop starts checking for divisibility from number 2.

The selected number(selected by outer for loop and stored in variable num), is divided by numbers 2 to num-1 times. If num is perfectly divisible by any number between 2 to num-1, then the number is not a prime number, else its a prime number.

Source Code: C Program To Find Prime Numbers From 1 To 300 using For Loop

#include<stdio.h >
#include<math.h>

int main()
{
    int num, count, i, prime;

    printf("Prime Numbers from 1 To 300 are\n");

    for(num = 1; num <= 300; num++)
    {
        if(num == 1)
        {
            printf("Number 1 is neither prime nor composite\n");
            continue;
        }

        count = sqrt(num);
        prime = 1;
        for(i = 2; i <= count; i++)
        {
            if(num % i == 0)
            {
                prime = 0;
                break;
            }
        }

        if(prime)
        {
            printf("%d\t", num);
        }
    }

    return 0;
}

Output:
Prime Numbers from 1 To 300 are
Number 1 is neither prime nor composite
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293

Table of all prime numbers up to 1,000:

prime number or not

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

break Statement In C Programming Language

In this video tutorial lets learn more about the working of break statement or break keyword in C programming language.

Related Read:
Nested For Loop In C Programming Language

Video Tutorial: break Statement In C Programming Language


[youtube https://www.youtube.com/watch?v=7WsVGKKs2bg]

YouTube Link: https://www.youtube.com/watch?v=7WsVGKKs2bg [Watch the Video In Full Screen.]


Source Code: break Statement In C Programming Language : For Loop

#include<stdio.h>

int main()
{
    int i;

    for(i = 1; i <= 5; i++)
    {
        if(i == 3)
            break;

        printf("%d Apple\n", i);
    }
    printf("\nEnd of for loop.\n", i);
    return 0;
}

Output:
1 Apple
2 Apple

End of for loop.

In above C program we introduce break keyword when i is equal to 3. so for 3rd iteration of the for loop control exits the loop and whatever instructions present after the for loop gets executed.

Source Code: Continue Statement In C Programming Language : Nested For Loop

#include<stdio.h>

int main()
{
    int i, j;

    for(i = 1; i <= 5; i++)
    {
        printf("%d Apple\n", i);

        for(j = 1; j <= 3; j++)
        {
            if(j == 2)
                break;

            printf("\t%d Oracle\n", j);
        }

    }
    printf("\nEnd of for loop.\n", i);
    return 0;
}

Output:

1 Apple
        1 Oracle
2 Apple
        1 Oracle
3 Apple
        1 Oracle
4 Apple
        1 Oracle
5 Apple
        1 Oracle

End of for loop.

In above C program, inside inner for loop we’ve break keyword when j value is equal to 2. So once the keyword break is encountered, control exits the inner for loop. This doesn’t affect the outer for loop, as the keyword break is present inside the inner for loop.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

21 Matchstick Game: C Program

Write a C program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:

– There are 21 matchsticks.
– The computer asks the player to pick 1, 2, 3 or 4 matchsticks.
– After the person picks, the computer does its picking.
– Whoever is forced to pick up the last matchstick loses the game.

Related Read:
while loop in C programming
if else statement in C
Relational Operators In C

Logic of 21 Matchstick Game C Program

There are in total 21 match sticks to start the game. First we ask the user to pick either 1 or 2 or 3 or 4 matches per pick. Once the user makes his/her pick, computer makes the picking(same rules apply to the computer i.e., it can pick either 1 or 2 or 3 or 4 matches per pick). The trick is, computers pick is always 5 minus the pick of the user. For example, if computers pick is variable c and user pick is stored in variable p, then:
c = 5 – p;
This makes sure computer always wins the game. That is, the last pick will always be of the user.

Note: We have 1 as the condition in while loop to make sure the while loop keeps executing until a break statement is occurred inside the loop to terminate the execution of the loop. while(1) is considered as an infinite loop(unless we have some ways to break out of the loop programmatically).

Note:
break; breaks out of the loop or terminates the execution of the loop.

continue; skips execution of all the code after it in the loop and goes for the next iteration of the loop.

Video Tutorial: 21 Matchstick Game: C Program


[youtube https://www.youtube.com/watch?v=VO_5XTLxKmc]

YouTube Link: https://www.youtube.com/watch?v=VO_5XTLxKmc [Watch the Video In Full Screen.]

Source Code: 21 Matchstick Game: C Program

#include<stdio.h>

int main()
{
    int m = 21, p, c;

    while(1)
    {
        printf("\nNumber of Match sticks left = %d\n", m);
        printf("Pick 1 or 2 or 3 or 4 matches\n");
        scanf("%d", &p);

        if(p > 4 || p < 1)
            continue;

        m = m - p;

        printf("Number of matches left = %d\n", m);

        c = 5 - p;

        printf("out of which computer picked up %d\n", c);

        m = m - c;

        if(m == 1)
        {
            printf("\nNumber of matches left = %d\n", m);
            printf("You lost the Game\n");
            break;
        }
    }

    return 0;
}

Output:
Number of Match sticks left = 21
Pick 1 or 2 or 3 or 4 matches
2
Number of matches left = 19
out of which computer picked up 3

Number of Match sticks left = 16
Pick 1 or 2 or 3 or 4 matches
3
Number of matches left = 13
out of which computer picked up 2

Number of Match sticks left = 11
Pick 1 or 2 or 3 or 4 matches
1
Number of matches left = 10
out of which computer picked up 4

Number of Match sticks left = 6
Pick 1 or 2 or 3 or 4 matches
4
Number of matches left = 2
out of which computer picked up 1

Number of matches left = 1
You lost the Game

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Simple Calculator Program using Switch Case: C

In this video tutorial we shall perform Addition, Subtraction, Multiplication and Division of numbers based on user input, using switch case statement(decision control statement).

Related Read:
Basic Arithmetic Operations In C
Addition of 2 Numbers: C
Subtraction of 2 Numbers: C
Multiplication of 2 Numbers: C
Division of 2 Numbers: C
else if statement in C

We had written same calculator program using else-if clause. Same program has been modified to use Switch case in this program.
Simple Calculator Application In C

Simple Calculator using Switch Case: C Program


[youtube https://www.youtube.com/watch?v=HHuaYKKoMR4]

YouTube Link: https://www.youtube.com/watch?v=HHuaYKKoMR4 [Watch the Video In Full Screen.]


Working of Calculator Program
We display list of operation one can perform. That is,

1. Addition
2. Subtraction
3. Multiplication
4. Division

We ask the user to input his / her choice for arithmetic operation. If the user selects 1, then we ask the user to enter 2 integer numbers to perform addition operation. Once the user enters 2 integer numbers we add and display the result on the screen.

If the user enters wrong choice, we ask the user to enter proper choice.

Calculator Program using Switch Case: C Program

#include < stdio.h >

int main()
{
    int a, b;
    char choice;

    printf("Enter your choice\n");
    printf("a. Addition\nb. Subtraction\nc. Multiplication\nd. Division\n");
    scanf("%c", &choice);


   printf("Enter 2 integer numbers\n");
   scanf("%d %d", &a, &b);


    switch(choice)
    {
        case 'a': printf("%d + %d = %d\n", a, b, (a+b));
                break;

        case 'b': printf("%d - %d = %d\n", a, b, (a-b));
                break;

        case 'c': printf("%d x %d = %d\n", a, b, (a*b));
                break;

        case 'd': if( b != 0)
                    printf("%d / %d = %d\n", a, b, (a/b));
                else
                    printf("Number can't be divided by 0\n");
                break;

        default: printf("You entered wrong choice\n");
                 break;
    }

    return 0;
}

Output
Enter your choice
a. Addition
b. Subtraction
c. Multiplication
d. Division
c
Enter 2 integer numbers
5
10
5 x 10 = 50

In above program we are asking user to enter character a or b or c or d to perform addition, subtraction, multiplication and division operations respectively.

#include < stdio.h >

int main()
{
    int a, b, choice;

    printf("Enter your choice\n");
    printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n");
    scanf("%d", &choice);

    if( choice > 4 )
    {
        printf("Select with in the range!\n");
    }
    else
    {
        printf("Enter 2 integer numbers\n");
        scanf("%d %d", &a, &b);
    }


    switch(choice)
    {
        case 1: printf("%d + %d = %d\n", a, b, (a+b));
                break;

        case 2: printf("%d - %d = %d\n", a, b, (a-b));
                break;

        case 3: printf("%d x %d = %d\n", a, b, (a*b));
                break;

        case 4: if( b != 0)
                    printf("%d / %d = %d\n", a, b, (a/b));
                else
                    printf("Number can't be divided by 0\n");
                break;

        default: printf("You entered wrong choice\n");
                 break;
    }

    return 0;
}

Output:
Enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
4
Enter 2 integer numbers
10
2
10 / 2 = 5

Here we are asking user to enter 1 or 2 or 3 or 4 to choose the arithmetic operation.

#include

int main()
{
    int a, b;
    char choice;

    printf("Enter your choice\n");
    printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n");
    scanf("%c", &choice);

    printf("Enter 2 integer numbers. Format: a + b\n");
    scanf("%d %c %d", &a, &choice, &b);



    switch(choice)
    {
        case '+': printf("%d + %d = %d\n", a, b, (a+b));
                break;

        case '-': printf("%d - %d = %d\n", a, b, (a-b));
                break;

        case '*': printf("%d x %d = %d\n", a, b, (a*b));
                break;

        case '/': if( b != 0)
                    printf("%d / %d = %d\n", a, b, (a/b));
                else
                    printf("Number can't be divided by 0\n");
                break;

        default: printf("You entered wrong choice\n");
                 break;
    }

    return 0;
}

Output:
Enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
1
Enter 2 integer numbers. Format: a + b
50 + 60
50 + 60 = 110

Here we ask the user to enter values as well as the operation to be performed. Operands and operator.

Note 1: There is no need of curly braces inside case.
Note 2: If a case doesn’t end with break statement, then the execution continues and the block of code present inside next case will also get executed.
Note 3: default case is optional. And the code inside it executes only when non of the cases match.
Note 4: Here switch, case, break, default are all keywords / reserve words.

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert