Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
Sum of Numbers from 1 to n in C
✅ C Program to Calculate Sum from 1 to n
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a positive number: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive number.\n");
return 1;
}
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of numbers from 1 to %d is: %d\n", n, sum);
return 0;
}
๐ Explanation:
✅ This program calculates the sum of all natural numbers from 1 to n.
✅ It uses a for loop to iterate from 1 to the given number n.
✅ On each iteration, it adds the value to a running sum variable.
✅ If the input is non-positive, it displays an error message.
๐งพ Sample Output:
Enter a positive number: 5 Sum of numbers from 1 to 5 is: 15
๐ Keywords:
Sum from 1 to n in C, C loop program, C addition logic, beginner C project, for loop in C, positive number sum
๐ Hashtags:
#CProgramming #ForLoop #BeginnerC #MathInC #SumOfNumbers #InterviewPrep #CodingBasics
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment