Q:

C Program to find the sum of odd natural numbers from 1 to n

belongs to collection: C Programming on Numbers

0

In this exercise we learn C Program to find the sum of odd natural numbers from 1 to n. We will take the help of iterative statements like for, while or do-while loop to find the sum of odd numbers from 1 to n.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C Program to find the sum of odd numbers 1 to n using if and for Loop

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will calculate the sum of odd natural numbers 1 to n terms with the help of for loop.

#include<stdio.h>
int main()
{
    int num, i;
    unsigned long int sum = 0;
    printf("Please Enter any Integer number = ");
    scanf("%d", &num);
    //Validate positive number
    if(num >0)
    {
        for(i = 1; i <= num; i++)
        {
            if((i%2) != 0)
            {
                sum += i;
            }
        }
        printf("Sum = %ld\n",sum);
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Output:

Please Enter any Integer number = 10
Sum = 25

-----------------------------------------------------------------------------------------------

C Program to find the sum of odd numbers 1 to n without using if

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will calculate the sum of odd natural numbers 1 to n terms without using the if condition.

#include<stdio.h>
int main()
{
    int num, i;
    unsigned long int sum = 0;
    printf("Please Enter any Integer number = ");
    scanf("%d", &num);
    //Validate positive number
    if(num >0)
    {
        //Get odd numbers only
        for(i = 1; i <= num; i+=2)
        {
            //calculating sum
            sum += i;
        }
        printf("Sum = %ld\n",sum);
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Output:

Please Enter any Integer number = 10
Sum = 25

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C Program to find the sum of odd numbers within a ... >>
<< C Program to find the sum of natural numbers withi...