Jun 7, 2012 at 11:20am UTC
how to write a C++ program to print out hello world ten times using a for loop
Jun 7, 2012 at 11:23am UTC
You can do it like this:
for (int i = 0; i < 10; i++){
cout << "hello world" << endl;
}
Last edited on Jun 7, 2012 at 11:23am UTC
Jun 7, 2012 at 6:30pm UTC
Or don't impress your professor and get sillier still!
1 2 3 4 5 6 7 8 9 10 11 12
for (int i = 0; i < 1; i++){
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
cout << "hello world" << endl;
}
Last edited on Jun 7, 2012 at 6:30pm UTC
Jun 7, 2012 at 6:37pm UTC
I recommend you do it this way, actually..
Except your professor may kick you out of the class.
1 2 3 4 5 6 7 8 9 10
bool tenTimes = true ;
int count = 1;
do {
cout << "Hello World!" ;
if (count == 10) {
tenTimes = true ;
}
count++;
}while (tenTimes == false );
Last edited on Jun 7, 2012 at 6:39pm UTC
Jun 7, 2012 at 7:14pm UTC
wait which is the best way?
Jun 7, 2012 at 8:59pm UTC
We're just messing around since this is obviously your homework and we're not just going to give you the answer. It's very simple though and you have more than enough hints given to you. Look at the tutorial linked by twistermonkey and try to put all the pieces together. Then try to compile and run it. If it works, you're done. There is really no best way to print the same thing ten times. It's too trivial to optimize.
Jun 7, 2012 at 9:27pm UTC
@Cubbi,
Your variant has a big disadvantage! Too many headers!:)
Jun 7, 2012 at 9:58pm UTC
Look ma, no loops!
1 2 3 4 5 6 7
#include <iostream>
int main(int _, char *__[])
{
_++<0xA?0x0>=!main(_,__):std::cout<<std::endl;
std::cout << "Hello, World!\n" ;
}
http://ideone.com/9hH7S
Edit: I keep finding things to tweak.
Last edited on Jun 7, 2012 at 10:08pm UTC
Jun 7, 2012 at 10:11pm UTC
@Catfish2
$5.2.2[expr.call]/9 says "Recursive calls are permitted, except to the function named main"
Fun idea, though.
Last edited on Jun 7, 2012 at 10:12pm UTC
Jun 7, 2012 at 10:13pm UTC
@Catfish2
In C++ the main may not call itself. It is suppressed by the C++ standard!
Jun 7, 2012 at 11:24pm UTC
Thanks killjoys, it has no soul anymore!
But at least it's still convoluted and hard to understand.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <functional>
#include <iostream>
int main()
{
std::function<int (int )> hello = [&](int i)->int {
if (--i != 0) hello(i);
std::cout << "Hello, World!" << std::endl;
return 0;
};
return hello(10);
}
http://ideone.com/OkPMR
Last edited on Jun 7, 2012 at 11:26pm UTC