Â
In this, we are going to see while loop, the program is based on while loop which prints, the sum of only positive numbers.
The code given below can be used for TURBO C++ Compiler:-
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, sum;
cout << "Enter the value of n (should be a positive integer): ";
cin >> n;
if (n >= 0)
{
int i = 1;
while (i <= n)
{
sum = sum + i;
i++;
}
cout << "sum of positive n no. is: " << sum << endl;
}
else
{
cout << "invaild input " << sum;
}
getch();
}
The code given below can be used for g++/gcc Compiler:-
#include<iostream>
using namespace std;
int main()
{
int n, sum;
cout << "Enter the value of n (should be a positive integer): ";
cin >> n;
if (n >= 0)
{
int i = 1;
while (i <= n)
{
sum = sum + i;
i++;
}
cout << "sum of positive n no. is: " << sum << endl;
}
else
{
cout << "invaild input " << sum;
}
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP