Lecture Looping and Machine Problem 3
Lecture Looping and Machine Problem 3
a. for-loop
for (initialization; condition; incrementation)
{
<statements/s>;
}
where:
Initialization – an assignment statement that is used to set the
loop control variable.
Condition – a relational expression that determines when the loop
will exist by testing the loop-control variable
against some values.
Incrementation – defines how the loop-control variable will
change each time the loop is repeated.
b. while-loop
while (<condition>) {
<statement/s>;
}
where:
statement – can be an empty statement, a single statement or a
block of statement that is to be repeated.
conditions – may be any valid expression. The loop iterates while
the condition is true and program control passes to
the next line following the loop if the condition is
false.
Another way of creating a loop that is not counter controlled
is to use the do-while loop. It is convenient when at least one
repetition of loop body must be ensured.
c. do/while-loop
do{
<statement/s>;
} while (<condition>);
Unlike the for and while loop, the do/while lop checks the
condition at the bottom of the loop. This means that a do/while
loop while always execute at least once. Its common use is in a
menu selection routine by testing a valid response at the bottom of
the loop, where can be reprompt the user until a valid response is
entered.
Nested loop
When one loop is inside of another, the loop is said to be
nested. It provides a means of solving some interesting
programming problems. It is sometimes important to note how
much iteration a nested loop executes. This number is determined
by multiplying the number of times the outer loop iterates by the
number of times the inner loop repeats each time it is executed.
#include<stdio.h>
#include<conio.h>
int ctr;
main()
{
for (ctr=1; ctr<=10; ctr++)
printf("%d \n",ctr);
getch();
}
Example 2. Make a program that will display integers 25, 21, 17,
13, 9 using while loops.
#include<stdio.h>
#include<conio.h>
int ctr;
main()
{
ctr=25;
while (ctr>=9)
{
printf("%d \n",ctr);
ctr = ctr - 4;
}
getch();
}
#include<stdio.h>
#include<conio.h>
int num,ctr,factorial;
main()
{
printf("Enter number [1-7]: ");
scanf("%d",&num);
if (num>=1 && num<=7)
{
factorial=1;
for(ctr=num; ctr>=1; ctr--)
{
factorial=factorial * ctr;
}
printf("Factorial is %d",factorial);
}
else
printf("Overflow!");
getch();
}
c. 5 4321 d. 1 2345
5 432 1 234
5 43 1 23
5 4 1 2
5 1
8. Write a code that will loop by inputting any integer and displays
whether the integer is “POSITIVE” or “NEGATIVE”, and terminate
the loop if the integer is equal to zero using any loops.
10. Design a program that will input ten integers and will compute
and display the sum and average.