Hi, I wonder if anyone can answer a simple question.
Is it possible to write a program where for example: You write a simple "Hello World" program with a twist. The user can input an integer and "Hello World" is displayed as many times as the value entered?
This is without having to write: for(n==1) cout << "Hello World" << endl; around a million times as you are only covering one number at a time.
I hope this is clear for anyone to understand the question and appreciate all responses.
I've looked over the structure of a for loop. The only part I am struggling with is coming up with a shorter way of writing the program without having to create 1000's of lines the same (only changing the number that is equal to that entered by the user).
It has to be a for loop as that is what has been requested in a tutorial I am doing.
I think you're on the right line Aceix. It is literally something that says: "Enter a number: "
Then the output is "Hello World" x number entered.
I know it works 100%. Just one question and it's just to do with my understanding. In the loop the:
for(int i=0;i<x;++i)
How does it read the value and know to output "Hello World" that many times? When I read this, I would assume that if the value "i" is less than "x" then increment "i" and output "Hello, World" once only.
Thanks and here is my working code thanks to your help/writing it for me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
unsigned n = 0;
cout << "How many times will I output the sentence?";
cin >> n;
{
for(unsigned i=0; i<n; ++i)
cout << "Hello, World!" << endl;
}
return 0;
}
Scratch that last question. It is understood 100% now.
I have also wrote similar codes for "while" & "do" loops which are posted below for comment negative or otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
unsigned n;
unsigned i=1;
cout << "How many times will I output the sentence?";
cin >> n;
while (i <= n)
{
cout << "Hello, World!" << endl;
i++ ;
}
return 0;
}
and
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
unsigned n, i = 1;
cout << "Tell me how many times to output Hello World: " ;
cin >> n ;
do
{
cout << "Hello, World!" << endl ;
i++;
}
while( i <= n );
return 0;
}