This blog is under construction

Saturday, 22 June 2013

C program to find the sum of odd numbers from 1 to N

Write a C program to find the sum of odd numbers from 1 to N.


  #include <stdio.h>
  int main() {
        int n, i, sum = 0;
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of odd nos between 1 and n */
        for (i = 1; i <= n; i++) {

                /* skip the even numbers */
                if (i % 2 == 0)
                        continue;
                sum = sum + i;
        }
        printf("Output: %d\n", sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out 
  Enter the value for n:100
  Output: 2500



No comments:

Post a Comment