Easy C++ concept I can't understand can anyone help me write this program?
Write a program that prompts the user to enter a positive integer. The program should then output whether it is a triangular number or not. Include a function to validate the input and a function to test if the input is a triangular number or not.
I feel extremely dumb and just want to know how to do this for future reference. Thanks in advance
>>8464241
#include <iostream>
using namespace std;
bool isTriangular(int);
int main()
{
int x;
cout<<"Please enter positive integer :\n";
cin>>x;
return 0;
}
bool isTriangular(int x){
this is what I have so far
The formula for triangular numbers is n(n+1)/2
Just do the reverse to see if you end up with a positive integer.
The reverse is at the bottom of this page: https://en.wikipedia.org/wiki/Triangular_number
We all feel lazy sometimes but you should really make a bit more of an effort with this extremely baby assignment. Programming is one of the most important life skills you can learn.
>>8464250
>https://en.wikipedia.org/wiki/Triangular_number
The problem I'm having is just the validation part. I had a working program but when I prompted the user to reenter x with a while loop the result turned out wrong.
>>8464242
>this is what I have so far
So nothing.
cpp.sh/7er3q
>>8464250
Solved it. Sorry I was facing a deadline.
Here is the finished code
#include <iostream>
using namespace std;
bool isTriangular(int);
int main()
{
int x;
do{
cout<<"Please enter positive integer :\n";
cin>>x;
}
while(x<0);
if (isTriangular(x))
cout << "The number is a triangular number";
else
cout << "The number is NOT a triangular number";
return 0;
}
bool isTriangular(int x)
{
if (x < 0)
return false;
int sum = 0;
for (int n=1; sum<=x; n++)
{
sum = sum + n;
if (sum==x)
return true;
}
return false;
}
>>8464376
That'll work.
Better would've been to check if n^2 + n - 2x = 0 has a positive integer solution, because x is triangular iff that's the case.
>>8464253
This means you do not understand program flow.
Don't worry, no one actually does. Just re-read the program book section of your book so that you can at least handle this babby problem.
/*
x = n*(n+1)/2
n=1/2*( sqrt(8 x +1) - 1)
*/
int IsTriangular(int x)
{
int h2,h;
h2=8*x+1;
h=(int)sqrt((double)h2)+0.5);
if (h*h!=h2) return(0);
if ((h-1)%2==0) return((h-1)/2); /* n= (h-1)/2 */
return(0);
}
>>8464706
>This means you do not understand program flow.
>Don't worry, no one actually does.
>no one actually does.
Speak for yourself, brainlet. You can easily imagine it in your head if you aren't retarded. You can literally run a program or a part of it in your head.
Is /sci/ really full of brainlets like you?