C Program To Find Sum of All Odd Numbers From 1 To N, using While loop

Lets write a C program to find sum of all the odd numbers from 1 to N, using while loop.

Odd Number: An odd number is an integer that is not exactly divisible by 2.

For Example: 3 % 2 != 0. When we divide 3 by 2, it doesn’t give a reminder of 0. So number 3 is odd number.

Related Read:
Decision Control Instruction In C: IF
while loop in C programming
Even or Odd Number: C Program

Video Tutorial: C Program To Find Sum of All Odd Numbers From 1 To N, using While loop



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

Logic To Find Sum of All Odd Numbers From 1 To N, using While loop

Since we are checking for odd numbers from 1 to user entered number, we assign value of variable count to 1. While loop keeps iterating until value of count is less than or equal to value of user input number. For each iteration of while loop we increment the value of count by 1.

Inside while loop we check for the condition, count%2 != 0. If it’s true, then we add the value present inside variable count to previous value present in variable sum.

After the control exits while loop we display the value present in variable sum – which has the sum of all the odd numbers from 1 to user entered number.

Source Code: C Program To Find Sum of All Odd Numbers From 1 To N, using While loop

#include<stdio.h>

int main()
{
    int num, count = 1, sum = 0;

    printf("Enter a integer number\n");
    scanf("%d", &num);

    while(count <= num)
    {
        if(count%2 != 0)
        {
            sum = sum + count;
        }
        count++;
    }

    printf("Sum of ODD integer number is %d\n", sum);

    return 0;
}

Output 1:
Enter a integer number
5
Sum of ODD integer number is 9

Output 2:
Enter a integer number
20
Sum of ODD integer number is 100

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