07/03/2016

C Program to Find Sum of Natural Numbers Using While Loop

Problem :- Write A C Program to Find Sum of Natural Numbers Using While Loop

Logic :- What is Natural Number ?
Natural Numbers Are Positive numbers Start With 1 Not 0 ( Zero )
So idea is simple use loop ans initialize with 1 and run into last terms ( Till you Want ) ,you can also print the sum of natural number using formula there are 2 method for solve.
Method 1 :-Using Formula

Natural Number = (N*(N+1))/2

Method 2:- Using Loop

while(count<=n)
{
sum+=count;
++count;
}

Try Yourself C++ Program To Check Number Is Armstrong Or Not

Solution :-

Method 1:-

#include<stdio.h>
int main()
{
  //Ghanendra Yadav
    int n, count=1, sum=0;
    
    while(1)
    {
printf("\nEnter The Natural Number :\n");
    scanf("%d",&n);
    
while(count<=n)
    {
        sum+=count;
        ++count;
    }
    
printf("\nSum Of Natural Number Is  = %d\n",sum);
    
}
return 0;
}

Method 2:-

#include<stdio.h>
int main()
{
  //Ghanendra Yadav
    int n,sum=0;
    
    while(1)
    {
printf("\nEnter The Natural Number :\n");
    scanf("%d",&n);
    
sum=(n*(n+1))/2;
printf("\nSum Of Natural Number Is  = %d\n",sum);
    
}
return 0;
}

Output:-

C Program to Find Sum of Natural Numbers Using While Loop

Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

1 comment:

  1. in first one if you put higher numbers, and then go for lower number
    the answer will not come. As yr count value is already more then yr given no.
    For correcting this put this,
    if(n<count)
    {count=1;
    sum=0; }
    after scanf function

    ReplyDelete