Programming for Problem Solving (3110003)

BE | Semester-1   Winter-2019 | 07-01-2020

Q3) (c)

Write a program to find sum of first N odd numbers. Ex. 1+3+5+7+………..+N .

Program

#include <stdio.h>
void main() {
    int n, i, s=0;
    printf("Enter n: ");
    scanf("%d", &n);
    
    for(i=1; i<=n; i++) {
        if(i%2 != 0) {
            if(i == n)
                printf("%d", i);
            else 
                printf("%d + ", i);  
            s = s + i;                              
        }
    }
    printf("\nSum of Series = %d\n", s);
}

Output:

Enter n: 5
1 + 3 + 5
Sum of Series = 9