Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression. C language supports three types of iterative en statements also known as looping statements.
ITERATIVE STATEMENTS
Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression. C language supports three types of iterative en statements also known as looping statements. They are:
• While loop
• Do-while loop
• For loop
In this section, we will discuss all these statements.
The while loop provides a mechanism to repeat one or more statements while a particular condition is true. Figure 3.6 shows the syntax and general form of representation of a while loop.
In the while loop, the condition is tested before any of the statements in the statement block is executed. If the condition is true, only then the statements will be executed otherwise if the condition is false, the control will jump to statement y, which is the immediate statement outside the while loop block.
From the flowchart, it is clear that we need to constantly update the condition of the while loop. It is this condition which determines when the loop will end. The while loop will execute as long as the condition is true. Note if the condition is never updated and the condition never becomes false then the computer will run into an infinite loop which is never desirable.
Programming Tip: Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression.
Programming Tip: Check that the relational operator is not mistyped as an assignment operator.
A while loop is also referred to as a top-checking loop since control condition is placed as the first line of the code. If the control condition evaluates to false, then the statements enclosed in the loop are never executed.
For example, look at the following code which prints first 10 numbers using a while loop.
#include <stdio.h>
int main()
{
int i = 1; // initialize loop variable
while (i<=10) // test the condition
{ // execute the loop statements
printf("%d", i);
i = i + 1; // condition updated
}
getch();
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Initially i = 1 and is less than 10, i.e., the condition is true, so in the while loop the value of i is printed and the condition is updated so that with every execution of the loop, the condition becomes more approachable. Let us look at some more programming examples that illustrate the use of while loop.
20. Write a program to calculate the sum of first 10 numbers.
#include <stdio.h>
int main()
{
int i = 1, sum = 0;
while (i<=10)
{
sum = sum + i;
i = i + 1; // condition updated
}
printf("\n SUM = %d", sum);
return 0;
}
Output
SUM = 55
21. Write a program to print 20 horizontal asterisks(*).
#include <stdio.h>
int main()
{
int i=1;
while (i<=20)
{
printf("*") ;
i++;
}
return 0;
}
Output
****************************
22. Write a program to calculate the sum of numbers from m to n.
#include <stdio.h>
int main()
{
int n, m, sum =0;
clrscr();
printf("\n Enter the value of m: ");
scanf("%d", &m);
printf("\n Enter the value of n: ");
scanf("%d", &n);
while (m<=n)
{
sum = sum + m;
m = m + 1;
printf("\n SUM = %d", sum);
return 0;
}
Output
Enter if- value of m: 7
Enter the value of n: 11
SUM = 45
23. Write a program to display the largest of 5 numbers using ternary operator.
#include <stdio.h>
#include <conio.h>
int main()
{
int i=1, large = -32768, num;
clrscr();
while(i<=5)
{
printf("\n Enter the number: ");
scanf("%d", &num);
large = num>large?num: large;
i++;
printf("\n The largest of five numbers entered is: %d", large);
return 0;
}
Output
Enter the number : 29
Enter the number : 15
Enter the number : 17
Enter the number : 19
Enter the number : 25
The largest of five numbers entered is: 29
24. Write a program to read the numbers until -1 is no encountered. Also count the negative, positive, and zeros entered by the user.
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int negatives=0, positives=0, zeros=0; clrscr();
clrscr();
printf("\n Enter -1 to exit....");
printf("\n\n Enter any number: ");
scanf("%d", &num);
while (num != -1)
{
if (num>0)
positives++;
else if (num<0)
negatives++;
else
zeroes++;
printf("\n\n Enter any number: ");
scanf("%d", &num);
printf("\n Count of positive numbers entered = %d", positives);
printf("\n Count of negative numbers entered = %d", negatives);
printf("\n Count of zeros entered %d", = zeros);
getch();
return 0;
}
Output
Enter any number: -12
Enter any number: 108
Enter any number: -24
Enter any number: 99
Enter any number: -23
Enter any number: 101
Enter any number: -1
Count of positive numbers entered = 3
Count of negative numbers entered = 3
Count of zeros entered = 0
25. Write a program to calculate the average of numbers entered by the user.
#include <stdio.h>
int main()
{
int num, sum = 0, count = 0;
float avg;
printf("\n Enter any number. Enter -1 to STOP: ");
scanf("%d", &num);
while (num != -1)
{
Programming Tip: Placing a semicolon after the while/for loop in not a syntax error. So it will not be reported by the compiler. However, it is considered to be a logical error as it changes the output of the program.
count++;
sum = sum + num;
printf("\n Enter any number. Enter -1 to STOP: ");
scanf("%d", &num);
}
avg = (float) sum/count;
printf("\n SUM = %d", sum);
printf("\n AVERGAE = %f", avg);
return 0;
}
Output
Enter any number. Enter -1 to STOP: 23
Enter any number. Enter -1 to STOP: 13
Enter any number. Enter -1 to STOP: 3
Enter any number. Enter -1 to STOP: 53
Enter any number. Enter -1 to STOP: 4
Enter any number. Enter -1 to STOP: 63
Enter any number. Enter -1 to STOP: -23
Enter any number. Enter -1 to STOP: -6
Enter any number. Enter -1 to STOP: -1
SUM = 130
AVERAGE = 16.25
Thus, we see that while loop is very useful for designing interactive programs in which the number of times the statements in the loop has to be executed is not known in advance. The program will execute until the user wants to stop by entering -1.
Now look at the code given below which makes the computer hang up in an infinite loop. The code given below is supposed to calculate the average of first 10 numbers, but since the condition never becomes false, the output will not be generated and the intended task will not be performed.
#include <stdio.h>
int main()
{
int i = 0, sum = 0;
float avg = 0.0;
while (i<=10)
{
sum = sum + i;
}
avg = (float) sum/10;
printf("\n The sum of first 10 numbers = %d", sum);
printf("\n The average of first 10 numbers = %f", avg);
return 0;
}
The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the test condition is evaluted at the end of the loop. Now that the test condition is evaluted at the end, this clearly means that the body of the loop gets executed at least one time (even if the condition is false). Figure 3.7 shows the syntax and general form of representation of a do-while loop.
Note that the test condition is enclosed in parentheses and followed by a semicolon. The statements in the statement block are enclosed within curly brackets. The curly brackets are optional if there is only one statement in the body of the do-while loop.
Like the while loop, the do-while loop continues to execute whilst the condition is true. There is no choice whether to execute the loop or not because the loop will be executed at least once irrespective of whether the condition is true or false. Hence, entry in the loop is automatic. There is only one choice: to continue or to exit. The do-while loop will continue to execute while the condition is true and when the condition becomes false, the control will jump to statement following the do-while loop.
Similar to the while loop, the do-while is an indefinite loop as the loop can execute until the user wants to stop. The number of times the loop has to be executed can thus be determined at the run time. However, unlike the while loop, the do-while loop is a bottom-checking loop, since the control expression is placed after the body of the loop.
The major disadvantage of using a do-while loop is that it always executes at least once, even if the user enters some invalid data, the loop will execute. One complete execution of the loop takes place before the first comparison is actually done. However, do-while loops are widely used to print a list of options for a menu-driven programs. For example, look at the following code.
#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("\n %d", i);
i = i + 1;
} while (i<=10);
return 0;
}
What do you think will be the output? The code will print numbers from 1 to 10.
26. Write a program to calculate the average of first n numbers.
Programming Tip: Do not forget to place a semicolon at the end of the do-while statement.
#include <stdio.h>
int main()
{
int n, i = 1, sum = 0;
float avg 0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
do
{
sum = sum + i;
i = i + 1;
} while (i<=n);
avg = (float) sum/n;
printf("\n The sum of first %d numbers = %d", n, sum);
printf("\n The average of first %d numbers %f", n, avg);
return 0;
}
Output
Enter the value of n: 18
The sum of first 18 numbers = 171
The average of first 18 numbers = 9.00
27. Write a program using a do-while loop to display the square and cube of first n natural numbers.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,n;
clrscr();
printf("\n Enter the value of n: ");
scanf("%d", &n);
printf("\n---------------------------------");
i=1;
do
{
printf("\n \t%d \t | \t%d \t \t %ld \t |", i, i*i, i*i*i);
i++;
}while(i<=n) ;
printf("\n---------------------------");
return 0;
}
Programming Tip: Avoid using do- while loop for implementing pre- test loops and use the do-while loop for post-test loops.
Output
Enter the value of n: 5
-------------------------
|1| |1| |1|
|2| |4| |8|
|3| |9| |27|
|4| |16| |64|
|5| |25| |125|
--------------------------
{
sum
sum + i;
i = i + 1;
} while(i<=n) ;
28. Write a program to list all the leap years from 1900 to 2100.
#include <stdio.h>
#include <conio.h>
int main()
{
int m=1900, n=2100;
clrscr();
do
{
Programming Tip: If you want that the body of the loop must get executed at least once, then use the do-while loop.
if (m%4 = =0)
printf("\n %d is a leap year", m);
else
printf("\n %d is not a leap year", m);
m = m+1;
} while (m<=n);
return 0;
}
29. Write a program to read a character until a* is encountered. Also count the number of upper case, lower case, and numbers entered.
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
int lowers = 0, uppers = 0, numbers = 0;
clrscr();
int num;
printf("\n Enter any character: ");
scanf("%c, &ch);
do
{
if (ch >='A' && ch<='Z')
uppers++;
if (ch >='a' && ch<='Z')
lowers++;
if (ch >='0' && ch<='9')
numbers++;
fflush(stdin);
/* The function is used to clear the standard input file. */
printf("\n Enter another character. Enter * to exit.");
scanf("%c", &ch);
} while (ch != '*');
printf("\n Total count of lower case characters entered = %d", lowers);
printf("\n Total count of upper case characters entered = %d", uppers);
printf("\n Total count of numbers entered = %d", numbers);
return 0;
}
Output
Enter any character: 0
Enter another character. Enter * to exit. x
Enter another character. Enter * to exit. F
Enter another character. Enter * to exit. O
Enter another character. Enter * to exit. R
Enter another character. Enter * to exit. d
Enter another character. Enter * to exit. *
Total count of lower case characters entered = 3
Total count of upper case characters entered = 3
Total count of numbers entered = 0
30. Write a program to read the numbers until -1 is encountered. Also calculate the sum and mean of all positive numbers entered and the sum and mean of all negative numbers entered separately.
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
"b") insoa /")ning
int sum_negatives=0, sum_positives=0;
int positives = 0, negatives = 0;
float mean_positives = 0.0, mean_negatives = 0.0;
clrscr();
printf("\n Enter -1 to exit");
printf("\n\n Enter any number: ");
scanf("%d", &num);
do
{
if (num>0)
sum_positives + = num;
positives++;
}
else if (num<0)
{
sum_negatives + = num;
negatives++;
}
printf("\n\n Enter any number: ");
scanf("%d", &num);
} while (num != -1);
mean_positives = (float) sum_positives/positives;
mean_negatives = (float) sum_negatives/negatives;
printf("\n Sum of all positive numbers entered = %d", sum_positives);
printf("\n Mean of all positive numbers entered = %.2f", mean_positives);
printf("\n Sum of all negative numbers entered = %d", sum_negatives);
printf("\n Mean of all negative numbers entered = %.2f", mean_negatives);
return 0;
}
Output
Enter -1 to exit
Enter any number: 9
Enter any number: 8
Enter any number: 7
Enter any number: -6
Enter any number: -5
Enter any number: -4
Enter any number: -1
Sum of all positive numbers entered = 24
Mean of all positive numbers entered = 8.00
Sum of all negative numbers entered = -15
Mean of all negative numbers entered = -5.00
Like the while and do-while loops, the for loop provides a mechanism to repeat a task until a particular condition is true. For loop is usually known as a determinate or definite loop because the programmer knows exactly how many times the loop will repeat. The number of times the loop has to be executed can be determined mathematically by checking the logic of the loop. The syntax and general form of a for loop is given in Figure 3.8.
When a for loop is used, the loop variable is initialized only once. With every iteration of the loop, the value of the loop variable is updated and the condition is checked. If the condition is true, the statement block of the loop is executed, else the statements comprising the statement block of the for loop are skipped and the control jumps to the immediate statement following the for loop body.
In the syntax of the for loop, initialization of the loop variable allows the programmer to give it a value. Second, the condition specifies that while the conditional expression is true the loop should continue to repeat itself. With every iteration, the condition when the loop would terminate should be approachable. So, with every iteration, the loop variable must be updated. Updating the loop variable may include incrementing the loop variable, decrementing the loop variable or setting it to some other value like, i +=2, where i is the loop variable.
Note that every section of the for loop is separated from the other with a semicolon. It is possible that one of the sections may be empty, though the semicolons still have to be there. However, if the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.
The for loop is widely used to execute a single or a group of statements a limited number of times. Another point to consider is that in a for loop, condition is tested before the statements contained in the body are executed. So if the condition does not hold true, then the body of the for loop is not executed.
Look at the following code which prints the first n numbers using a for loop.
#include <stdio.h>
int main()
{
int i, n;
printf("\n Enter the value of n :");
scanf("%d", &n);
for (i=1;i<=n;i++)
printf("\n %d", i);
return 0;
}
Programming Tip: It is a logical error to update the loop control variable in the body of the for loop as well as in the for statement.
In the code, i is the loop variable. Initially, it is initialized with value 1. Suppose the user enters 10 as the value for n. Then the condition is checked, since the condition is true as i is less than n, the statement in the for loop is executed and the value of i is printed. After every iteration, the value of i is incremented. When i = n, the control jumps to the return O statement.
Points to Remember About for Loop
• In a for loop, any or all the expressions can be omitted. In case all the expressions are omitted, then there must be two semicolons in the for statement.
• There must be no semicolon after a for statement. If you do that, then you are sure to get some unexpected results. Consider the following code.
#include <stdio.h>
int main()
{
int i;
for (i=0;i<10; i++);
for (i=10000;i>0; i--);
printf("%d", i);
return 0;
}
In this code, the loop initializes i to o and increments its value. Since a semicolon is placed after the loop, it means that loop does not contain any statement. So even if the condition is true, no statement is executed. The loop continues till i becomes 10 and the moment i=10, the statement following the for loop is executed and the value of i (10) is printed on the screen.
When we place a semicolon after the for statement, then the compiler will not generate any error message. Rather it will treat the statement as a null statement. Usually such type of null statement is used to generate time delays. For example, the following code produces no output and simply delays further processing.
#include <stdio.h>
int main()
{
int i;
for (i=10000;i>0; i--);
printf("%d", i);
return 0;
}
• Multiple initializations must be separated with a comma operator as shown in the following code segment.
#include <stdio.h>
int main()
{
int i, sum;
for (i=0, sum=0;i<10;i++)
sum += i;
printf("%d", sum);
return 0;
}
• If there is no initialization to be done, then the initialization statement can be skipped by giving only semicolon. This is shown in the following code.
Programming Tip: Although we can place the initialization, testing and updating the loop control variable outside the for loop, we must try to avoid it as much as possible.
#include <stdio.h>
int main()
{
int i=0;
for(;i<10;i++)
printf("%d", i);
return 0;
}
• Multiple conditions in the test expression can be tested by using logical operators (&& or ||).
• If the loop controlling variable is updated within the statement block, then the third part can be skipped. This is shown in the code given below.
#include <stdio.h>
int main()
{
int i=0;
for(;i<10;)
printf("%d", i);
i = i + 1;
}
return 0;
}
• Multiple statements can be included in the third part of the for statement by using the comma operator. For example, the for statement given below is valid in C. for (i=0, j=10;i<j; i++, j--)
• The controlling variable can also be incremented/ decremented by values other than 1. This is shown in the code below which prints all odd numbers from 0 to 10.
#include <stdio.h>
int main()
{
}
int i;
for (i=1;i<=10;i+=2)
printf("%d", i);
return 0;
}
• If the for loop contains nothing but two semicolons, that is no initialization, condition testing, and updating of the loop control variable then the for loop may become an infinite loop if no stopping condition is specified in the body of the loop. For example, the following code will infinitely print C Programming on the computer screen.
Programming Tip: Although placing an arithmetic expression in initialization and updating section of the for loop is permissible, try to avoid them as they may cause some round-off and/or truncation errors.
#include <stdio.h>
int main()
{
for(;;)
printf(" C Programming");
return 0;
}
• Never use a floating point variable as the loop control variable. This is because floating point values are just approximations and therefore may result in imprecise values and thus inaccurate test for termination. For example, the following code will result in an infinite loop because of inaccuracies of floating point numbers.
#include <stdio.h>
int main()
{
float i;
for (i=100;i>=10;)
{
printf("%f", i);
i = (float) i/10;
}
return 0;
}
Selecting an appropriate loop Loops can be entry- controlled (also known as pre-test) or exit-controlled (also known as post-test). While in an entry-controlled loop, condition is tested before the loop starts, an exit-controlled loop, on the other hand, tests the condition after the loop is executed. If the condition is not met in entry-controlled loop, then the loop will never execute. However, in case of post-test, the body of the loop is executed unconditionally for the first time.
If your requirement is to have a pre-test loop, then choose either for loop or while loop. In case you need to have a post-test loop then choose a do-while loop.
Look at Table 3.2 which shows a comparison between a pre-test loop and a post-test loop.
When we know in advance the number of times the loop should be executed, we use a counter-controlled loop. The counter is a variable that must be initialized, tested, and updated for performing the loop operations. Such a counter-controlled loop in which the counter is assigned a constant or a value is also known as a definite repetition loop.
When we do not know in advance the number of times the loop will be executed, we use a sentinel-controlled loop. In such a loop, a special value called the sentinel value is used to change the loop control expression from true to false. For example, when data is read from the user, the user may be notified that when they want the execution to stop, they may enter -1. This value is called a sentinel value. A sentinel-controlled loop is often useful for indefinite repetition loops.
Programming in C: Unit I (c): Decision Control and Looping Statements : Tag: : with Example C Programs - Iterative Statements
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation