YouTip LogoYouTip

C Examples Sum Natural Numbers

# C Example - Sum of Natural Numbers [![Image 3: C Examples](#) C Examples](#) Natural numbers are numbers that represent the count of objects, starting from 0, i.e., 0, 1, 2, 3, 4, ..., one after another, forming an infinite set, referring to non-negative integers. ## Example - Using for #includeint main(){int n, i, sum = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=1; i<= n; ++i){sum += i; // sum = sum+i;}printf("Sum = %d",sum); return 0; } ## Example - Using while #includeint main(){int n, i, sum = 0; printf("Enter a positive integer: "); scanf("%d",&n); i = 1; while(i<=n){sum += i; ++i; }printf("Sum = %d",sum); return 0; } Output: Enter a positive integer: 100Sum = 5050 ## Example - Using recursion #includeint addNumbers(int n); int main(){int num; printf("Enter an integer: "); scanf("%d", &num); printf("Sum = %d",addNumbers(num)); return 0; }int addNumbers(int n){if(n != 0)return n + addNumbers(n-1); else return n; } [![Image 4: C Examples](#) C Examples](#)
← C Examples Multiplication TablC Examples Negative Positive Z β†’