An essential tool in programming is iteration. We must often repeat an operation a set number of times, or until a certain condition is reached. The first loop we’ll look at is called the while-loop.


Inside the brackets, we have some condition that is re-evaluated at the end of each cycle of the loop, if this condition is evaluated to true, the entire body of the loop is executed, again reevaluating the condition after each cycle until the condition becomes false.
For example, write some code to ask a user to enter an integer and print out a sequence of integers from 0 to the user input.

int userIn;
int Seq = 0;

scanf("%d", &userIn);

while(Seq != userIn)
    printf("%d, ", Seq);

This code first takes UserIn as input. Now inside the loop we need to print all the digits from 0 up to userIn. The easiest way to do this is have a counter start at 0 and increment it until it’s equal to userIn, printing it out before each increment.

For a more challenging problem, write code that continuously takes input from a user until the user enters 0. The program then outputs the largest number entered.
Hint: save each number entered, then compare to the next input and always keep the largest one.

int userIn;
int Largest = 0;

scanf("%d", &userIn);

    scanf("%d", &userIn);
    if(userIn > Largest)
         Largest = userIn;
printf("The largest number entered was: %dn", Largest);

For some more practice, write a program that will ask a user for input, then print out all the digits of the input.
For an input of 431, the output will be: 4 3 1
Hint: recall that you can use the % operator to obtain the last digit. You can also use a property called truncation to remove the last digit. Observe that if you divide 44 by 10, you get 4.4. However if this is stored as an integer the decimal is chopped off resulting in 4. So use division by 10 to chop off the last digit.

int userIn;
int LastDig;

scanf("%d", &userIn);

   LastDig = userIn % 10;
   printf(" %d ", LastDig);

The way this program will work is, after taking userIn as an input, it checks if it’s zero. If not, it assigns LastDig to be the last digit using the mod operator, than prints it out. It then chops off the last digit from userIn, and goes back to the top of the loop checking if userIn = 0, this will keep looping until you have chopped off the last digit and userIn will equal 0.

Final example
Ask a user to keep inputting values until he enters 0. Return the length of the longest increasing series.
For example for an input of:
1 4 5 6 2 3 4 7 8 9 0
The program should print out 6, since the longest increasing series is: 2 3 4 7 8 9.
Hint:To count the length of any series, have a counter, keep the user input in one variable, than compare to the next input, if the next is larger than increment the counter, once you have a new input less than current, you can assign your current to a variable called LargestSeries, and reset the counter to 1. For every next series, compare the counter to LargestSeries, and if you have a longer series assign it to LargestSeries.

int currValue = 0;
int lastValue = 0;
int largestSet = 0;
int currSet = 0;

printf("Enter list of integers (enter 0 to end) n");
scanf("%d", &currValue);

	if(currValue >= lastValue)
		currSet = 1;
	if(currSet > largestSet)
		largestSet = currSet;

	lastValue = currValue;	
	scanf("%d", &currValue);
printf("The size of the largest increasing series is %d:n", largestSet);

The Do-While
Sometimes, we may wish to check a condition at the end of each iteration as opposed to the beginning. For those instances, we have the do-while loop.


This is identical to the while-loop, the only difference being that the condition is evaluated at the end of each loop cycle.

For Loop
The final iteration structure we’ll look at is called the for loop. A simple way to show this, is first modeling it using a while loop which we already covered.
Let’s write a loop to sum the digits from 0 to 100.

int i = 0;
int sum = 0;

while(i <= 100)
    sum += i;

This code will keep comparing i to 100 and while it’s less than 100 it adds it on to sum. We can write this in a cleaner way with a for-loop.

int i = 0;
int sum = 0;

for(i = 0; i <= 100; i++)
      sum += i;

The fist segment of the for is the initialization, it sets i equal to 0, this only happens once at the beginning of the loop.
Second is the condition and this is checked after each loop cycle, as in the while-loop.
Finally we increment i and this occurs at the end of each loop cycle.
In an updated version of the C language we can declare the counter variable i inside the loop like so:

int sum = 0;

for(int i = 0; i <= 100; i++)
      sum += i;

Nested Loops:
Sometimes, it’s required to have multiple iterations occurring inside other iterations. This is what we call nested loops.
Let’s take a look at an example.
Try printing out the following pattern:


As you can see we first print 0 stars on row 0, 1 star on row 1, 2 stars on row 2, etc.
For this example let’s go to 5 stars on row 5.
The best way to do this problem is by controlling the rows with 1 for-loops that goes from 0 to 5, and then inside this for-loop have a second loop which will control how many stars are printed. Here we want to make sure that the inner for-loop counter is always less than the outer counter. Like so:

for (int i = 0; i < 5; i++)
    for (int j = 0; j <= i; j++)

