Answer to Question #144672 in C for manish thakur

Question #144672
Sometimes ,we want some part
of our code to be executed more than
once. We can repeat the code in our
program. For example, we need to
display our name for a hundred or
more times it is not practical to write
the same code. Which concept will
be used? Explain it with the help of
suitable examples.
1
Expert's answer
2020-11-16T10:04:26-0500

If we want to execute some part of the code multiple times, we can use cyclic structures.

There are three types of cycles:

  • for(){}
  • while(){}
  • do {} while().

They can be replaced by each other, but their purposes are slightly different.


Cycle for() can be used to iterate over some structure or do smth for fixed amount of times.

The skeleton: for(init val; condition; change),

where 

  • init val: initialization of a value, that will be checked in condition
  • condition: is checked every iteration, and cycle breaks when it becomes false,
  • change: changes some variable, usually that is checked in condition, to make it false sometimes


Examples:

for (int i = 0; i < 10; i++)
    printf("Name\n");

int a[10];
for (int i = 0; i < 10; i++)
    printf("%d ", a[i]);


Cycle while() is a simplified for(), that contains only condition

int i = 0;
while (i < 10) {
    printf("Name\n");
    i++;
}

is the same as

for (int i = 0; i < 10; i++) {
    printf("Name\n");
}

Sometimes it can be useful and simplify your code.

For example, we can count a sum of digits in a number:

int n, sum = 0;
scanf("%d", &n);
while (n != 0) {
    sum += n % 10;
    n /= 10;
}


Cycle do {} while() is the same as while(), but its body will be executed at least time.

So, if we write while():

int i = 10;
while (i < 10) {
    printf("Name\n");
    i++;
}

nothing will be printed, but if rewritten with do {} while():

int i = 10;
do {
    printf("Name\n");
    i++;
}
while (i < 10);

the cycle executes 1 time, though the condition is false.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Manish
16.11.20, 18:31

Thankyou very much , it helped me a lot .i hope that in future you will help us in the same manner

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS