c program to find sum of n numbers using function and for loop

11/15/2023
All Articles

#c program find sum of n numbers using function for loop

c program to find sum of n numbers using function and for loop

C Program to Find Sum of N Numbers Using Function and For Loop

In this article, we will learn how to write a C program to find the sum of N numbers using a function and a for loop. This program is a great example for beginners to understand the use of functions and loops in C programming.

Mathematical Formula for Sum of N Numbers

The sum of the first N natural numbers can be calculated using the formula:


Sum = N * (N + 1) / 2
    

For example, the sum of the first 5 natural numbers is:


Sum = 5 * (5 + 1) / 2 = 15
    

C Program to Find Sum of N Numbers

Below is a C program that calculates the sum of the first N natural numbers using a function and a for loop:


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

// Function to calculate the sum of N numbers
void my_sum(int n) {  
    int i, s = 0;  
    for (i = 1; i <= n; i++) {  
        s += i;  
    }  
    printf("Sum of first %d integers is %d\n", n, s);  
}  

int main() {  
    int n;  
    clrscr();  
    printf("Please enter a number: ");  
    scanf("%d", &n);  
    my_sum(n);  
    getch();  
    return 0;  
}
    

Explanation of the Code

  1. Function my_sum: This function takes an integer n as input and calculates the sum of the first n natural numbers using a for loop.
  2. For Loop: The loop iterates from 1 to n, adding each number to the variable s.
  3. Main Function: The program prompts the user to enter a number, calls the my_sum function, and prints the result.

Output Example

If the user enters 5, the output will be:


Please enter a number: 5
Sum of first 5 integers is 15
    

Conclusion

This C program demonstrates how to use a function and a for loop to calculate the sum of the first N natural numbers. It’s a simple yet effective way to understand the basics of functions, loops, and user input in C programming. Try modifying the program to calculate the sum of numbers in different ranges or using other mathematical formulas!

Article