-->

program to get/sum of all even numbers lying between 1 to n natural numbers

//program  to get/sum of all even numbers lying between 1 to n natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int k=0,n,sum=0;                         //you can take k=1, even
printf("enter value of 'n'\n");
scanf("%d",&n);
while(k<=n)
   {
      if(k%2==0)
      {      sum=sum+k;
      }
    k++;
   }
printf("the sum=%d",sum);getch();
getch();
}

-----------------------------
we can also write this program as shown below.
-------------------------------------
//program  to get/sum of all even numbers lying between 1 to n natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int k=0,n,sum=0;                         
printf("enter value of 'n'\n");
scanf("%d",&n);
while(k<=n)
   {
            sum=sum+k;
      
    k=k+2;
   }
printf("the sum=%d",sum);
getch();
getch();
}


No comments:

Post a Comment