Program to find out the sum of natural numbers


Default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Write a program to find out the sum of natural numbers
// Ex: 4 -> 10; 10 -> 55
// Author: AimForJob.com
#include<stdio.h>
int main(){
    int num;
    printf("Enter a number to find sum upto that number:");
    scanf("%d",&num);
    while(num<=0){
        printf("Please enter only a positive integer: ");
        scanf("%d",&num);        
    }
    // calculating sum of natural numbers
    int i=1;
    printf("\n");
    if(num<=4){
        while(i<num){
            printf("%d+",i);      
            i++;
        }
        printf("%d\n",i);
    }
    else{
        printf("1+2+...+%d+%d\n",num-1,num);
    }
    long long int sum;
    sum = (num/2.0)*(num+1);
    printf("Sum of the natural numbers upto %d is: %lld",num,sum);
getch();
}

No comments:

Post a Comment