Write C program to accept the value of n and display sum of all odd numbers up to n.

#include<conio.h>
#include<stdio.h>
void main()
{
int n,i,sum;   //n=no of odd numbers , sum= to get sum of all odd number till n

   //Accept value of n
   printf("\nEnter value of n: ");
   scanf("%d",&n);

   sum=0;//initialize value of sum

   for(i=1;i<=n;i++)
   {
    if(i%2!=0)
      {
      sum=sum+i;  //to add every odd numbers till n in sum variable
      }
   }

   //printing a result
   printf("\nSum of all odd numbers till %d = %d",n,sum);
   getch();
}

0 Comments