Professional Documents
Culture Documents
Lab 5
Lab 5
Lab 5
Applied Sciences
Computing Fundamentals
Laboratory Exercise-05
Loops
Activity 1
Write a program in C to display the n terms of odd natural number and their
sum.
Test Data
Input number of terms : 10
Expected Output :
The odd numbers are :1 3 5 7 9 11 13 15 17 19
The Sum of odd Natural Number upto 10 terms : 100
Activity 2
Write a program in C to display the pattern like right angle triangle with a
number.
Activity 3
Write a program in C to display the n terms of square natural number and their
sum.
Break Statement
1 4 9 16 ... n Terms
Test Data:
Input the number of terms : 5
Expected Output:
The square natural upto 5 terms are :1 4 9 16 25
The Sum of Square Natural Number upto 5 terms = 55
Break
The break is a keyword in C which is used to bring the program control out of the loop.
The break statement is used inside loops or switch statement. The break statement breaks the
loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then
proceeds to outer loops.
Example-01
#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num);
if (num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
Output:
value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop
#include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf("var: %d\n", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
return 0;
}
Output:
var: 100
var: 99
Out of for-loop
Activity 4
Write a program in C to read 10 numbers from keyboard and find their sum. If
sum exceeds the value of 100 program should break otherwise find the
average.
Activity 5
Activity 6
Continue Statement
The continue statement in C programming works somewhat like the break statement. Instead
of forcing termination, it forces the next iteration of the loop to take place, skipping any code
in between. For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute.
Example-03
#include <stdio.h>
int main()
{
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
return 0;
}
Output:
10 9 8 6 5 4 3 2 1 0
Example-04
#include <stdio.h>
int main()
{
int j=0;
do
Output:
012345689
Activity 7
Write a program in C to read 20 numbers from user using for loop, count the
odd numbers and skip the even numbers by using continue statement.
Also find the sum, average and largest odd number from the entered
numbers.
Activity 8
Modify the program in activity 4 to count the prime numbers from the 20
entered numbers by user and skip the other ones.