This blog is under construction

Wednesday 10 July 2013

C program to find the sum of first n odd numbers

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


  #include <stdio.h>

  int main() {
        int num, count = 0, j = 1, sum = 0;

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

        /* calculate the sum of first n odd numbers */
        while (count < num) {
                if (j % 2 != 0) {
                        sum = sum + j;
                        count++;
                }
                j++;
        }

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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:100
  Sum of first 100 odd numbers is 10000



3 comments:

  1. what does the J stand for?

    ReplyDelete
    Replies
    1. it is used instead of i.it just stands for the variable used for for function.

      Delete