Hello.I am trying to make this program work. Because I am learning by myself c++ my only option to ask question witch I don't know the answer is on the internet.The exercise sounds like this:Reads an integer n with at most four digits. Display all the natural numbers in ascending order as long as their sum exceeds n.And if you are trying to type a character , you type again.
This is my code so far.Can someone point me to the right direction? I don't want code, I want to figure this by myself. I don't know where is the mistake.
#include <iostream>
#include <conio.h>
usingnamespace std;
int main(){
int number;
int sum = 0;
cout << "Reads an integer n with at most four digits. Display all the natural numbers" << "\n"
<< " in ascending order as long as their sum exceeds n." << endl;
while ( (number != 0) & (number < 0) & (number > 9999) )
{
cout << "Write a pozitive number and smaller than 9999 \n";
cin >> number;
while (!(cin >> number))
{
cin.clear();
cout << '\a';
while (cin.get() != '\a')
continue;
cout << "Write a pozitive number and smaller than 9999 \n";
for ( int i = 0; i < number; i++ )
if ( (i%2 == 0) & (sum < number) )
{
sum = sum + i; // sum += i;
cout << sum << " " << endl;
}
}
} //(number < 0) || (number > 9999)
_getch();
return 0;
}
3 problems with outer while loop while ( (number != 0) & (number < 0) & (number > 9999) )
Using number before you read it in.
You are using & which is bitwise and, you want && which is logical and.
Also how can number be less than 0 and greater than 9999 at the same time, loop will never execute
your reading in number twice.
1 2 3
cin >> number;
while (!(cin >> number))
{
No idea what you are doing here
1 2 3 4
cin.clear();
cout << '\a';
while (cin.get() != '\a')
continue;
Now the program looks like this. But I can't figure how to make it work.I forgot to mention above : Display all the natural even number in ascending order as long as their sum exceeds n.
1 2 3 4 5 6 7 8 9 10 11 12 13
do {
cout << "Write a pozitive number and smaller than 9999, 0 to exit.";
cin >> number;
cout << endl;
if ((number > 1) && (number < 9999)){
for ( int i = 0; i < number; i++ )
if ( (i%2 == 0) && (sum < number) ){
sum = sum + i;
cout << sum << " ";
}
cout << endl;
}
} while (number != 0);
Thank you for the reply. I really appreciate it.
Here
1 2 3 4
cin.clear();
cout << '\a';
while (cin.get() != '\a')
continue;
i was trying to make something like this : if you type a character instead of a number it makes a sound and you type again
#include <iostream>
#include <conio.h>
usingnamespace std;
int main(){
int number, sum = 0, even = 0;
cout << "Enter a number: " << endl;
cin >> number;
while (sum < number)
{
cout << even << " ";
even = even + 2; // even += 2
sum = sum + even; // sum += even
}
_getch();
return 0;
}
Thank you.