C Program to find the sum of ‘n’ numbers using functions !

Program to find the sum of n numbers using functions

This article explains you how to find sum of n numbers using functions.

Example:
Given the value of n = 3.
Sum of 3 numbers = 1+2+3
answer = 6

Logic:
1. Take a value of n
2. Define a variable sum, i and inintialize it to 0 (int sum = 0 and int i = 0)
3. Store the value of sum +i in variable sum ( sum = sum + i )
4. Increment the value of i
5. Repeat above 2 steps till value of i becomes less than or equal to n. ( i <= n)
6. Print the value stored in variable sum.

Source code:

#include<stdio.h>
int sum(int);
int main()
{
      int num,s;
      printf("enter value of n:");
      scanf("%d",&num);
      s = sum(num);
      printf("sum of %d numbers = %d\n",num,s);
}
int sum(int num)
{
     int i,sum=0;
     for(i=0;i<=num;i++)
     {
          sum = sum + i;
      }
      return sum;
}


This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

We offer Embedded System certification courses in Bangalore ! 

2 Response Comments

  • Jay Buddhdev  March 1, 2017 at 1:30 pm

    why int sum(int); is written befor int main()

    Reply
    • subhash_user  July 24, 2017 at 5:06 pm

      It’s known as the function prototype.

      Reply

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.