Write a C program to find the sum of all odd numbers from 1 to n.
Odd Number: An integer which is not divisible by 2.
#include <stdio.h>
int main() {
int i, n, sum = 0;
printf("Enter the value for n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
if (i % 2 == 0)
continue;
/* sum of odd numbers */
sum = sum + i;
}
/* print the result - sum of odd nos */
printf("Sum of odd numbers:%d\n", sum);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the value for n:100
Sum of odd numbers:2500
Enter the value for n:100
Sum of odd numbers:2500
No comments:
Post a Comment