Monday, August 4, 2014

C Program to Calculate the Sum of Odd & Even Numbers

This C Program calculates the sum of odd & even numbers. The program first seperates odd and even numbers. Later it adds the odd and even numbers seperately.
Here is source code of the C program to calculate the sum of odd & even numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program to find the sum of odd and even numbers from 1 to N
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     int i, num, odd_sum = 0, even_sum = 0;
  9.  
  10.     printf("Enter the value of num\n");
  11.     scanf("%d", &num);
  12.     for (i = 1; i <= num; i++)
  13.     {
  14.         if (i % 2 == 0)
  15.             even_sum = even_sum + i;
  16.         else
  17.             odd_sum = odd_sum + i;
  18.     }
  19.     printf("Sum of all odd numbers  = %d\n", odd_sum);
  20.     printf("Sum of all even numbers = %d\n", even_sum);
  21. }

$ cc pgm12.c
$ a.out
Enter the value of num
10
Sum of all odd numbers  = 25
Sum of all even numbers = 30
 
$ a.out
Enter the value of num
100
Sum of all odd numbers  = 2500
Sum of all even numbers = 2550

No comments:

Post a Comment