in this program we are supposed to enter numbers greater than or equal to 0. if we enter a number lesser than 0, the program should end and then display the total amount of positive numbers that i entered.
#include <iostream>
usingnamespace std;
int main ()
{
int number=0,total=0;
cout<<"Type a number : ";
cin>>number;
while(number>=0)
{
cout<<"Type a number : ";
cin>>number;
total=number+1;
}
cout<<total;
return 0;
}
something is still not right. let me rephrase what i mentioned above. if i enter any 5 positive numbers and after that if i enter -1, the program should display 5. similarly if i enter any 15 positive numbers the program should display 15
You still have work to do. Providing cin>> with a numeric string will not automatically convert it to its intended binary value. Typing "-1" will not give you a negative integer as it is still in string form. Instead you get a positive value of 0x2D31. I should also mention entering any more than 8 digits will likely cause this code to crash due to a memory access violation.
if i enter any 5 positive numbers and after that if i enter -1, the program should display 5. similarly if i enter any 15 positive numbers the program should display 15
#include <iostream>
int main ()
{
int number = 0;
int total = 0;
while(true)
{
std::cout<<"Type a number : ";
std::cin>>number;
if (number < 0)
{
break;
}
total++;
}
std::cout << "\nThe total is: " << total << std::endl;
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int total = 0;
// number should be a char array
char number[24];
while (true)
{
cout << "Type a number : ";
cin >> number;
//check for negative number
if (number[0] == '-')
break;
total++;
}
cout << total;
return 0;
#include <iostream>
usingnamespace std;
int main ()
{
int number=0,total=0;
do
{
cout<<"Type a number : ";
cin>>number;
if (number>=0)
++total;
} while(number>=0)
cout << total;
return 0;
}
I stand corrected. Jaybob66's code will work, though I should point out that problems may occur if anything other than a number is given. This code is a little bulkier, but is more stable.
I appreciate you guys trying to help, but the thing is, I started C++ less than a week ago. I am only aware of the following functions;
1. If-Else
2. Nested if
3. While loop
4. For loop
I only know the basics of these functions. And my teacher didn't teach us the "Do-While Loop".
My teacher did not tell us anything about using "std" anywhere else other than "using namespace std;".
So, can you guys please make it simple? Thank you!