Write a C program to add a series of odd numbers i.e. 1+3+5+7+……..+n

This program will give you an idea of adding a series having only odd numbers. Let a series  1+3+5+7+……..25. Now Define the first odd number by a variable and last odd number by another variable. Then use a while loop for performing sum operation. Here I used variable i as loop counter as well as putting each odd number of the series on it. While loop will stop when i>lastODDnumber 
 

//1+3+5+..............+n
#include <stdio.h> 
main(){
    int i,n1,n2,SUM=0;
    printf("Insert the first ODD number: ");
    scanf("%d",&n1);
    printf("Insert the last ODD number: ");
    scanf("%d",&n2);
    i=n1; //initialize i by first odd number
    while(i<=n2){
        SUM=i+SUM;
        i=i+2;
    }
    printf("Total: %d",SUM);
    return 0;
}

No comments:

Post a Comment