Sum of Natural number between two range in C language…

Let’s understand some concept.

Natural Number..

All counting number which start from 1, 2, 3, 4, 5, 6, 7, 8, 9…………………. Infinite…

Sum of Natural Number between two range b=n/2*[2*a+(n+1)*d] if you enter number then the sum done by this formula…

  • a=first number
  • n = number of Natural number
  • d= difference between the two number

Some important symbols used in code.

  • () small bracket
  • && use for ‘and’ use for address
  • {} curly bracket
  • “” double code

Sum by using the arithmetic progression..

  • #include<stdio.h>
  • #include<conio.h>
  • void main()
  • {
  • int a, b, c, d, n, e, f, g, h;
  • clrscr();
  • printf(“Enter Number to find the Sum of Natural number between two range \n Enter two range number”);
  • scanf(“%f%f”, &b, &c);
  • n=c-b;
  • d=1;
  • a=b;
  • e=n/2;
  • f=2*a+(n-1)*d;
  • g=e*f;
  • printf(“%f”, g);
  • getch();
  • }

Inputs..

If b=10 and c=20 then

Results..

Sum= 165

Sum by using ‘for’ loop..

If you enter range of Natural Number then using a loop. A after increment natural Number added by this method b+=a which like a++. In loop same rule follow by Increment and adding in on container like all alphabet.

  • #include<stdio.h>
  • #include<conio.h>
  • void main()
  • {
  • float a, b, c, d=0, e;
  • clrscr();
  • printf(“Enter two range to find sum of Natural number between range number”);
  • scanf(“%f%f”, &a, &b);
  • for(c=a;c<=b;c++)
  • {
  • d+=c;
  • }
  • printf(“%f”, d);
  • getch();
  • }

Inputs..

If a=10 and b=20 then

Results..

Sum= 165

Sum by using ‘while’ loop..

  • #include<stdio.h>
  • #include<conio.h>
  • void main()
  • {
  • float a, b, c, d=0, e;
  • clrscr();
  • printf(“Enter two range to find sum of Natural number between range number”);
  • scanf(“%f%f”, &a, &b);
  • while(a<=b)
  • {
  • c+=a;
  • a++;
  • }
  • printf(“%f”, c);
  • getch();
  • }

Inputs..

If a=10 and b=20 then

Results..

Sum= 165

Sum by using ‘do while’ loop..

  • #include<stdio.h>
  • #include<conio.h>
  • void main()
  • {
  • float a, b, c, d=0, e;
  • clrscr();
  • printf(“Enter two range to find sum of Natural number between range number”);
  • scanf(“%f%f”, &a, &b);
  • do
  • {
  • c+=a;
  • a++;
  • }
  • while(a<=b);
  • printf(“%f”, c);
  • getch();
  • }

Inputs..

If a=10 and b=20 then

Results..

Sum= 165

Design a site like this with WordPress.com
Get started