0
for(int t(0); t < 10;++t) { cout<<t<<endl;}

I'm just biginer in C++, and want to know how can I take the last elemnt of my "cout...."; in this case my laste element is 9

thx for help ;)

6 Answers6

1

You can extract int t from the for loop :

int t;  
for (t = 0; t < 10; ++t)  
{
    cout << t << endl;
}
diapir
  • 2,872
  • 1
  • 19
  • 26
1
int c = 0;
for(int t = 0; t<10; t++)
{
  c = t;
}
cout<<c;

This might be what you are looking for I am not sure I understand your question properly though.The variable c should hold the last element of t when the loop ends.

Treader
  • 11
  • 1
0
int t = 9;
cout << t << endl;

Now you have the last element, #9.

abelenky
  • 63,815
  • 23
  • 109
  • 159
0

ghagha, in C++ the ranges are run from 0 to n-1, in your example you have a range of 0 to < 10 hence 0 to 9, therefore your last element is 9. But as I said you can do any range as n-1 for the last element, provided that it follows normal conventions (it is possible to have a range from 1 to n if you code it that way)

GMasucci
  • 2,834
  • 22
  • 42
0

It is not clear what you want but in any case your loop contains a bug. Instead of

for(int t(0); t < 10;  t) { cout<<t<<endl;}

should be

for(int t(0); t < 10;  t++) { cout<<t<<endl;} 

that is variable t has to be incremented.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

One simple way -

int t = 0;
for (; t < 10; ++t)
   cout << t << ;

Tough the correct way to do it will be (one variable should not have two meanings, i.e 1. last element, 2. iterator context) -

int last_element;
for (int t = 0; t < 10; ++t;
{
    cout << t << ;
    last_element = t;
}
user1708860
  • 1,683
  • 13
  • 32