Problem
Statement
In
this program we will code a basic program to find the sum of first ‘N’ numbers
in C Programming language.
Code
#include
using namespace std;
int sumofn(int n)
{
int sum=0,i;
for(i=1;i<=n;i++)
{
sum+=i;
}
return sum;
}
int main()
{
int n;
printf("Enter
the number ?\n");
scanf("%d",&n);
int res=sumofn(n);
printf("Sum of
first %d numbers : %d",n,res);
return 0;
}
Output
Enter
the number ? - 5
Sum
of first 5 numbers : 15
Explanation
In
this problem we have to find the sum of first 'N' numbers. To do so we declare
a variable 'sum',which will store the result value(don't forget to initialize
it with zero). Then,to access each value from '1' to 'N',we run the loop and
update our 'sum' value by adding updated value of 'i', 'N' times,and we get the
result.


0 Comments