TP-04 DSP Loop
TP-04 DSP Loop
TP-04
Loop Types
in C/C++
C Loop Types
For example, let's say we want to show a message 100 times. Then instead of
writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.
• for loop
• while loop
• do...while loop
1. for loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
Example:
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
Example:
// Print numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
3. do…while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
Example:
// Program to add numbers until the user enters zero
#include <stdio.h>
int main() {
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
Problem1:
A program to get st and en from a user, where st is a starting number and en is an
ending number. Find summation and multiplication of numbers from st to en.
-----
st: 2
en: 5
Problem2:
Write a program to get numbers, say m and n, from a user. Display numbers in
between [m, n] on screen using 'for' loop, 'while loop', and 'do while' loop.
-----
m: 5
n: 100
Problem3:
Write a program to generate 10 random numbers in between [10, 10000]. Display
those randomized numbers on screen.
-----
-----
Problem4:
Write a program to check whether an input number is a primary number or not.
Display "Primary" if it is a primary number. If not primary, display "NOT primary!".
Remark: Keep the program running again so that we can always check another
input number.
Help: A positive integer which is only divisible by 1 and itself is known as primary
number.
For example: 13 is a primary number because it is only divisible by 1 and 13 but, 15
is not primary number because it is divisible by 1, 3, 5 and 15.
-----
Problem5:
Write a program to find maximum number between 10 numbers entered by the user.
You are not allowed to create 10 variables for those numbers.
Hint:
-Use 'for' loop, make it run 10 times
-Get each input inside loop. Check and update max value.
-----