Abdur Rahim
Abdur Rahim

Reputation: 19

don't want to check a condition for 1st time?

I know that if I don't want to check a condition in first iterate of a loop, I have to give a condition that will ignore first time iterate.

For example:

for(i=0;i<n;i++){scan(......) if(i!=0 &&......){};}

But I want to know that is there any help in C/C++ language that the condition will be ignored the first time automatically?

Upvotes: 1

Views: 1835

Answers (3)

Bharath Kumar
Bharath Kumar

Reputation: 541

Do-while loop is the way to go! It executes your instructions first and then check trueness of the condition in order to loop.

do {
//your instructions
} while(condition ) 

For details refer https://en.cppreference.com/w/cpp/language/do

Upvotes: 0

Sudip Bhattarai
Sudip Bhattarai

Reputation: 1154

do-while loop is there for this purpose.

int i=0;
do{
   // what you want to do
   i++;
}while(i<10);

This loop will execute at least once at all conditions.

Edit

In your case, it's better take one input before the loop starts or you could also use if statement to check for first loop.

last_input=get_input();
for(int i=0;i<10;i++){
    new_input=get_input();
    // do what you want to do with them.
    last_input=new_input;
}   

or

last_input=null;
for(int i=0;i<10;i++){
   new_input=get_input();

   if(i>0){
      // do what you want to do with them.    
   }
   last_input=new_input
}

Upvotes: 4

Syed Khizaruddin
Syed Khizaruddin

Reputation: 435

use do-while loop it comes handy for your case

do{

// statement..

}while(condition);`

this will work.

the statement will execute first then the condition will be checked

so in your case the first iteration will be executed then it will check the condition

see this for more explaination

Upvotes: 2

Related Questions