|
|
|
|
|||
|
We have to calculate the sum of first 1000
integers by taking a variable sum of type int. It is a good programming practice to initialize the variable
before using it. Here, we initialize the variable sum with zero. int sum = 0; Now we get the first integer i.e. 1. We add
this to the sum (sum becomes 0
+ 1 = 1). Now get the next integer which can be obtained by adding 1 to the
previous integer i.e. 2 and add it to the sum
(sum
becomes 1 + 2 = 3). Get the next integer by adding 1 to the previous integer
and add it to the sum (sum becomes 3
+ 3 = 6) and so on. This way, we get
the next integer by adding 1 to the previous integer and the new integer to
the sum. It is obvious that we are repeating this procedure again and again
i.e. adding 1 to the previous integer and add this new integer to the sum. So
we need some repetition structure in the programming language. There are many
looping constructs in C Language. The repetition structure we are discussing
in this lecture is 'while
loop
structure'. ‘while’ is also a key word of 'C' so it cannot be used as a variable
name. While means, 'do it until the condition is
true'. The use of while construct can be helpful in repeating a set of
instructions under some condition. We can also use curly braces with while just like we used with if. If we omit to use
the braces with while construct, then only
one statement after while will be repeatedly executed. For good programming
practices, always use braces with while irrespective of the
number of statements in while block. The code will also be indented
inside the while block as Indentation makes the code easy to
understand. |
|||||
|
|
Previous |
TOC |
Next |
||