C program to find sum of all numbers from 0 to N without using loop

Here, we are implementing a C program that will be used to find the sum of all numbers from 0 to N without using loop.
Submitted by IncludeHelp, on September 04, 2018

Problem statement

Given the value of N and we have to find sum of all numbers from 0 to N in C language.

To find the sum of numbers from 0 to N, we use a mathematical formula: N(N+1)/2

Example

Input:
Enter value of N: 5
Logic/formula:
sum = N*(N+1)/2 = 5*(5+1)/2 =5*6/2 = 15
Output:
sum = 15


Input:
Enter value of N: 10
Logic/formula:
sum = N*(N+1)/2 = 10*(10+1)/2 =10*11/2 = 110/2 = 55
Output:
sum = 55

C program to find sum of all numbers from 0 to N without using loop

#include <stdio.h>

int main(void) {
	
    int n, sum;
	
    //input value of n
    printf("Enter the value of n: ");
    scanf("%d", &n);
	
    //initialize sum with 0
    sum =0;
	
    //use formula to get the sum from 0 to n
    sum = n*(n+1)/2;
	
    //print sum 
    printf("sum = %d\n", sum);
	
    return 0;
}

Output

Run1:
Enter the value of n: 5
sum = 15

Run2:
Enter the value of n: 10
sum = 55

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.