This blog is under construction

Monday, 10 June 2013

C program to find the sum of all odd numbers from 1 to n

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.


  /* C program to find the sum of all odd nos from 1 to n */
  #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



No comments:

Post a Comment