C++ Program to print the sum of n odd numbers using 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;
while (i <= n)
{
if (i % 2 != 0)
{
sum = sum + i;
}
i++;
}
cout << "Sum of all odd numbers from 1 to " << n << " is:" << sum;
return 0;
}
Output
$ g++ sum-of-n-odd-numbers-using-while.cpp
$ ./a.out
Enter the value of n
20
Sum of all odd numbers from 1 to 20 is:100