C Program to Find the Number of Integers Divisible by 3

C Programming Computer Science

In this program we will write code to find the number of integers which are divisible by 3 in the given range.

  • Source Code

/*
 * C program to find the number of integers divisible by 
 * 3 between the given range n1 and n2. where n1 < n2.
 *
 * Also find the sum of all these integer numbers which are divisible
 * by 3 and display the total.
 */
#include <stdio.h>
 
void main()
{
    int i, n1, n2, count = 0, sum = 0;
 
    printf("Enter the value of n1 and n2 \n");
    scanf("%d %d", &n1, &n2);
    /* Count the number and compute their sum*/
    printf("Integers divisible by 3 are \n");
    for (i = n1; i < n2; i++)
    {
        if (i % 3 == 0)
        {
            printf("%d,", i);
            count++;
            sum = sum + i;
        }
    }
    printf("\n Number of integers divisible by 3 between %d and %d =
 %d\n", n1, n2, count);
    printf("Sum of all integers that are divisible by 3 = %d\n", sum);
}

 

  • Runtime
Case:1
Enter the value of n1 and n2
10 15
Integers divisible by 3 are 12,15
Number of integers divisible by 3 between 10 and 15 = 2
Sum of all integers that are divisible by 3 = 27
 
Case:2
Enter the value of n1 and n2
1 10
Integers divisible by 3 are
3,6,9
Number of integers divisible by 3 between 1 and 10 = 3
Sum of all integers that are divisible by 3 = 18

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.