This is the first of 2 posts on conditions and iterations. Essentially this means conditional execution and repetitive operations. Using arrays and a variable to index into the array we can process an entire array without writing code which specifically accesses each element in the array.
Other than using arrays (which I’ve described in an earlier post), there are 2 new things in this post.
if(condition to evaluate)
{
… one or more statements
}
else // can also be else if (condition to evaluate)
{
… one or more statements
}and
for(init;condition to evaluate;execute on loop)
{
… one or more statements
}
In both the if and the for statement is condition to evaluate which consists of the logical operations described in this post. The code that is between the first set of braces after the if are executed if the logical operation produces a true result. If there is an else associated with the if then code between the set of braces after the else are executed.
In C, for is a looping (or iterating) statement. In the for statement, the init is code that is executed before the loop begins. The code between the braces is executed as 1 iteration of the loop. At the end of each iteration, the code in execute on loop is executed. Then the for statement evaluates condition to evaluate and if it evaluates to true then it re-executes the loop. This continues until the condition to evaluate evaluates to false.
Here is the sample code for this tutorial. It is commented as well.
#include <stdio.h>
/* Sample Program for C Tutorials for the home ed student.
Demonstrating the use of an integer array and a character
array.
Ron R.
July 2005
*/int main()
{
// some variables for iteration
int i,j;
// some variables to track integer values
int max,min,sum;
// preassign values to integer array
int example[10] = {45,22,67,987,423,11,45,76,16,91};
// space for an extra character has to be left on the end
char sentence[13] = “Hello World!”;
// show the sentence one character at a time
for(i=0;i<13;i++)
{
/* %c = print a character
then printf needs a piece of data for each control string
*/
printf(“%c “,sentence[i]);
}
/* print integer values and calculate values
the next statement is called a compound assignment
sum, min, max will all be set to the value in example[0]
*/
sum = min = max = example[0];
printf(“\n”); // some spacing
for(j=0;j<10;j++)
{
// print it – %i = print an integer
printf(“%i:%i\n”,j,example[j]);
/* if this is not the first element in the array we have to do some
other processing
*/
if(j != 0)
{
// add to sum
sum += example[j];
// if its smaller than current min then replace
if(example[j] < min)
{
min = example[j];
}
// it will only be bigger when it is not smaller than min
else if (example[j] > max)
{
max = example[j];
}
}
}
// print results
printf(“smallest #: %i\n”,min);
printf(“largest #: %i\n”,max);
printf(“sum of #s: %i\n”,sum);
return 0;
}
Try it. Then change the numbers and see what happens. Put in a different sentence.
Recent Comments