Check The Programming Section
Using Iterative Approach
#include <stdio.h>
int main(){
int num;
//this variable will be used to save the result of the sum
int sum = 0;
printf("Enter any positive number....");
scanf("%d",&num);
for(int i=1;i<=num;i++){
sum = sum + i;
}
printf("The sum of the numbers from 1 to %d is %d",num,sum);
return 0;
}
Using a Function
#include <stdio.h>
//this function will take a number as argument and
//retrun the sum upto that number to the calling function
int getSum(int num){
//this variable will be used to save the result of the sum
int sum = 0;
printf("The sum of the numbers from 1 to %d is\n",num);
for(int i=1;i<=num;i++){
sum = sum + i;
printf("%d+",i);
}
return sum;
}
int main(){
int num;
printf("Enter Any number ::");
scanf("%d",&num);
//number is passed as argument to the fun
int sum = getSum(num);
printf("=%d",sum);
return 0;
}
Using Function Recursion
#include <stdio.h>
//this function will take a number as argument and
//call itself till the number > 0
int getSum(int num){
//base condition
if(num>0){
num>1?printf("%d+",num):printf("%d",num);
return num + getSum(num-1);
}
}
int main(){
int num;
printf("Enter Any number ::");
scanf("%d",&num);
printf("The sum of the numbers from 1 to %d is\n",num);
//number is passed as argument to the fun
int sum = getSum(num);
printf("=%d",sum);
return 0;
}