Hi all,
How to write a c/c++ program to execute limited number of times.
if anybody know plz give reply.
thanks
If you mean to loop a specific chunk of code within the program X
number of times, you can use a FOR loop or a WHILE loop
FOR loop:
===================
int n; // my counter variable.
..
..
..
// Executes the code inside the loop 4 times.
for (n=0; n < 4; n++)
{
[your code goes here]
}
WHILE LOOP:
-loops so long as the condition in the brackets (n > 0) is true.
======================
int n=4;
while (n > 0)
{
[your code goes here]
n--;
};
Do WHILE LOOP
-A variation of the While loop:
==================================
int n=4;
do
{
[your code goes here]
n--;
}
while (n > 0);
With a DO-WHILE, the condition test isn't done until it's gone through
the code, so no matter what happens, the stuff inside the DO-WHILE
loop will run at least once. Even if the condition is totally false
to begin with. With the WHILE loop, if the condition is false, the
test happens at the beginning and if the condition is false, it will
skip over the code in the loop and it will never be run.
Try it yourself by setting n=0 using the examples shown above.
---------------------------------------------------------------------------
If you mean to limit the number of times that the user may run your
program, that's more of a program design thing than a language thing.
I'd imagine you'd have to use file IO or some feature of the OS to
store a counter value. Load up the old value each time it's run, and
increment the file value at some point during the program's run (at
start, after the initial check, or just before exit). It'd be pretty
easy to defeat, unless you disguised the way it was stored in some
way. All of this stuff is somewhat off topic and a bit more than I'd
like to think about at this early hour though.