• C program to find sum of n numbers using function
  • This is about to get sum of all natural numbers in C using for loop
  • For example 4: 1+2+3+4=11
  • Let us see an example program to get  sum of natural numbers using while loop.
  • c program to find sum of n numbers using for loop



Program #1 :  Write a C program to get sum of all natural numbers up to n using for loop

  1. // www. instanceofjava.com all rights reserved
  2.  #include<stdio.h> 
  3. #include<math.h>
  4.  
  5. int main()
  6. {
  7.     int n, i, sum = 0;
  8.     
  9.     printf("Enter a positive integer: ");
  10.     scanf("%d",&n);
  11.  
  12.     for(i=1; i <= n; ++i)
  13.     {
  14.         sum += i;   // sum = sum+i;
  15.     }
  16.  
  17.     printf("Sum = %d",sum);
  18.  
  19.    return 0;
  20. }

 Output:


sum of all natural numbers in c

In this program, we first declare three variables: n, i, and sum. We use the printf function to prompt the user to enter the value of n, and the scanf function to read the value entered by the user and store it in the n variable.

The for loop iterates from 1 to n, and for each iteration, the current value of i is added to the sum variable. Once the loop completes, the final value of sum is the sum of the first n natural numbers.

The program then prints the final value of sum using the printf function.

You can try running this program and entering different values for n to see how it works.

Note: This program assumes that the input will be valid. You may want to include error check for non-integer input or negative number input.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu