C++ Program to print the sum of n odd numbers using do while
Program
#include <iostream>
using namespace std;
int main()
{
int i, n;
int sum = 0;
cout << "Enter the value of n \n";
cin >> n;
i = 1;
do
{
if (i % 2 != 0)
{
sum = sum + i;
}
i++;
} while (i <= n);
cout << "Sum of all odd numbers from 1 to " << n << " is:" << sum;
return 0;
}
Output
$g++ sum-of-n-odd-numbers-using-do-while.cpp
$ ./a.out
Enter the value of n
46
Sum of all odd numbers from 1 to 46 is:529