Lesson 11: Infinite and Finite Loops


E-mail this post



Remember me (?)



All personal information that you provide here will be governed by the Privacy Policy of Blogger.com. More...



Seems to me that submitting new lessons every two days became a rutine lately. Let’s hope it stays that way. Today I posted new lesson which will put some light on programming loops - you surely have heard about those. So from now on, when you watch Futurama and hear Beneder blabring something about being stuck in an infinite loop, you’ll understand his problem in details: from one – to zero. Hehe, let’s start...


Iteration with previously known number of repeats.


Syntax:

for (expression1; expression2; expression3) {
.

.
.
}



  • expression1 is an expression which will be executed only once, before entering into the first iteration. It’s most commonly used for counters initialization. If more then one expression is needed in this field, they are separated by comma.

  • expression2 is calculated as logical condition (0 - false, !=0 - true), and the iteration is executed number of times expression2 is true. Testing of condition is done before any iteration is processed.

  • expression3 is executed after each iteration (executed loop). It’s most common use is to increase counter’s value. If more then one expression is needed to be executed, they are separated by comma.

  • either one of expressions (expression1; expression2; expression3) can be left out. If expression 2 is left out, loop is executed as if logical value of the expression were TRUE.



Common use:

for (i = start; i <= end; i = i + k)  {
.

.
.
}




Example of “for” loop with 2 counters:


for (hi = 100, lo = 0; hi >= lo; hi--, lo++) {
.

.
.
}




Example:


Write your own program that will calculate arithmetic middle of n given numbers.


#include <stdio.h>

void main() {


int i, n, sum, x;

float arit_midd;

printf("For how many numbers do you wish to calc. their arithmetic middle : ");
scanf("%d", &n );

sum = 0;
for(i=0; i<n; i++) {

printf("Give %d. number : ", i);

scanf("%d", &x);
sum += x;

}


arit_midd = (float) sum / n;

printf("Arithmetic middle of scanned numbers is %f\n", arit_midd);

}




Example:

Write your own program which will print real numbers from 0 till n, with step of 0.1


#include <stdio.h>

void main() {


int n;

float i;

printf("Until which number do you wish report to be printed on screen :");
scanf("%d", &n );

for( i=0; i<=n; i=i+0.1 ) {

printf("%f\n",i);

}
}




Example:

Write your own program which will print numbers dividable with 7, 13 and 19, and lower than given number n. Numbers must be printed from biggest to the lowest one.


#include <stdio.h>

void main() {

int i, n;

printf("Give number n : ");
scanf("%d", &n );

for( i=n; i > 0; i-- ) {

if ( i % 7 == 0 ) || ( i % 13 == 0 ) || (i % 19 == 0) {


printf(" %d \n", i);

}
}
}



Warning:



for(;;); // infinite loop

or

for(;;){

//block of orders


}



Block of orders inside the body of loop is executed infinite number of times if that block doesn’t consist of: breaking order (break), order for escaping the function (return), program finish function call (exit) or goto order.



Common Mistakes:






Iteration (loop) which tests condition at the end.

Syntax:


do {
.

.
.
} while (expression);


  • loop is executed while condition is true, for example this is different in Pascal, where loop is executed until expression becomes true (means it keeps executing while condition is false)

  • loop will be executed minimum once (first test of condition comes after first run through the loop)


Example in C:


do {
.

.
.
} while (x < y);



Same example in Pascal:

repeat
.

.
.
until ( x >= y )




Example


Write your own program that reads numbers from interval [-100, 100] or [800, 1000]. Program has to print how much of these numbers were positive, how much of them were negative and how much times 0 encountered.

Program has to be written using “do – while” loop.


#include <stdio.h>

void main(){


int number;

int nrPositive=0, nrNegative=0, nrZero=0;
printf("Give in numbers: ");

do {

scanf("%d", &number);

if (number >=-100 && number <=100 || number >=800 && number <=1000) {

if (!number) nrZero ++;

else if (number >0) nrPositive ++;
else nrNegative ++;

}


}while (number >=-100 && number <=100 || number >=800 && number <=1000);


printf("Number of positive number %d, number of negative numbers %d, number of
zeroes %d\n", nrPositive, nrNegative, nrZero);


}





Example

Following program block:

k=0;
i=7;

lab:
k=k+i*2;
i=i-2;
printf ("%d\n", k);
if (i >= -7) goto lab;


should be replaced with following loop:

  1. Loop that tests condition at start

  2. Loop that tests condition at the end

  3. Loop that has previously known number of repeats


Solved:

1.)

k=0;

i=7;

while (i>=-7) {

k=k+i*2;

i=i-2;
printf ("%d\n", k);
}


2.)

k=0;
i=7;
do {

k=k+i*2;

i=i-2;
printf ("%d\n", k);

} while(i >= -7);



3.)

for (i = 7, k = 0; i >= -7; i-=2){

k = k + i * 2;

printf ("%d\n", k);

}




Warning: if it’s initialized that i < -7, 1. and 3. loop won’t be executed neither once, but 2. loop will be executed once.

Advantage of “for” loop: it’s starting counter’s initialization, testing of condition and counters step, all are placed in one place in programmer’s code. This can be really practical.



Technorati Tags:
, , , , , ,




1 Responses to “Lesson 11: Infinite and Finite Loops”

  1. Anonymous Mortis 

    "loop is executed while condition is true, for example this is different in Pascal, where loop is executed until expression becomes true (means it keeps executing while condition is false)"

    About Pascal, this is not entirely true, you are reffering to a Pascal DO LOOP UNTIL construction. It is the until statement that makes the difference, meaning it will continue executing the block until the UNTIL expression evaluates to true.

Leave a Reply

      Convert to boldConvert to italicConvert to link

 


German Flag Spanish Flag French Flag Italian Flag Portuguese Flag Japanese Flag Korean Flag Chinese Flag British Flag


This Website is optimized for Firefox. Users browsing with Internet Explorer may encounter problems while viewing pages.


C++ Maniac



Learn C



Additional



#include



Learn Converting



Appendix


Links


Previous posts




Daily Lessons for programming in Visual Studio, using C code.