This blog is under construction

Wednesday 10 July 2013

C program to find the sum of first n even numbers

Write a C program to find the sum of first n even numbers.


  #include <stdio.h>

  int main() {
        int n, count = 0, i = 1, sum = 0;

        /* get the input from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of first n even numbers */
        while (count < n) {
                if (i % 2 == 0) {
                        sum = sum + i;
                        count++;
                }
                i++;
        }

        /* print the sum of first n even numbers */
        printf("Sum of first %d even numbers is %d\n", n, sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:5
  Sum of first 5 even numbers is 30



No comments:

Post a Comment