Do something with last value in loop in C++ -


Let's say I have another in the loop and if I am true in loop then print it with a space or comma And this is true for all the rest, but I want to do something else with the last few which is true. How do i do this (I = 0; i & lt; = somenum; i ++) for

  {if (i% 2! = 0) {cout & lt; & Lt; I; }}   

I want to understand the last value which follows the situation and do something else with it.

There are actually three ways to deal with this problem. I'm going to use what you want to do for the loop, 0 to 9 numbers divided by commas and spaces.

(1) Do the same thing to the loop every time, but modify your result after the loop is an example of doing this:

  #include   

(2) Exit your loop before your final repetition and handle the last case outside the loop:

  #include   

(3) In the special case, the last walk in your loop. This option is bad, and you probably want to do this in cases where you can not apply 1 or 2. The reason for this is bad because your conditional time will be executed in the loop, and it will only be true once.

  #include & lt; Iostream & gt; Int main (int, char **) {std :: stringstream ss; For (int i = 0; i <10; ++ i) {if (i == 9) {std :: cout & lt; & Lt; I; break; } Std :: cout & lt; & Lt; I & lt; & Lt; ","; }}   

In most cases Option 2 is the best bet for your performance, but sometimes the Option 1 provides a cleaner code that can be valuable.

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -