Ok so i have trouble with looping with while and for statments
heres the questions: 1. Write a program that gets a positive integer from the user and prints all the numbers from one to that integer. If the inputted number is zero or negative, then the program will print an error and quit.

I dont have much, but this is all i have:

#include <iostream>

using namespace std;

int main()
{
 int num=1, i;

 cout<<"please enter a number"<<endl;
 cin>>i>>

 while num<i;

 cout<< num+1<<;




return 0;

}

Can someone please to me what to add and the correct format

Recommended Answers

All 9 Replies

Wow,

while (true) {
cin >> number;
if (num > 0) break;
else {cout << "Incorrect";}
}
for (int i = 0; i < number; i++) {
cout << i << "\n";

I wrote it in about 30 seconds...

This took a bit more than 30 secs but it isn't full of errors and uses whitespace so you can actually see what is going on.

#include <iostream>

using namespace std;

int main()
{
	int num;

	cout << "please enter a number" << endl;
	cin >> num;
	if( num > 0 )
	{
		for( int i = 0; i < i; i++ )
		{
			cout << i << endl;
		}
	}
	else
	{
		cout << "number is less than or equal to 0" << endl;
	}

	return 0;
}

The point wasn't to do the program for the person asking, though.

commented: True +16

I don't see the point in him posting that at all then. He is just showing someone, that doesn't know what they are doing, code that doesn't work.

@Adam Ma
I would highly recommend you go over this tutoral. I learned C++ from here and I use the reference section all the time.

to line 11: after entering the number on the upper part your going to apply a condition.

And to add to the above, here's a tut specified on loops.

You also need to pay more attention to your code-syntax. If you miss just one semicolon, your program won't compile. C++ is very unforgiven :)

I wrote it in about 30 seconds...

That's nice. :icon_wink:

in using while looping statement your need the following the initialization,logical condition,incrementation or decrementation.

#include <iostream>
 
using namespace std;
 
int main()
{
	int num;
 
	cout << "please enter a number" << endl;
	cin >> num;
	if( num > 0 )
	{
		for(num=num;num>0;num--)
		{
			cout <<num<<" "<<"positive"<<endl;
		}
	}
	else
	{
		cout<<num<<" "<<"negative"<<endl;
	//	cout << "number is greater  than or equal to 0" << endl;
	}
 
	return 0;
}

just try run this program... and gathered information,

just game me idea what is the possible output statement of your program,, as i run your program there a lot of errors..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.