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


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

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

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

Related Read:
Decision Control Instruction In C: IF
For Loop In C Programming Language
Even or Odd Number: C Program

You can also watch the video for C Program To Find Sum of All Odd Numbers From 1 To N, using While loop

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


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

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

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

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

Inside for 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 for 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 For loop

#include<stdio.h>

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

    printf("Enter the limit\n");
    scanf("%d", &num);

    printf("Odd numbers from 1 To %d are:\n", num);
    for(count = 1; count <= num; count++)
    {
        if(count % 2 != 0)
        {
            printf("%d\n", count);
            sum = sum + count;
        }

    }

    printf("Sum of odd numbers from 1 To %d is %d\n", num, sum);

    return 0;
}

Output 1:
Enter the limit
5
Odd numbers from 1 To 5 are:
1
3
5
Sum of odd numbers from 1 To 5 is 9

Output 2:
Enter the limit
10
Odd numbers from 1 To 10 are:
1
3
5
7
9
Sum of odd numbers from 1 To 10 is 25

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

Leave a Reply

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