とらりもんHOME  Index  Search  Changes  Login

とらりもん - C intro 2. for satement Diff

  • Added parts are displayed like this.
  • Deleted parts are displayed like this.

Next, let's master a "repetitive processing". To repeat a similar process many times is called "repetitive processing" or "loop processing". This is an indispensable process in jobs that handle multiple data (such as numerical simulation, image analysis, etc.).

In C language, when using repetitive processing, we often use "{{fontc("for statement", red)}}" described below.

For example, the following program is the same program that displays sentence "Hello!" as we made last time. Let's typing in, compile and run. The leftmost line number is for the explanation to follow and you do not have to enter it. Replace lines 2 and 3 with today's date and your name:

     1. /* hello.c */
     2. /* 2017/02/18 K. Nasahara */
     3. # include <stdio.h>
     4. main()
     5. {printf("Hello!\n");
     6. }

Note: Do not type the number at the head of each line.

$ gcc hello.c -o hello
$ ./hello
Hello!
$

Now we want to make your computer say Hello! ten times:

     1. /* hello.c */
     2. /* 2017/02/18 K. Nasahara */
     3. # include <stdio.h>
     4. main()
     5. {int i;
     6. for (i=1; i<=10; i++)
     7.    {printf("Hello!\n");
     8.    }
     9. }

Note: Do not type the number at the head of each line.

$ gcc hello.c -o hello
$ ./hello Hello!
Hello!
Hello!
...
Hello!
$

Here, a new integer variable "i" is defined in the fifth line. In the sentence "for" and after that, it increments "i" one by one starting from 1, as long as "i" is less than or equal to 10 and repeats the command in lines 7 (and 8; enclosed by{}). In other words, "i" is like a counter that counts the number of repetition.

In the example above, it just repeated exactly the same way to display "Hello!" every time. However, you can repeat something which looks alike but slightly different. As an example, the following source code is a program that adds integers from 1 to 10. Create this file with the file name repeat.c, compile it, and execute it. Note that the leftmost line numbers are for the comments later and you do not have to enter them. You do not need to enter comments starting with // on the right end:

     1. /* repeat.c */
     2. /* 2017/02/18 K. Nasahara */
     3. /* sum of 1+2+...+10 */
     4. # include <stdio.h>
     5. main()
     6. {
     7. int i;
     8. int s=0;              // variable to store the result. initial value should be zero.
     9. for (i=1; i<=10; i++) // command for repeat (loop).
    10.    {s=s+i;              // i increases from 1 to 10. We add it to s.
    11.     printf("%d %d\n", i, s); // display results at each step
    12.    }                    // end of the loop
    13. }

Note: Do not type the number at the head of each line.

Let's focus on the line 9. First, it puts 1 in variable i (i = 1). Then, as long as i is less than or equal to 10 (i <= 10), it repeat running the lines 10 and 11 and add 1 to i (i ++) each time. In this way, the for statement is used in a style as "for (initial condition: condition to repeat; process to be executed for each iteration)". "i ++" may be written as "i = i + 1". The line 10 to the line 11 describes the contents of the processing repeated by the for statement. Surround it with {}.

'''Exercise 2-1''': Delete "{" in line 10 and "}" in line and then compile and run it. What happens? Why?

Note: You can make your work easier by using two terminals simultaneously: one for editting a source code and another one for compile and run.

'''Exercise 2-2''': Modify this program so that i calculates sum of all integers from 1 to 100.

'''Exercise 2-3''': Make a program which calculates sum of squares of all integers from 1 to 10. (Hint: square of i is written by i*i. Simple is the best!)

'''Exercise 2-4''': Make a program which calculates sum of all the odd numbers from 1 to 99. (Hint: increment i in the for statement by "i=i+2".)

'''Exercise 2-5''': Make a program which displays 9 to 1 in a descending order. (Hint: Initial value in the for statement is "i=9". Condition should be "0<=i". Increment should be "i=i-1" which is actually a decrement.)

'''Exercise 2-6''': Make a program which displays a table like this (square, cubic, fourth power of integers 0 to 9). (Hint: In order to align the column, you can use "tab" which is described as "\t" in the printf statement)

        0       0       0       0
        1       1       1       1
        2       4       8       16
        3       9       27      81
        4       16      64      256
        5       25      125     625
        6       36      216     1296
        7       49      343     2401
        8       64      512     4096
        9       81      729     6561

Now let's try to output the result of the previous exercise to a file (not to a display):

$ gcc exercise2-6.c -o exercise2-6
$ ./exercise2-6 > exercise2-6.txt
$ cat exercise2-6.txt

Where, exercise2-6.txt is the name of a file for output. You can decide it's name as you want.

This technique is "redirection" which you must have learned in Linux lesson.

'''Exercise 2-7''': Make a program which reads an integer from a keyboard and display sum of the all the integers from 1 to that number.

'''Exercise 2-8''': Make a program which reads an integer from a keyboard and display its square, cubic, and 4th power.

'''Exercise 2-9''': Make a program which reads two integers x, y from a keyboard and display x^y.  (Hint: use for loop and multiply y times. Declare an integer z and initialize it as z=1. Repeat y times of z=z*x)

'''Exercise 2-10''': Make a program which reads an integer from a keyboard and display n!=1*2*...*n.


[Go back to [[C language introduction]]]