Programming C : Posts 6 – Loop in C

1. For example, the opening

The print out your name so simple is not. A very simple programs written.

#include <stdio.h>

int main()
{
    printf("Nguyen Van Quan\n");
    return 0;
}

Ok. So now I want you to print out 10 times your name?

#include <stdio.h>

int main()
{
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    printf("Nguyen Van Quan\n");
    return 0;
}

Pretty simple, just copy the 10 printf line is finished. But if not 10, that is 1000 or more? Obviously copying is not feasible.

In reality, the software will be work to be repeated many times as in the example above. Or like your software to print a list of employees, every employee information (content) different but the structure is very similar. Or simply that you surf facebook and see stories from your friends, the news was not identical in content, but the structure is very similar.

To accomplish the tasks that need repeated such, we will use the loop structure consisting for, while, do-while. This lesson we will learn about the loop for.

We will revise the example in 10 once named you as follows:

#include <stdio.h>

int main()
{
    int i;
    for (i = 1; i <= 10; i++)
    {
        printf("Nguyen Van Quan\n");
    }
    return 0;
}

As the code above, I've used loop to do the job in his name 10 time, with 1000 simple times when I also replaced some 10 a number 1000 (you can try). Looking at the code you can also visualize the basic things we do.

2. Loop structure

Loop

Syntax, flowcharts, and the behavior of the loop

Looking at the picture above we see the loop has a syntax and how it works is quite clear and easy to understand. However you should note:

  • After the command for no semicolon.
  • 3 Expressions of loops separated by semicolons (;), expressions may be absent 1,2 or both 3 but this must be raised semicolon.
  • Expressions 1 always be calculated only once when dialed for.
  • Expressions 2, 3 and for possible relatives repeatedly.
  • Expressions 1, 2, 3 must be separated by a semicolon ( ; ), expressions may be absent 1,2 or both 3 but this must be raised semicolon.
  • If the expression 2 no, loop is considered to be always right. Want to escape the loop in order to take a break, goto hoặc return.
  • For each expression can be written as a series of human expressions separated by commas. Then the child is determined expression from left to right. As of right and wrong in the expression of the sequence first expression 2 is determined by the final expression.
  • In the body for (block command) may contain one or more other control structures, another loop.
  • When having a break statement, deepest loop structure will exit.
  • In the body there for thedung goto exit the loop to the desired location.
  • In the body can use for return to return to a certain function.
  • In the body can use for the command continue to move to the top of the loop (skip the remaining statements in the body).

Return code examples:

#include <stdio.h>

int main()
{
    int i;
    for (i = 1; i <= 10; i++)
    {
        printf("Nguyen Van Quan\n");
    }
    return 0;
}

The process works as follows:

  • Step 1: Running expressions 1 ie assign i = 1.
  • Step 2: Running expressions 2 ie check i <= 10 not. Do i = 1 Should this right => Run command block that is printed name.
  • Step 3: Running expressions 3 ie an increase of i up 1 unit. Now i = 2.
  • Step 4: Back expression 2. Check i < 10 not. Do i = 2 should still correct => Run command block, ie in the name.
  • Step 5: Running expressions 3 ie increase i up 1. Now i = 3.
  • Step 6. Back expression 2,…
  • Step….
  • step x: Running expressions 3, i increase up 1. Now i = 10.
  • Step x + 1: Back expression 2 ie check i <= 10. Remains true => Run command block print name.
  • Step x + 2: Running expressions 3, i increase up 1. Now i = 11.
  • Step x + 3: Back expression 2, check i <=10. Now it wrong because i was 11 => Exit loop. Next perform peer command loop (return statement 0 underneath).

Ok. Now you have the basic understanding of loop. Continue to do a few more examples.

Example 1:

Write a program that prints out 15 times your name, together with the following order:

  1. Nguyen Van Quan
  2. Nguyen Van Quan
  3. Nguyen Van Quan
  4. ….

Hum… how to derive the number ascending? You can look at the process of running the steps of the for loop? We have 1 i turn on ascending… So we will take advantage of it.

#include <stdio.h>

int main()
{
    int i;
    for (i = 1; i <= 10; i++)
    {
        printf("%d.Nguyen Van Quan\n", i);
    }
    return 0;
}

