28. Program to calculate the sum of the first n odd integers.

Chapter 6: 

Looping Structures

Programming Exercise

Problem # 28:

Write a program to calculate the sum of the first n odd integers.

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    int n, o_num, num=0, sum=0;
    cout<<"Enter the number of odd numbers required:";
    cin>>o_num;
    for(n=1;num<o_num;n++)
    {
        if(n%2!=0)
        {
            sum=sum+n;
            num++;
        }  
    }
    cout<<"\nThe sum of first "<<num<<" odd numbers is: "<<sum<<endl;
    getch();
}

Let me know in the comment section if you have any question.

Previous Post:
27. A person invests $1000.00 in a saving account yielding 5% interest. Calculate and print the amount of money in the accounts at the end of each year for ten years.

Comments