Note that, the outer loop goes from i = 0 (the first row), incrementing at the end of each cycle, while i is less than 5 (the last row).
At the end of each iteration of the outer loop, we need to print a new line so that the pattern isn’t all printed in a single row.
Now in the inner loop, observe that our counter j starts off at 0, however this only runs while j is less than i.
If we follow this code for a few cycles we have the following behavior:

Code starts: We are in the outer loop.
i set to 0, i < 5? yes!
Continue inside the inner loop.
Now we are inside the inner for-loop.
j set to 0,
is j < i ? 0 <= 0 evaluates to True! Print out a star, and increment j.
Loop back to the top and check the inner loop condition again, is j <= i? 1<=0 is false!
exit the inner loop without incrementing j or printing off the star.
Now we come to the last line of the OUTER loop, print out the new line, and increment i.
Now, i=1
Loop back up to the top of the outer loop, check our condition; i < 5? since i=1, 1 yes! let's jump to the inner loop again.
Since we had exited this loop previously, and are now re-entering this inner loop, j is reinitialized to 0.
j is 0, now we recheck the condition, is j < i? yes!
print out the star, increment j,
now j=1.
Loop back up to the top of the INNER LOOP and check condition. j < i? 1 <= 1 evaluates to true! print off a second star for this row and increment j.
now j=2
Loop back up to the top of the INNER LOOP and check condition. j < i? 2 <= 1 is flase!
exit the inner loop without incrementing j or printing off the star.
Now we come to the last line of the OUTER loop, print out the new line, and increment i.
Now, i=2.
So far our pattern looks like this:

If we repeat what we just said for the next line, we end up with the inner loop running thee times printing off another 3 stars, this will continue until all 5 rows get printed off.

Another Example
Write a program that prompts the user for a digit of any length, iterates through the digit and prints off:
1) the number of even digits
2) the number of odd digits
3) the average of all the digits
4) the largest digit
5) the smallest digit

Note that, this problem is quite simple if we break it down.
The first thing that we need to identify is the problem is asking us to iterate through a digit.
This should have you immediately thinking of having a while-loop and inside, using the mod operator to obtain the last digit, and then use division by 10 to reduce the digit by 1 decimal place. The condition will be, while our digit is still greater than 0. Once we have 0 it means we have iterated through every digit and we’re finished.
Now that we know how we are going to iterate through it, we need to identify what we actually do inside the loop.
The first thing the program is asking for is the number of even digits, any time we need to calculate “the number of” anything, it means we need a counter, you can call it numEven, have it initialized to zero at the beginning. To check if a digit is zero, use the mod operator and mod it by 2. If that results in 0, we have an even digit and we are incrementing the numEven counter. If it doesn’t evaluate to 0, that means the digit is odd. Hence this also can be used to answer part 2) which asks for the number of odd digits. If the %2 doesn’t equal zero, increment a different counter you will have called numOdd.
Part 3) asks for the average of all the digits. By definition, average is calculated by finding the sum of all the digits, and then dividing it by the number of digits. Hence to solve this, we can have a counter called numDig which we can increment at the end of each iteration of the loop after diving by 10 to chop decimal places. Alternatively, observe that for parts 1) and 2) we calculate the number of odd digits, and number of even digits. The sum of those 2 counters will be the sum of all the digits.
To get the sum of all digits, have a variable called digSum, initialize to 0 at the start and keep adding the last digit to it after you perform the % 10 operation on it.
Parts 4) and 5) are similar, as they ask for the largest and smallest digits. Here we need to save the last digit in a variable called LargestDig and SmallestDig, if the next last digit is greater than LargestDig, assign LargestDig to it. If it’s smalled than SmallestDig, assign SmallestDig to it.
Okay, let’s look at the code now.

    int numEven = 0;
	int numOdd = 0;
	int SumDig = 0;
	int lastDig;
	int LargestDig = 0;
	int SmallestDig = 10;
	int userIn = 0;
	int totalDig = 0;
	int numAvg = 0;

	scanf("%d", &userIn);

	while (userIn)
		lastDig = userIn % 10;

		if (lastDig % 2) //this will evaulate to true if the digit is odd, ie. the % isn't 0
		else numEven++;

		if (lastDig >= LargestDig)
			LargestDig = lastDig;
		if (lastDig <= SmallestDig)
			SmallestDig = lastDig;

		SumDig += lastDig;

		userIn /= 10; 

	totalDig = numEven + numOdd;
	numAvg = SumDig / totalDig;
    printf("The number of even digits: %dn", numEven);
	printf("The number of odd digits: %dn", numOdd);
	printf("The average of all digits is: %dn", numAvg);
	printf("The largest digit is: %dn", LargestDig);
	printf("The smallest digit is: %dn", SmallestDig);

One thing to note is in the initialization for the variable holding the smallest digit, I initialized it to 10. This is a small trick to realize since you are comparing single digits to each other, every digit you compare will be between 0 and 9, hence the digit you get using the % operator will always be less than 10.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s