Q:

Write a C Program to find out the sum of first n numbers

0

Write a C Program to find out the sum of first n numbers. Here’s simple Program to find out the sum of first n numbers in C Programming Language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

LOGIC : : 

The program asks the user to enter the number of terms he/she would like to evaluate the sum of, which is stored in variable n. Another variable i is assigned value 1, which is used for counting the number of terms in the loop and also as a natural number which is added to the result.

The variable sum stores sum of the natural numbers. The sum is initialized to 0 to avoid addition of garbage numbers.As the program enters the loop, value of i is added to the variable sum which now equals the sum of all natural numbers till i. Then the value of i is increased by 1.

The loop continues as long as the value of i is less than or equal to n as we are calculating the sum of first n natural numbers. When, the loop exits, the result is displayed on the screen.

Below is the source code for C Program to find out the sum of first n numbers which is successfully compiled and run on Windows System to produce desired output as shown below :

SOURCE CODE : :

/* C Program to find out the sum of first n numbers */

#include<stdio.h>
#include<conio.h>

int main()
{
  int i=0,num,sum=0;
  printf("Enter a number :: ");
  scanf("%d",&num);
  for(;i<num;i++)
  {
  sum=sum+i;
  }
  printf("\n The sum of numbers = %d",sum);

  return 0;
}

OUTPUT : :

/* C Program to find out the sum of first n numbers */

Enter a number :: 6

 The sum of numbers = 15

Above is the source code for C Program to find out the sum of first n numbers which is successfully compiled and run on Windows System.The Output of the program is shown above .

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Number Solved Programs – C Programming

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a C Program To find the biggest and smallest... >>
<< C Program to display sum of even and product of od...