Lesson 10: Program Iterations


E-mail this post



Remember me (?)



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



Today’s lecture is also examples mostly, but this time I’ll introduce you to iterations and you will see why these program lines are common in every programmer’s code. Just don’t be confused when you see i= i++ (this really bugged me when I was first introduced to world of programming). How the heck can i be equal to i+1 ? You have to think outside of the box this time, and forget regular math.




Program Iterations

Program iterations are used to process certain program’s block, multiple number of times. Number of repeats (iterations) can be, or don’t have to be previously known. We have following iterations that:

  • test condition before starting iteration (while, for)

  • test condition at the end (do-while)


Iterations that tests iteration condition at the beginning


Example:

Write your own program that will read given positive-whole numbers, until number zero is given. Then it will print which given number was the smallest. The program must ignore given negative numbers (given = keyboard inputted).

Warning: While searching for smallest (biggest) filed member or flow, we use following algorithm:

  1. first member in field is declared smallest and it’s value is assigned to temp variable, which presents current minimum.

  2. we search through other field members and if one of them is smaller then our current minimum, we update our temp variable to show new current minimum.

  3. after we processed the whole field, temp variable now stores the real minimum member of field.


Example:

flow: 5, 6, 3, 9, 4, 7, 2, -1, 5.






#include <stdio.h>

void main() {


int min, x = 0;

while(x <= 0){

printf("Input number : ");
scanf("%d", &x);
min = x; // we assume first given number is the smallest

}

while (x != 0) {

printf("Input number : ");

scanf("%d", &x);
if(x > 0 && x < min )
min = x;

}

printf("Smallest given number is: %d\n", min);

}



Alternative approach (to avoid double storing)



#include <stdio.h>

void main() {


int min=0, x=1;

// in first iteration x=1

while (x != 0) {


printf("Input number : ");
scanf("%d", &x); //after first iteration x becomes != 1
if (x > 0) {

if ((min==0) || (x < min)) min = x;

}
}

printf("Smallest given number is: %d\n", min);

}





Example:

Program reads positive-whole numbers until their sum reaches value bigger than approved range short int allows. Program also prints last valid sum.



#include <stdio.h>

void main() {


short int x, sum = 0, end = 0;

while (!end) {

printf("Input number : ");
scanf("%d", &x);

if ((signed short)(sum+x) >= sum) { //why cast?

sum += x;


} else {

end = 1;

}
}

printf("Sum: %d\n", sum);

}



Example of programs testing:

Input number : 30000
Input number : 10
Input number : 10000
Sum: 30010

Is the number of iterations in this program block previously known?



Example:

Program prints first 100 numbers that are dividable with 7:


#include <stdio.h>

void main() {


int i=0, n=0;

while (n < 100) {

if (i % 7 == 0) {

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

}

i++;

}
}




Example:

Program reads positive-whole number and calculates range of following numbers in this way:
  • if the given number is even, then divides it with 2

  • if the given number is odd, then multiplies it with 3 and adds 1
The procedure is repeated until given number becomes 1. Program prints current value in every step. Program also prints number of calculations above processed number.



#include <stdio.h>

void main() {


int number, nrSteps = 0;

printf("Give positive number:");
scanf("%d", &number);
while (number > 1) {

++ nrSteps;
if (number % 2){

number = number * 3 + 1;

}

else {

number /= 2;

}

printf ("In %d. step, number = %d \n", nrSteps, number);

}

printf ("All together %d steps. \n", nrSteps);

}




Give positive number: 9
In 1. step, number = 28
In 2. step, number = 14
In 3. step, number = 7
In 4. step, number = 22
In 5. step, number = 11
In 6. step, number = 34
In 7. step, number = 17
In 8. step, number = 52
In 9. step, number = 26
In 10. step, number = 13
In 11. step, number = 40
In 12. step, number = 20
In 13. step, number = 10
In 14. step, number = 5
In 15. step, number = 16
In 16. step, number = 8
In 17. step, number = 4
In 18. step, number = 2
In 19. step, number = 1
All together 19 steps.



Technorati Tags:
, , , , , ,



12 Responses to “Lesson 10: Program Iterations”

  1. Anonymous Broeisi 

    Wow... more than 24 hours without a new lesson... that's a new record :)

  2. Anonymous vurdlak 

    today is friday, had million things to do, but I added new version of c maniac (black on white) in my news category :)

  3. Anonymous Michał Kwiatkowski 

    "i= ++i" is not proper C. Program behaviour with this instruction is undefined. Google for "sequence point".

  4. Anonymous Dennis Ritchie 

    void main() is not legal C. I stopped reading at that point.

  5. Anonymous Pavel 

    good riddance, Dennis!

  6. Anonymous sami 

    why don't you complete your education before posting the tutorials for others to learn?
    though your teaching style is commendable, you are teaching some bad practices to the young minds.
    void main() and i = ++i; are both illegal in C.

  7. Anonymous Bob 

    Not only that but ANSI standard C requires a return! non here.

  8. Anonymous Pavel 

    This thing is very funny. What's the point of coming and posting here if you don't like the resource? Showing off your competence? These stupid details do not make a good or a bad programmer, be sure. All the more so if the mind is dead and stiff.

  9. Anonymous rjc 

    > This thing is very funny. What's the point of coming and posting here if you don't like the resource? Showing off your competence?

    Correct me if I'm wrong, but think that's what comments are for, right?
    Besides, this is rather constructive criticism. If the author doesn't care about it, that's his choice.
    I already said what I think about it. This tutorial is for beginners and the style of coding will be a big influence to them.

    rjc

  10. Anonymous vurdlak 

    All comments are welcome,even the bad ones. Please do understand that I am aware of main characteristic as returning value (int main) or returning nothing void main. I am also aware of return, break, continue commands...

    We will come to all of this, but for now simple (BUT PROPER, CORRECT and WORKING) examples are to be shown first.

    i=i++, is the right form, I appologise. This was only an example of something different than usual math. But notice, I never used it falsly in my code and lessons (just intro..sorry!)

  11. Anonymous Pavel 

    rjc, THIS is constructive. But giving unconditional orders and showing apparent indignation sound completely misplaced. Most of the times regardless of the subject .

  12. Anonymous mita 

    very intersting .here

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.