find sum of all odd numbers from 1 to n using for loop
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
sum += i;
}
}
printf("Sum of all odd numbers from 1 to %d is %d", n, sum);
return 0;
}
Explanation:
- In this program, we are finding the sum of all odd numbers from 1 to a given number n
.
- We start by including the necessary header file stdio.h
, which contains the standard input/output functions.
- The main()
function is the entry point of the program.
- We declare two variables n
and sum
, both of type int
. n
will store the given number, and sum
will store the sum of odd numbers.
- We prompt the user to enter a number using the printf()
function and read the input using the scanf()
function. The entered number is stored in the variable n
.
- We initialize the variable sum
to 0, as we haven't calculated the sum yet.
- Next, we use a for
loop to iterate from 1 to n
(inclusive) using the variable i
as the loop counter.
- Inside the loop, we use an if
statement to check if the current value of i
is odd. This is done by checking if i
modulo 2 is not equal to 0. If i
is odd, we add its value to the sum
variable.
- After the loop finishes, we print the result using the printf()
function. The %d
format specifier is used to print the values of n
and sum
.
- Finally, we return 0 from the main()
function, indicating successful program execution.