Example 2:

Please print out positive numbers even from 1 to 20 on top of 1 current, separated by spaces.

Just for i running from 1 to 20 and we will check the printed number is even,. To check the parity, we recall the division took balances. If i divide 2 residual 0 shall be even.

#include <stdio.h>

int main()
{
    int i;
    for (i = 1; i <= 20; i++)
    {
        if( i % 2 == 0) 
        {
            printf("%d ", i);
        }
    }
    return 0;
}

Ok. But I want you to think a little more before looking down and code hints. How could we not use test if even numbers and still do to this post?

Remember the expression of for not fixed, we can change it. And change the way increase i. We give i start 2 and each increase, the rise 2 unit.

#include <stdio.h>

int main()
{
    int i;
    for (i = 2; i <= 20; i = i + 2)
    {
        printf("%d ", i);
    }
    return 0;
}

This code clearly better than the previous time code. Above we increase i up 2 command unit i = i + 2.
This is an assignment i + 2 for i, not compare i and i command + 2.

Example 3:

Summed even integer from 1 to 20.

#include <stdio.h>

int main()
{
    int i;
    int s = 0;
    for (i = 2; i <= 20; i = i + 2)
    {
        s = s + i;
    }

    printf("S = %d\n", s);

    return 0;
}

Notice in the above code, we declare 1 variable s (stands sum) to save total. Every time i increases, we accrued to the s command s = s + in.

Example 4:

Sum of odd numbers from 1 to 20 but until the total exceeds 15 then stop.

Here we are summing the odd numbers, like the even numbers only, however when the total is greater than 15 then we will stop, plus no more.

#include <stdio.h>

int main()
{
    int i;
    int s = 0;
    for (i = 1; i <= 20; i = i + 2)
    {
        if(s <= 15)
        {
            s = s + i;
        }
    }

    printf("S = %d\n", s);

    return 0;
}

Simply check when s still less than or equal 15 then we added. We will have s = 1 + 3 + 5 + 7 = 16.

However if you notice, when s> 15, we are not added to the loop's but still running until i> 20. That is going to run to the iteration i = 9, 11, 13, 15, 17, 19. Therefore it makes waste, superfluous and make programs run longer. So we should break the loop at the time the command is done when i = 7. To do so can be used break, or goto, but you should use break recommend for simplicity and safety.

#include <stdio.h>

int main()
{
    int i;
    int s = 0;
    for (i = 1; i <= 20; i = i + 2)
    {
        if(s <= 15)
        {
            s = s + i;
        } else 
        {
            break;
        }
    }

    printf("S = %d\n", s);

    return 0;
}

Example 5

Enter integer n, sum of even numbers entered.

#include <stdio.h>

int main()
{
    int i, n, x;
    int s = 0;

    printf("Enter n = ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        printf("Enter number %d : ", i);
        scanf("%d", &x);

        if(x % 2 != 0) continue;

        s = s + x;
    }

    printf("S = %d\n", s);

    return 0;
}

In this example, I instruct you how to use the command continue. This command does not escape capital effects loop but is returning to the expression 3 without orders behind it. Here if x does not even enter the command skip Incremental command s which runs to increase i right.

Exercise:

  1. Write a program to print out the number n and the number n is estimated that.
  2. Write test program 1 there is prime number not? Prime number is a positive integer only 2 Convention is 1 and itself. Example No. 2, 3, 5, …
  3. Write test program 1 there is the perfect number does not? Perfect number is a positive integer equal the sum of the estimated 2 times it. Examples of 6 the Convention 1, 2, 3, 6 and total 1 + 2 + 3 + 6 = 12 (equal 2 time 6).
  4. Write a program to calculate S = 1 + 1/2 + 1/3 + … + 1/N
  5. Write a program that calculates the squares of the odd numbers from 1 to n.
  6. Write a program to calculate n! know n! = 1.2.3.4…n
  7. Write a program that counts the n th Fibonacci sequence known sequence f(n) = f(A-1) + f(n-2), n > 2 and f(1) = 1, f(2) = 1.
  8. Write a program in length, the width of the rectangle. Draw a rectangle asterisk (*) size entered.